3 * Copyright (c) 2003 Thomas Raivio
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "avio_internal.h"
34 #include "libavcodec/ac3_parser.h"
35 #include "libavcodec/dnxhddata.h"
36 #include "libavcodec/flac.h"
37 #include "libavcodec/get_bits.h"
38 #include "libavcodec/put_bits.h"
39 #include "libavcodec/vc1_common.h"
40 #include "libavcodec/raw.h"
42 #include "libavutil/avstring.h"
43 #include "libavutil/intfloat.h"
44 #include "libavutil/mathematics.h"
45 #include "libavutil/libm.h"
46 #include "libavutil/opt.h"
47 #include "libavutil/dict.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/timecode.h"
50 #include "libavutil/color_utils.h"
56 static const AVOption options[] = {
57 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
58 { "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" },
59 { "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 },
60 { "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" },
61 { "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" },
62 { "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" },
63 { "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" },
64 { "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" },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 { "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" },
73 { "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" },
74 { "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" },
75 { "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" },
76 { "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" },
77 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
78 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
79 { "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},
80 { "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},
81 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
82 { "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},
83 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
84 { "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},
85 { "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},
86 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
87 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
88 { "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},
89 { "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},
90 { "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 },
91 { "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 },
92 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
93 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
94 { "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},
95 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
99 #define MOV_CLASS(flavor)\
100 static const AVClass flavor ## _muxer_class = {\
101 .class_name = #flavor " muxer",\
102 .item_name = av_default_item_name,\
104 .version = LIBAVUTIL_VERSION_INT,\
107 static int get_moov_size(AVFormatContext *s);
109 static int utf8len(const uint8_t *b)
114 GET_UTF8(val, *b++, return -1;)
120 //FIXME support 64 bit variant with wide placeholders
121 static int64_t update_size(AVIOContext *pb, int64_t pos)
123 int64_t curpos = avio_tell(pb);
124 avio_seek(pb, pos, SEEK_SET);
125 avio_wb32(pb, curpos - pos); /* rewrite size */
126 avio_seek(pb, curpos, SEEK_SET);
131 static int co64_required(const MOVTrack *track)
133 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
138 /* Chunk offset atom */
139 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
142 int mode64 = co64_required(track); // use 32 bit size variant if possible
143 int64_t pos = avio_tell(pb);
144 avio_wb32(pb, 0); /* size */
146 ffio_wfourcc(pb, "co64");
148 ffio_wfourcc(pb, "stco");
149 avio_wb32(pb, 0); /* version & flags */
150 avio_wb32(pb, track->chunkCount); /* entry count */
151 for (i = 0; i < track->entry; i++) {
152 if (!track->cluster[i].chunkNum)
155 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
157 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
159 return update_size(pb, pos);
162 /* Sample size atom */
163 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
166 int i, j, entries = 0, tst = -1, oldtst = -1;
168 int64_t pos = avio_tell(pb);
169 avio_wb32(pb, 0); /* size */
170 ffio_wfourcc(pb, "stsz");
171 avio_wb32(pb, 0); /* version & flags */
173 for (i = 0; i < track->entry; i++) {
174 tst = track->cluster[i].size / track->cluster[i].entries;
175 if (oldtst != -1 && tst != oldtst)
178 entries += track->cluster[i].entries;
180 if (equalChunks && track->entry) {
181 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
182 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
183 avio_wb32(pb, sSize); // sample size
184 avio_wb32(pb, entries); // sample count
186 avio_wb32(pb, 0); // sample size
187 avio_wb32(pb, entries); // sample count
188 for (i = 0; i < track->entry; i++) {
189 for (j = 0; j < track->cluster[i].entries; j++) {
190 avio_wb32(pb, track->cluster[i].size /
191 track->cluster[i].entries);
195 return update_size(pb, pos);
198 /* Sample to chunk atom */
199 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
201 int index = 0, oldval = -1, i;
202 int64_t entryPos, curpos;
204 int64_t pos = avio_tell(pb);
205 avio_wb32(pb, 0); /* size */
206 ffio_wfourcc(pb, "stsc");
207 avio_wb32(pb, 0); // version & flags
208 entryPos = avio_tell(pb);
209 avio_wb32(pb, track->chunkCount); // entry count
210 for (i = 0; i < track->entry; i++) {
211 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
212 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
213 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
214 avio_wb32(pb, 0x1); // sample description index
215 oldval = track->cluster[i].samples_in_chunk;
219 curpos = avio_tell(pb);
220 avio_seek(pb, entryPos, SEEK_SET);
221 avio_wb32(pb, index); // rewrite size
222 avio_seek(pb, curpos, SEEK_SET);
224 return update_size(pb, pos);
227 /* Sync sample atom */
228 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
230 int64_t curpos, entryPos;
232 int64_t pos = avio_tell(pb);
233 avio_wb32(pb, 0); // size
234 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
235 avio_wb32(pb, 0); // version & flags
236 entryPos = avio_tell(pb);
237 avio_wb32(pb, track->entry); // entry count
238 for (i = 0; i < track->entry; i++) {
239 if (track->cluster[i].flags & flag) {
240 avio_wb32(pb, i + 1);
244 curpos = avio_tell(pb);
245 avio_seek(pb, entryPos, SEEK_SET);
246 avio_wb32(pb, index); // rewrite size
247 avio_seek(pb, curpos, SEEK_SET);
248 return update_size(pb, pos);
251 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
253 avio_wb32(pb, 0x11); /* size */
254 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
255 else ffio_wfourcc(pb, "damr");
256 ffio_wfourcc(pb, "FFMP");
257 avio_w8(pb, 0); /* decoder version */
259 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
260 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
261 avio_w8(pb, 0x01); /* Frames per sample */
265 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
270 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
272 if (track->vos_len < 7)
276 ffio_wfourcc(pb, "dac3");
278 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
279 fscod = get_bits(&gbc, 2);
280 frmsizecod = get_bits(&gbc, 6);
281 bsid = get_bits(&gbc, 5);
282 bsmod = get_bits(&gbc, 3);
283 acmod = get_bits(&gbc, 3);
285 skip_bits(&gbc, 2); // dsurmod
287 if ((acmod & 1) && acmod != 1)
288 skip_bits(&gbc, 2); // cmixlev
290 skip_bits(&gbc, 2); // surmixlev
292 lfeon = get_bits1(&gbc);
294 init_put_bits(&pbc, buf, sizeof(buf));
295 put_bits(&pbc, 2, fscod);
296 put_bits(&pbc, 5, bsid);
297 put_bits(&pbc, 3, bsmod);
298 put_bits(&pbc, 3, acmod);
299 put_bits(&pbc, 1, lfeon);
300 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
301 put_bits(&pbc, 5, 0); // reserved
303 flush_put_bits(&pbc);
304 avio_write(pb, buf, sizeof(buf));
314 /* Layout of the EC3SpecificBox */
315 /* maximum bitrate */
317 /* number of independent substreams */
320 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
322 /* bit stream identification 5 bits */
324 /* one bit reserved */
325 /* audio service mixing (not supported yet) 1 bit */
326 /* bit stream mode 3 bits */
328 /* audio coding mode 3 bits */
330 /* sub woofer on 1 bit */
332 /* 3 bits reserved */
333 /* number of dependent substreams associated with this substream 4 bits */
335 /* channel locations of the dependent substream(s), if any, 9 bits */
337 /* if there is no dependent substream, then one bit reserved instead */
338 } substream[1]; /* TODO: support 8 independent substreams */
341 #if CONFIG_AC3_PARSER
342 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
345 AC3HeaderInfo tmp, *hdr = &tmp;
346 struct eac3_info *info;
349 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
350 return AVERROR(ENOMEM);
351 info = track->eac3_priv;
353 init_get_bits(&gbc, pkt->data, pkt->size * 8);
354 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
355 /* drop the packets until we see a good one */
357 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
360 return AVERROR_INVALIDDATA;
363 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
364 num_blocks = hdr->num_blocks;
366 if (!info->ec3_done) {
367 /* AC-3 substream must be the first one */
368 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
369 return AVERROR(EINVAL);
371 /* this should always be the case, given that our AC-3 parser
372 * concatenates dependent frames to their independent parent */
373 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
374 /* substream ids must be incremental */
375 if (hdr->substreamid > info->num_ind_sub + 1)
376 return AVERROR(EINVAL);
378 if (hdr->substreamid == info->num_ind_sub + 1) {
379 //info->num_ind_sub++;
380 avpriv_request_sample(track->par, "Multiple independent substreams");
381 return AVERROR_PATCHWELCOME;
382 } else if (hdr->substreamid < info->num_ind_sub ||
383 hdr->substreamid == 0 && info->substream[0].bsid) {
389 /* fill the info needed for the "dec3" atom */
390 info->substream[hdr->substreamid].fscod = hdr->sr_code;
391 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
392 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
393 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
394 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
396 /* Parse dependent substream(s), if any */
397 if (pkt->size != hdr->frame_size) {
398 int cumul_size = hdr->frame_size;
399 int parent = hdr->substreamid;
401 while (cumul_size != pkt->size) {
403 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
404 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
405 return AVERROR_INVALIDDATA;
406 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
407 return AVERROR(EINVAL);
408 cumul_size += hdr->frame_size;
409 info->substream[parent].num_dep_sub++;
411 /* header is parsed up to lfeon, but custom channel map may be needed */
414 /* skip volume control params */
415 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
416 skip_bits(&gbc, 5); // skip dialog normalization
417 if (get_bits1(&gbc)) {
418 skip_bits(&gbc, 8); // skip compression gain word
421 /* get the dependent stream channel map, if exists */
423 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
425 info->substream[parent].chan_loc |= hdr->channel_mode;
431 if (!info->num_blocks && num_blocks == 6)
433 else if (info->num_blocks + num_blocks > 6)
434 return AVERROR_INVALIDDATA;
436 if (!info->num_blocks) {
438 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
440 info->num_blocks = num_blocks;
444 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
446 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
447 info->num_blocks += num_blocks;
448 info->pkt.duration += pkt->duration;
449 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
451 if (info->num_blocks != 6)
453 av_packet_unref(pkt);
454 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
456 av_packet_unref(&info->pkt);
457 info->num_blocks = 0;
464 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
468 struct eac3_info *info;
471 if (!track->eac3_priv)
472 return AVERROR(EINVAL);
474 info = track->eac3_priv;
475 size = 2 + 4 * (info->num_ind_sub + 1);
476 buf = av_malloc(size);
478 size = AVERROR(ENOMEM);
482 init_put_bits(&pbc, buf, size);
483 put_bits(&pbc, 13, info->data_rate);
484 put_bits(&pbc, 3, info->num_ind_sub);
485 for (i = 0; i <= info->num_ind_sub; i++) {
486 put_bits(&pbc, 2, info->substream[i].fscod);
487 put_bits(&pbc, 5, info->substream[i].bsid);
488 put_bits(&pbc, 1, 0); /* reserved */
489 put_bits(&pbc, 1, 0); /* asvc */
490 put_bits(&pbc, 3, info->substream[i].bsmod);
491 put_bits(&pbc, 3, info->substream[i].acmod);
492 put_bits(&pbc, 1, info->substream[i].lfeon);
493 put_bits(&pbc, 5, 0); /* reserved */
494 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
495 if (!info->substream[i].num_dep_sub) {
496 put_bits(&pbc, 1, 0); /* reserved */
499 put_bits(&pbc, 9, info->substream[i].chan_loc);
502 flush_put_bits(&pbc);
504 avio_wb32(pb, size + 8);
505 ffio_wfourcc(pb, "dec3");
506 avio_write(pb, buf, size);
511 av_packet_unref(&info->pkt);
512 av_freep(&track->eac3_priv);
518 * This function writes extradata "as is".
519 * Extradata must be formatted like a valid atom (with size and tag).
521 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
523 avio_write(pb, track->par->extradata, track->par->extradata_size);
524 return track->par->extradata_size;
527 static int mov_write_enda_tag(AVIOContext *pb)
530 ffio_wfourcc(pb, "enda");
531 avio_wb16(pb, 1); /* little endian */
535 static int mov_write_enda_tag_be(AVIOContext *pb)
538 ffio_wfourcc(pb, "enda");
539 avio_wb16(pb, 0); /* big endian */
543 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
548 avio_w8(pb, (size >> (7 * i)) | 0x80);
549 avio_w8(pb, size & 0x7F);
552 static unsigned compute_avg_bitrate(MOVTrack *track)
556 if (!track->track_duration)
558 for (i = 0; i < track->entry; i++)
559 size += track->cluster[i].size;
560 return size * 8 * track->timescale / track->track_duration;
563 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
565 AVCPBProperties *props;
566 int64_t pos = avio_tell(pb);
567 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
568 unsigned avg_bitrate;
570 avio_wb32(pb, 0); // size
571 ffio_wfourcc(pb, "esds");
572 avio_wb32(pb, 0); // Version
575 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
576 avio_wb16(pb, track->track_id);
577 avio_w8(pb, 0x00); // flags (= no flags)
579 // DecoderConfig descriptor
580 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
582 // Object type indication
583 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
584 track->par->codec_id == AV_CODEC_ID_MP3) &&
585 track->par->sample_rate > 24000)
586 avio_w8(pb, 0x6B); // 11172-3
588 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
590 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
591 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
592 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
593 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
594 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
595 avio_w8(pb, 0x15); // flags (= Audiostream)
597 avio_w8(pb, 0x11); // flags (= Visualstream)
599 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
602 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
604 avg_bitrate = compute_avg_bitrate(track);
605 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)
606 avio_wb32(pb, avg_bitrate);
608 if (track->vos_len) {
609 // DecoderSpecific info descriptor
610 put_descr(pb, 0x05, track->vos_len);
611 avio_write(pb, track->vos_data, track->vos_len);
615 put_descr(pb, 0x06, 1);
617 return update_size(pb, pos);
620 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
622 return codec_id == AV_CODEC_ID_PCM_S24LE ||
623 codec_id == AV_CODEC_ID_PCM_S32LE ||
624 codec_id == AV_CODEC_ID_PCM_F32LE ||
625 codec_id == AV_CODEC_ID_PCM_F64LE;
628 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
630 return codec_id == AV_CODEC_ID_PCM_S24BE ||
631 codec_id == AV_CODEC_ID_PCM_S32BE ||
632 codec_id == AV_CODEC_ID_PCM_F32BE ||
633 codec_id == AV_CODEC_ID_PCM_F64BE;
636 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
639 int64_t pos = avio_tell(pb);
641 avio_wl32(pb, track->tag); // store it byteswapped
642 track->par->codec_tag = av_bswap16(track->tag >> 16);
643 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
645 return update_size(pb, pos);
648 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
651 int64_t pos = avio_tell(pb);
653 ffio_wfourcc(pb, "wfex");
654 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
656 return update_size(pb, pos);
659 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
661 int64_t pos = avio_tell(pb);
663 ffio_wfourcc(pb, "dfLa");
664 avio_w8(pb, 0); /* version */
665 avio_wb24(pb, 0); /* flags */
667 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
668 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
669 return AVERROR_INVALIDDATA;
671 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
672 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
673 avio_wb24(pb, track->par->extradata_size); /* Length */
674 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
676 return update_size(pb, pos);
679 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
681 uint32_t layout_tag, bitmap;
682 int64_t pos = avio_tell(pb);
684 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
685 track->par->channel_layout,
688 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
689 "lack of channel information\n");
693 if (track->multichannel_as_mono)
696 avio_wb32(pb, 0); // Size
697 ffio_wfourcc(pb, "chan"); // Type
698 avio_w8(pb, 0); // Version
699 avio_wb24(pb, 0); // Flags
700 avio_wb32(pb, layout_tag); // mChannelLayoutTag
701 avio_wb32(pb, bitmap); // mChannelBitmap
702 avio_wb32(pb, 0); // mNumberChannelDescriptions
704 return update_size(pb, pos);
707 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
709 int64_t pos = avio_tell(pb);
711 avio_wb32(pb, 0); /* size */
712 ffio_wfourcc(pb, "wave");
714 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
715 avio_wb32(pb, 12); /* size */
716 ffio_wfourcc(pb, "frma");
717 avio_wl32(pb, track->tag);
720 if (track->par->codec_id == AV_CODEC_ID_AAC) {
721 /* useless atom needed by mplayer, ipod, not needed by quicktime */
722 avio_wb32(pb, 12); /* size */
723 ffio_wfourcc(pb, "mp4a");
725 mov_write_esds_tag(pb, track);
726 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
727 mov_write_enda_tag(pb);
728 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
729 mov_write_enda_tag_be(pb);
730 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
731 mov_write_amr_tag(pb, track);
732 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
733 mov_write_ac3_tag(pb, track);
734 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
735 mov_write_eac3_tag(pb, track);
736 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
737 track->par->codec_id == AV_CODEC_ID_QDM2) {
738 mov_write_extradata_tag(pb, track);
739 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
740 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
741 mov_write_ms_tag(s, pb, track);
744 avio_wb32(pb, 8); /* size */
745 avio_wb32(pb, 0); /* null tag */
747 return update_size(pb, pos);
750 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
753 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
754 int unescaped_size, seq_found = 0;
755 int level = 0, interlace = 0;
756 int packet_seq = track->vc1_info.packet_seq;
757 int packet_entry = track->vc1_info.packet_entry;
758 int slices = track->vc1_info.slices;
761 if (track->start_dts == AV_NOPTS_VALUE) {
762 /* No packets written yet, vc1_info isn't authoritative yet. */
763 /* Assume inline sequence and entry headers. */
764 packet_seq = packet_entry = 1;
765 av_log(NULL, AV_LOG_WARNING,
766 "moov atom written before any packets, unable to write correct "
767 "dvc1 atom. Set the delay_moov flag to fix this.\n");
770 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
772 return AVERROR(ENOMEM);
773 start = find_next_marker(track->vos_data, end);
774 for (next = start; next < end; start = next) {
777 next = find_next_marker(start + 4, end);
778 size = next - start - 4;
781 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
782 init_get_bits(&gb, unescaped, 8 * unescaped_size);
783 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
784 int profile = get_bits(&gb, 2);
785 if (profile != PROFILE_ADVANCED) {
787 return AVERROR(ENOSYS);
790 level = get_bits(&gb, 3);
791 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
793 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
794 skip_bits(&gb, 1); /* broadcast */
795 interlace = get_bits1(&gb);
796 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
801 return AVERROR(ENOSYS);
804 init_put_bits(&pbc, buf, 7);
805 /* VC1DecSpecStruc */
806 put_bits(&pbc, 4, 12); /* profile - advanced */
807 put_bits(&pbc, 3, level);
808 put_bits(&pbc, 1, 0); /* reserved */
809 /* VC1AdvDecSpecStruc */
810 put_bits(&pbc, 3, level);
811 put_bits(&pbc, 1, 0); /* cbr */
812 put_bits(&pbc, 6, 0); /* reserved */
813 put_bits(&pbc, 1, !interlace); /* no interlace */
814 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
815 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
816 put_bits(&pbc, 1, !slices); /* no slice code */
817 put_bits(&pbc, 1, 0); /* no bframe */
818 put_bits(&pbc, 1, 0); /* reserved */
821 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
822 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
824 put_bits32(&pbc, 0xffffffff);
826 flush_put_bits(&pbc);
833 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
835 uint8_t buf[7] = { 0 };
838 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
841 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
842 ffio_wfourcc(pb, "dvc1");
843 avio_write(pb, buf, sizeof(buf));
844 avio_write(pb, track->vos_data, track->vos_len);
849 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
851 avio_wb32(pb, track->vos_len + 8);
852 ffio_wfourcc(pb, "glbl");
853 avio_write(pb, track->vos_data, track->vos_len);
854 return 8 + track->vos_len;
858 * Compute flags for 'lpcm' tag.
859 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
861 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
864 case AV_CODEC_ID_PCM_F32BE:
865 case AV_CODEC_ID_PCM_F64BE:
867 case AV_CODEC_ID_PCM_F32LE:
868 case AV_CODEC_ID_PCM_F64LE:
870 case AV_CODEC_ID_PCM_U8:
872 case AV_CODEC_ID_PCM_S16BE:
873 case AV_CODEC_ID_PCM_S24BE:
874 case AV_CODEC_ID_PCM_S32BE:
876 case AV_CODEC_ID_PCM_S8:
877 case AV_CODEC_ID_PCM_S16LE:
878 case AV_CODEC_ID_PCM_S24LE:
879 case AV_CODEC_ID_PCM_S32LE:
886 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
890 if (cluster_idx >= track->entry)
893 if (cluster_idx + 1 == track->entry)
894 next_dts = track->track_duration + track->start_dts;
896 next_dts = track->cluster[cluster_idx + 1].dts;
898 next_dts -= track->cluster[cluster_idx].dts;
900 av_assert0(next_dts >= 0);
901 av_assert0(next_dts <= INT_MAX);
906 static int get_samples_per_packet(MOVTrack *track)
908 int i, first_duration;
910 // return track->par->frame_size;
912 /* use 1 for raw PCM */
913 if (!track->audio_vbr)
916 /* check to see if duration is constant for all clusters */
919 first_duration = get_cluster_duration(track, 0);
920 for (i = 1; i < track->entry; i++) {
921 if (get_cluster_duration(track, i) != first_duration)
924 return first_duration;
927 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
929 int64_t pos = avio_tell(pb);
931 uint32_t tag = track->tag;
933 if (track->mode == MODE_MOV) {
934 if (track->timescale > UINT16_MAX) {
935 if (mov_get_lpcm_flags(track->par->codec_id))
936 tag = AV_RL32("lpcm");
938 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
939 mov_pcm_be_gt16(track->par->codec_id) ||
940 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
941 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
942 track->par->codec_id == AV_CODEC_ID_QDM2) {
947 avio_wb32(pb, 0); /* size */
948 if (mov->encryption_scheme != MOV_ENC_NONE) {
949 ffio_wfourcc(pb, "enca");
951 avio_wl32(pb, tag); // store it byteswapped
953 avio_wb32(pb, 0); /* Reserved */
954 avio_wb16(pb, 0); /* Reserved */
955 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
957 /* SoundDescription */
958 avio_wb16(pb, version); /* Version */
959 avio_wb16(pb, 0); /* Revision level */
960 avio_wb32(pb, 0); /* Reserved */
965 avio_wb16(pb, 0xfffe);
967 avio_wb32(pb, 0x00010000);
969 avio_wb64(pb, av_double2int(track->par->sample_rate));
970 avio_wb32(pb, track->par->channels);
971 avio_wb32(pb, 0x7F000000);
972 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
973 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
974 avio_wb32(pb, track->sample_size);
975 avio_wb32(pb, get_samples_per_packet(track));
977 if (track->mode == MODE_MOV) {
978 avio_wb16(pb, track->par->channels);
979 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
980 track->par->codec_id == AV_CODEC_ID_PCM_S8)
981 avio_wb16(pb, 8); /* bits per sample */
982 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
983 avio_wb16(pb, track->par->bits_per_coded_sample);
986 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
987 } else { /* reserved for mp4/3gp */
988 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
989 avio_wb16(pb, track->par->channels);
990 avio_wb16(pb, track->par->bits_per_raw_sample);
998 avio_wb16(pb, 0); /* packet size (= 0) */
999 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1000 track->par->sample_rate : 0);
1001 avio_wb16(pb, 0); /* Reserved */
1004 if (version == 1) { /* SoundDescription V1 extended info */
1005 if (mov_pcm_le_gt16(track->par->codec_id) ||
1006 mov_pcm_be_gt16(track->par->codec_id))
1007 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1009 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1010 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1011 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1012 avio_wb32(pb, 2); /* Bytes per sample */
1015 if (track->mode == MODE_MOV &&
1016 (track->par->codec_id == AV_CODEC_ID_AAC ||
1017 track->par->codec_id == AV_CODEC_ID_AC3 ||
1018 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1019 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1020 track->par->codec_id == AV_CODEC_ID_ALAC ||
1021 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1022 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1023 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1024 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1025 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1026 mov_write_wave_tag(s, pb, track);
1027 else if (track->tag == MKTAG('m','p','4','a'))
1028 mov_write_esds_tag(pb, track);
1029 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1030 mov_write_amr_tag(pb, track);
1031 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1032 mov_write_ac3_tag(pb, track);
1033 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1034 mov_write_eac3_tag(pb, track);
1035 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1036 mov_write_extradata_tag(pb, track);
1037 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1038 mov_write_wfex_tag(s, pb, track);
1039 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1040 mov_write_dfla_tag(pb, track);
1041 else if (track->vos_len > 0)
1042 mov_write_glbl_tag(pb, track);
1044 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1045 mov_write_chan_tag(s, pb, track);
1047 if (mov->encryption_scheme != MOV_ENC_NONE) {
1048 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1051 return update_size(pb, pos);
1054 static int mov_write_d263_tag(AVIOContext *pb)
1056 avio_wb32(pb, 0xf); /* size */
1057 ffio_wfourcc(pb, "d263");
1058 ffio_wfourcc(pb, "FFMP");
1059 avio_w8(pb, 0); /* decoder version */
1060 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1061 avio_w8(pb, 0xa); /* level */
1062 avio_w8(pb, 0); /* profile */
1066 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1068 int64_t pos = avio_tell(pb);
1071 ffio_wfourcc(pb, "avcC");
1072 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1073 return update_size(pb, pos);
1076 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1078 int64_t pos = avio_tell(pb);
1081 ffio_wfourcc(pb, "vpcC");
1082 avio_wb32(pb, 0); /* version & flags */
1083 ff_isom_write_vpcc(s, pb, track->par);
1084 return update_size(pb, pos);
1087 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1089 int64_t pos = avio_tell(pb);
1092 ffio_wfourcc(pb, "hvcC");
1093 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1094 return update_size(pb, pos);
1097 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1098 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1103 int display_width = track->par->width;
1105 if (track->vos_data && track->vos_len > 0x29) {
1106 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1107 /* looks like a DNxHD bit stream */
1108 interlaced = (track->vos_data[5] & 2);
1109 cid = AV_RB32(track->vos_data + 0x28);
1111 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1115 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1119 avio_wb32(pb, 24); /* size */
1120 ffio_wfourcc(pb, "ACLR");
1121 ffio_wfourcc(pb, "ACLR");
1122 ffio_wfourcc(pb, "0001");
1123 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1124 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1125 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1126 } else { /* Full range (0-255) */
1127 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1129 avio_wb32(pb, 0); /* unknown */
1131 if (track->tag == MKTAG('A','V','d','h')) {
1133 ffio_wfourcc(pb, "ADHR");
1134 ffio_wfourcc(pb, "0001");
1136 avio_wb32(pb, 0); /* unknown */
1137 avio_wb32(pb, 1); /* unknown */
1138 avio_wb32(pb, 0); /* unknown */
1139 avio_wb32(pb, 0); /* unknown */
1143 avio_wb32(pb, 24); /* size */
1144 ffio_wfourcc(pb, "APRG");
1145 ffio_wfourcc(pb, "APRG");
1146 ffio_wfourcc(pb, "0001");
1147 avio_wb32(pb, 1); /* unknown */
1148 avio_wb32(pb, 0); /* unknown */
1150 avio_wb32(pb, 120); /* size */
1151 ffio_wfourcc(pb, "ARES");
1152 ffio_wfourcc(pb, "ARES");
1153 ffio_wfourcc(pb, "0001");
1154 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1155 if ( track->par->sample_aspect_ratio.num > 0
1156 && track->par->sample_aspect_ratio.den > 0)
1157 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1158 avio_wb32(pb, display_width);
1159 /* values below are based on samples created with quicktime and avid codecs */
1161 avio_wb32(pb, track->par->height / 2);
1162 avio_wb32(pb, 2); /* unknown */
1163 avio_wb32(pb, 0); /* unknown */
1164 avio_wb32(pb, 4); /* unknown */
1166 avio_wb32(pb, track->par->height);
1167 avio_wb32(pb, 1); /* unknown */
1168 avio_wb32(pb, 0); /* unknown */
1169 if (track->par->height == 1080)
1170 avio_wb32(pb, 5); /* unknown */
1172 avio_wb32(pb, 6); /* unknown */
1175 for (i = 0; i < 10; i++)
1181 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1184 ffio_wfourcc(pb, "DpxE");
1185 if (track->par->extradata_size >= 12 &&
1186 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1187 avio_wb32(pb, track->par->extradata[11]);
1194 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1196 int tag = track->par->codec_tag;
1198 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
1201 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1202 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1203 else if (track->par->codec_id == AV_CODEC_ID_VP9) tag = MKTAG('v','p','0','9');
1204 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1205 else if (track->par->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1206 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1207 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1208 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1209 else if (track->par->codec_id == AV_CODEC_ID_FLAC) tag = MKTAG('f','L','a','C');
1210 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1211 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1212 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1217 static const AVCodecTag codec_ipod_tags[] = {
1218 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1219 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1220 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1221 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1222 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1223 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1224 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1225 { AV_CODEC_ID_NONE, 0 },
1228 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1230 int tag = track->par->codec_tag;
1232 // keep original tag for subs, ipod supports both formats
1233 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1234 (tag == MKTAG('t', 'x', '3', 'g') ||
1235 tag == MKTAG('t', 'e', 'x', 't'))))
1236 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
1238 if (!av_match_ext(s->filename, "m4a") &&
1239 !av_match_ext(s->filename, "m4b") &&
1240 !av_match_ext(s->filename, "m4v"))
1241 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1242 "Quicktime/Ipod might not play the file\n");
1247 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1251 if (track->par->width == 720) { /* SD */
1252 if (track->par->height == 480) { /* NTSC */
1253 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1254 else tag = MKTAG('d','v','c',' ');
1255 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1256 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1257 else tag = MKTAG('d','v','p','p');
1258 } else if (track->par->height == 720) { /* HD 720 line */
1259 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1260 else tag = MKTAG('d','v','h','p');
1261 } else if (track->par->height == 1080) { /* HD 1080 line */
1262 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1263 else tag = MKTAG('d','v','h','6');
1265 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1272 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1274 AVRational rate = st->avg_frame_rate;
1276 #if FF_API_LAVF_AVCTX
1277 FF_DISABLE_DEPRECATION_WARNINGS
1278 rate = av_inv_q(st->codec->time_base);
1279 if (av_timecode_check_frame_rate(rate) < 0) {
1280 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1281 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1282 rate = st->avg_frame_rate;
1284 FF_ENABLE_DEPRECATION_WARNINGS
1290 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1292 int tag = track->par->codec_tag;
1293 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1294 AVStream *st = track->st;
1295 int rate = av_q2d(find_fps(s, st));
1298 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1300 if (track->par->format == AV_PIX_FMT_YUV420P) {
1301 if (track->par->width == 1280 && track->par->height == 720) {
1303 if (rate == 24) tag = MKTAG('x','d','v','4');
1304 else if (rate == 25) tag = MKTAG('x','d','v','5');
1305 else if (rate == 30) tag = MKTAG('x','d','v','1');
1306 else if (rate == 50) tag = MKTAG('x','d','v','a');
1307 else if (rate == 60) tag = MKTAG('x','d','v','9');
1309 } else if (track->par->width == 1440 && track->par->height == 1080) {
1311 if (rate == 24) tag = MKTAG('x','d','v','6');
1312 else if (rate == 25) tag = MKTAG('x','d','v','7');
1313 else if (rate == 30) tag = MKTAG('x','d','v','8');
1315 if (rate == 25) tag = MKTAG('x','d','v','3');
1316 else if (rate == 30) tag = MKTAG('x','d','v','2');
1318 } else if (track->par->width == 1920 && track->par->height == 1080) {
1320 if (rate == 24) tag = MKTAG('x','d','v','d');
1321 else if (rate == 25) tag = MKTAG('x','d','v','e');
1322 else if (rate == 30) tag = MKTAG('x','d','v','f');
1324 if (rate == 25) tag = MKTAG('x','d','v','c');
1325 else if (rate == 30) tag = MKTAG('x','d','v','b');
1328 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1329 if (track->par->width == 1280 && track->par->height == 720) {
1331 if (rate == 24) tag = MKTAG('x','d','5','4');
1332 else if (rate == 25) tag = MKTAG('x','d','5','5');
1333 else if (rate == 30) tag = MKTAG('x','d','5','1');
1334 else if (rate == 50) tag = MKTAG('x','d','5','a');
1335 else if (rate == 60) tag = MKTAG('x','d','5','9');
1337 } else if (track->par->width == 1920 && track->par->height == 1080) {
1339 if (rate == 24) tag = MKTAG('x','d','5','d');
1340 else if (rate == 25) tag = MKTAG('x','d','5','e');
1341 else if (rate == 30) tag = MKTAG('x','d','5','f');
1343 if (rate == 25) tag = MKTAG('x','d','5','c');
1344 else if (rate == 30) tag = MKTAG('x','d','5','b');
1352 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1354 int tag = track->par->codec_tag;
1355 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1356 AVStream *st = track->st;
1357 int rate = av_q2d(find_fps(s, st));
1360 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1362 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1363 if (track->par->width == 960 && track->par->height == 720) {
1365 if (rate == 24) tag = MKTAG('a','i','5','p');
1366 else if (rate == 25) tag = MKTAG('a','i','5','q');
1367 else if (rate == 30) tag = MKTAG('a','i','5','p');
1368 else if (rate == 50) tag = MKTAG('a','i','5','q');
1369 else if (rate == 60) tag = MKTAG('a','i','5','p');
1371 } else if (track->par->width == 1440 && track->par->height == 1080) {
1373 if (rate == 24) tag = MKTAG('a','i','5','3');
1374 else if (rate == 25) tag = MKTAG('a','i','5','2');
1375 else if (rate == 30) tag = MKTAG('a','i','5','3');
1377 if (rate == 50) tag = MKTAG('a','i','5','5');
1378 else if (rate == 60) tag = MKTAG('a','i','5','6');
1381 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1382 if (track->par->width == 1280 && track->par->height == 720) {
1384 if (rate == 24) tag = MKTAG('a','i','1','p');
1385 else if (rate == 25) tag = MKTAG('a','i','1','q');
1386 else if (rate == 30) tag = MKTAG('a','i','1','p');
1387 else if (rate == 50) tag = MKTAG('a','i','1','q');
1388 else if (rate == 60) tag = MKTAG('a','i','1','p');
1390 } else if (track->par->width == 1920 && track->par->height == 1080) {
1392 if (rate == 24) tag = MKTAG('a','i','1','3');
1393 else if (rate == 25) tag = MKTAG('a','i','1','2');
1394 else if (rate == 30) tag = MKTAG('a','i','1','3');
1396 if (rate == 25) tag = MKTAG('a','i','1','5');
1397 else if (rate == 50) tag = MKTAG('a','i','1','5');
1398 else if (rate == 60) tag = MKTAG('a','i','1','6');
1400 } else if ( track->par->width == 4096 && track->par->height == 2160
1401 || track->par->width == 3840 && track->par->height == 2160
1402 || track->par->width == 2048 && track->par->height == 1080) {
1403 tag = MKTAG('a','i','v','x');
1410 static const struct {
1411 enum AVPixelFormat pix_fmt;
1414 } mov_pix_fmt_tags[] = {
1415 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1416 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1417 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1418 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1419 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1420 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1421 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1422 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1423 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1424 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1425 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1426 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1427 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1428 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1429 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1432 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1434 int tag = MKTAG('A','V','d','n');
1435 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1436 track->par->profile != FF_PROFILE_DNXHD)
1437 tag = MKTAG('A','V','d','h');
1441 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1443 int tag = track->par->codec_tag;
1445 enum AVPixelFormat pix_fmt;
1447 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1448 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1449 tag = mov_pix_fmt_tags[i].tag;
1450 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1451 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1456 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1457 track->par->bits_per_coded_sample);
1458 if (tag == MKTAG('r','a','w',' ') &&
1459 track->par->format != pix_fmt &&
1460 track->par->format != AV_PIX_FMT_GRAY8 &&
1461 track->par->format != AV_PIX_FMT_NONE)
1462 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1463 av_get_pix_fmt_name(track->par->format));
1467 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1469 int tag = track->par->codec_tag;
1471 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1472 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1473 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1474 track->par->codec_id == AV_CODEC_ID_H263 ||
1475 track->par->codec_id == AV_CODEC_ID_H264 ||
1476 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1477 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1478 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1479 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1480 tag = mov_get_dv_codec_tag(s, track);
1481 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1482 tag = mov_get_rawvideo_codec_tag(s, track);
1483 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1484 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1485 else if (track->par->codec_id == AV_CODEC_ID_H264)
1486 tag = mov_get_h264_codec_tag(s, track);
1487 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1488 tag = mov_get_dnxhd_codec_tag(s, track);
1489 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1490 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1491 if (!tag) { // if no mac fcc found, try with Microsoft tags
1492 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1494 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1495 "the file may be unplayable!\n");
1497 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1498 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1499 if (!tag) { // if no mac fcc found, try with Microsoft tags
1500 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1502 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1503 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1504 "the file may be unplayable!\n");
1507 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1508 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1514 static const AVCodecTag codec_3gp_tags[] = {
1515 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1516 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1517 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1518 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1519 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1520 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1521 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1522 { AV_CODEC_ID_NONE, 0 },
1525 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1526 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1527 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1528 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1529 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1530 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1531 { AV_CODEC_ID_NONE, 0 },
1534 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1538 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1539 tag = mp4_get_codec_tag(s, track);
1540 else if (track->mode == MODE_ISM) {
1541 tag = mp4_get_codec_tag(s, track);
1542 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
1543 tag = MKTAG('w', 'm', 'a', ' ');
1544 } else if (track->mode == MODE_IPOD)
1545 tag = ipod_get_codec_tag(s, track);
1546 else if (track->mode & MODE_3GP)
1547 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
1548 else if (track->mode == MODE_F4V)
1549 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
1551 tag = mov_get_codec_tag(s, track);
1556 /** Write uuid atom.
1557 * Needed to make file play in iPods running newest firmware
1558 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1560 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1563 ffio_wfourcc(pb, "uuid");
1564 avio_wb32(pb, 0x6b6840f2);
1565 avio_wb32(pb, 0x5f244fc5);
1566 avio_wb32(pb, 0xba39a51b);
1567 avio_wb32(pb, 0xcf0323f3);
1572 static const uint16_t fiel_data[] = {
1573 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1576 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1578 unsigned mov_field_order = 0;
1579 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1580 mov_field_order = fiel_data[field_order];
1584 ffio_wfourcc(pb, "fiel");
1585 avio_wb16(pb, mov_field_order);
1589 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1591 int64_t pos = avio_tell(pb);
1592 avio_wb32(pb, 0); /* size */
1593 avio_wl32(pb, track->tag); // store it byteswapped
1594 avio_wb32(pb, 0); /* Reserved */
1595 avio_wb16(pb, 0); /* Reserved */
1596 avio_wb16(pb, 1); /* Data-reference index */
1598 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1599 mov_write_esds_tag(pb, track);
1600 else if (track->par->extradata_size)
1601 avio_write(pb, track->par->extradata, track->par->extradata_size);
1603 return update_size(pb, pos);
1606 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1609 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1610 track->par->sample_aspect_ratio.den, INT_MAX);
1613 ffio_wfourcc(pb, "pasp");
1614 avio_wb32(pb, sar.num);
1615 avio_wb32(pb, sar.den);
1619 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1624 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1626 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1629 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1630 av_log(pb, AV_LOG_DEBUG, "writing gama value %d\n", gama);
1632 av_assert0(track->mode == MODE_MOV);
1634 ffio_wfourcc(pb, "gama");
1635 avio_wb32(pb, gama);
1639 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1644 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1646 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1647 // Ref (MP4): ISO/IEC 14496-12:2012
1649 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1650 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1651 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1652 if ((track->par->width >= 1920 && track->par->height >= 1080)
1653 || (track->par->width == 1280 && track->par->height == 720)) {
1654 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1655 track->par->color_primaries = AVCOL_PRI_BT709;
1656 } else if (track->par->width == 720 && track->height == 576) {
1657 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1658 track->par->color_primaries = AVCOL_PRI_BT470BG;
1659 } else if (track->par->width == 720 &&
1660 (track->height == 486 || track->height == 480)) {
1661 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1662 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1664 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1666 switch (track->par->color_primaries) {
1667 case AVCOL_PRI_BT709:
1668 track->par->color_trc = AVCOL_TRC_BT709;
1669 track->par->color_space = AVCOL_SPC_BT709;
1671 case AVCOL_PRI_SMPTE170M:
1672 case AVCOL_PRI_BT470BG:
1673 track->par->color_trc = AVCOL_TRC_BT709;
1674 track->par->color_space = AVCOL_SPC_SMPTE170M;
1679 /* We should only ever be called by MOV or MP4. */
1680 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1682 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1683 ffio_wfourcc(pb, "colr");
1684 if (track->mode == MODE_MP4)
1685 ffio_wfourcc(pb, "nclx");
1687 ffio_wfourcc(pb, "nclc");
1688 switch (track->par->color_primaries) {
1689 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1690 case AVCOL_PRI_SMPTE170M:
1691 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1692 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1693 default: avio_wb16(pb, 2);
1695 switch (track->par->color_trc) {
1696 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1697 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1698 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1699 default: avio_wb16(pb, 2);
1701 switch (track->par->color_space) {
1702 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1703 case AVCOL_SPC_BT470BG:
1704 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1705 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1706 default: avio_wb16(pb, 2);
1709 if (track->mode == MODE_MP4) {
1710 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1711 avio_w8(pb, full_range << 7);
1718 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1720 AVDictionaryEntry *encoder;
1721 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1722 || (track->par->width == 1440 && track->par->height == 1080)
1723 || (track->par->width == 1920 && track->par->height == 1080);
1725 if (track->mode == MODE_MOV &&
1726 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1727 av_strlcpy(compressor_name, encoder->value, 32);
1728 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1729 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1730 AVStream *st = track->st;
1731 int rate = av_q2d(find_fps(NULL, st));
1732 av_strlcatf(compressor_name, len, "XDCAM");
1733 if (track->par->format == AV_PIX_FMT_YUV422P) {
1734 av_strlcatf(compressor_name, len, " HD422");
1735 } else if(track->par->width == 1440) {
1736 av_strlcatf(compressor_name, len, " HD");
1738 av_strlcatf(compressor_name, len, " EX");
1740 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1742 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1746 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1748 int64_t pos = avio_tell(pb);
1749 char compressor_name[32] = { 0 };
1752 avio_wb32(pb, 0); /* size */
1753 if (mov->encryption_scheme != MOV_ENC_NONE) {
1754 ffio_wfourcc(pb, "encv");
1756 avio_wl32(pb, track->tag); // store it byteswapped
1758 avio_wb32(pb, 0); /* Reserved */
1759 avio_wb16(pb, 0); /* Reserved */
1760 avio_wb16(pb, 1); /* Data-reference index */
1762 avio_wb16(pb, 0); /* Codec stream version */
1763 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1764 if (track->mode == MODE_MOV) {
1765 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1766 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1767 avio_wb32(pb, 0); /* Temporal Quality */
1768 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1770 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1771 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1774 avio_wb32(pb, 0); /* Reserved */
1775 avio_wb32(pb, 0); /* Reserved */
1776 avio_wb32(pb, 0); /* Reserved */
1778 avio_wb16(pb, track->par->width); /* Video width */
1779 avio_wb16(pb, track->height); /* Video height */
1780 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1781 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1782 avio_wb32(pb, 0); /* Data size (= 0) */
1783 avio_wb16(pb, 1); /* Frame count (= 1) */
1785 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1786 find_compressor(compressor_name, 32, track);
1787 avio_w8(pb, strlen(compressor_name));
1788 avio_write(pb, compressor_name, 31);
1790 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1791 avio_wb16(pb, track->par->bits_per_coded_sample |
1792 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1794 avio_wb16(pb, 0x18); /* Reserved */
1796 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1797 int pal_size = 1 << track->par->bits_per_coded_sample;
1799 avio_wb16(pb, 0); /* Color table ID */
1800 avio_wb32(pb, 0); /* Color table seed */
1801 avio_wb16(pb, 0x8000); /* Color table flags */
1802 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1803 for (i = 0; i < pal_size; i++) {
1804 uint32_t rgb = track->palette[i];
1805 uint16_t r = (rgb >> 16) & 0xff;
1806 uint16_t g = (rgb >> 8) & 0xff;
1807 uint16_t b = rgb & 0xff;
1809 avio_wb16(pb, (r << 8) | r);
1810 avio_wb16(pb, (g << 8) | g);
1811 avio_wb16(pb, (b << 8) | b);
1814 avio_wb16(pb, 0xffff); /* Reserved */
1816 if (track->tag == MKTAG('m','p','4','v'))
1817 mov_write_esds_tag(pb, track);
1818 else if (track->par->codec_id == AV_CODEC_ID_H263)
1819 mov_write_d263_tag(pb);
1820 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1821 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1822 mov_write_extradata_tag(pb, track);
1824 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1825 mov_write_avid_tag(pb, track);
1827 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1828 mov_write_hvcc_tag(pb, track);
1829 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1830 mov_write_avcc_tag(pb, track);
1831 if (track->mode == MODE_IPOD)
1832 mov_write_uuid_tag_ipod(pb);
1833 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1834 mov_write_vpcc_tag(mov->fc, pb, track);
1835 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1836 mov_write_dvc1_tag(pb, track);
1837 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1838 track->par->codec_id == AV_CODEC_ID_VP6A) {
1839 /* Don't write any potential extradata here - the cropping
1840 * is signalled via the normal width/height fields. */
1841 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1842 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1843 mov_write_dpxe_tag(pb, track);
1844 } else if (track->vos_len > 0)
1845 mov_write_glbl_tag(pb, track);
1847 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1848 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1849 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1850 int field_order = track->par->field_order;
1852 #if FF_API_LAVF_AVCTX
1853 FF_DISABLE_DEPRECATION_WARNINGS
1854 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1855 field_order = track->st->codec->field_order;
1856 FF_ENABLE_DEPRECATION_WARNINGS
1859 if (field_order != AV_FIELD_UNKNOWN)
1860 mov_write_fiel_tag(pb, track, field_order);
1863 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1864 if (track->mode == MODE_MOV)
1865 mov_write_gama_tag(pb, track, mov->gamma);
1867 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1869 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1870 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1871 mov_write_colr_tag(pb, track);
1873 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1876 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
1877 mov_write_pasp_tag(pb, track);
1880 if (mov->encryption_scheme != MOV_ENC_NONE) {
1881 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1884 /* extra padding for avid stsd */
1885 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1889 return update_size(pb, pos);
1892 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1894 int64_t pos = avio_tell(pb);
1895 avio_wb32(pb, 0); /* size */
1896 ffio_wfourcc(pb, "rtp ");
1897 avio_wb32(pb, 0); /* Reserved */
1898 avio_wb16(pb, 0); /* Reserved */
1899 avio_wb16(pb, 1); /* Data-reference index */
1901 avio_wb16(pb, 1); /* Hint track version */
1902 avio_wb16(pb, 1); /* Highest compatible version */
1903 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1905 avio_wb32(pb, 12); /* size */
1906 ffio_wfourcc(pb, "tims");
1907 avio_wb32(pb, track->timescale);
1909 return update_size(pb, pos);
1912 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1914 uint64_t str_size =strlen(reel_name);
1915 int64_t pos = avio_tell(pb);
1917 if (str_size >= UINT16_MAX){
1918 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1920 return AVERROR(EINVAL);
1923 avio_wb32(pb, 0); /* size */
1924 ffio_wfourcc(pb, "name"); /* Data format */
1925 avio_wb16(pb, str_size); /* string size */
1926 avio_wb16(pb, track->language); /* langcode */
1927 avio_write(pb, reel_name, str_size); /* reel name */
1928 return update_size(pb,pos);
1931 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1933 int64_t pos = avio_tell(pb);
1937 AVDictionaryEntry *t = NULL;
1939 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
1940 #if FF_API_LAVF_AVCTX
1941 FF_DISABLE_DEPRECATION_WARNINGS
1942 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
1943 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
1944 FF_ENABLE_DEPRECATION_WARNINGS
1946 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
1947 return AVERROR(EINVAL);
1950 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
1951 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
1954 if (nb_frames > 255) {
1955 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1956 return AVERROR(EINVAL);
1959 avio_wb32(pb, 0); /* size */
1960 ffio_wfourcc(pb, "tmcd"); /* Data format */
1961 avio_wb32(pb, 0); /* Reserved */
1962 avio_wb32(pb, 1); /* Data reference index */
1963 avio_wb32(pb, 0); /* Flags */
1964 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1965 avio_wb32(pb, track->timescale); /* Timescale */
1966 avio_wb32(pb, frame_duration); /* Frame duration */
1967 avio_w8(pb, nb_frames); /* Number of frames */
1968 avio_w8(pb, 0); /* Reserved */
1970 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1971 if (t && utf8len(t->value) && track->mode != MODE_MP4)
1972 mov_write_source_reference_tag(pb, track, t->value);
1974 avio_wb16(pb, 0); /* zero size */
1977 avio_wb32(pb, 0); /* size */
1978 ffio_wfourcc(pb, "tmcd"); /* Data format */
1979 avio_wb32(pb, 0); /* Reserved */
1980 avio_wb32(pb, 1); /* Data reference index */
1981 if (track->par->extradata_size)
1982 avio_write(pb, track->par->extradata, track->par->extradata_size);
1984 return update_size(pb, pos);
1987 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1989 int64_t pos = avio_tell(pb);
1990 avio_wb32(pb, 0); /* size */
1991 ffio_wfourcc(pb, "stsd");
1992 avio_wb32(pb, 0); /* version & flags */
1993 avio_wb32(pb, 1); /* entry count */
1994 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
1995 mov_write_video_tag(pb, mov, track);
1996 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1997 mov_write_audio_tag(s, pb, mov, track);
1998 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1999 mov_write_subtitle_tag(pb, track);
2000 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2001 mov_write_rtp_tag(pb, track);
2002 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2003 mov_write_tmcd_tag(pb, track);
2004 return update_size(pb, pos);
2007 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
2009 MOVStts *ctts_entries;
2010 uint32_t entries = 0;
2014 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2016 return AVERROR(ENOMEM);
2017 ctts_entries[0].count = 1;
2018 ctts_entries[0].duration = track->cluster[0].cts;
2019 for (i = 1; i < track->entry; i++) {
2020 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2021 ctts_entries[entries].count++; /* compress */
2024 ctts_entries[entries].duration = track->cluster[i].cts;
2025 ctts_entries[entries].count = 1;
2028 entries++; /* last one */
2029 atom_size = 16 + (entries * 8);
2030 avio_wb32(pb, atom_size); /* size */
2031 ffio_wfourcc(pb, "ctts");
2032 avio_wb32(pb, 0); /* version & flags */
2033 avio_wb32(pb, entries); /* entry count */
2034 for (i = 0; i < entries; i++) {
2035 avio_wb32(pb, ctts_entries[i].count);
2036 avio_wb32(pb, ctts_entries[i].duration);
2038 av_free(ctts_entries);
2042 /* Time to sample atom */
2043 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2045 MOVStts *stts_entries = NULL;
2046 uint32_t entries = -1;
2050 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2051 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2053 return AVERROR(ENOMEM);
2054 stts_entries[0].count = track->sample_count;
2055 stts_entries[0].duration = 1;
2059 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2061 return AVERROR(ENOMEM);
2063 for (i = 0; i < track->entry; i++) {
2064 int duration = get_cluster_duration(track, i);
2065 if (i && duration == stts_entries[entries].duration) {
2066 stts_entries[entries].count++; /* compress */
2069 stts_entries[entries].duration = duration;
2070 stts_entries[entries].count = 1;
2073 entries++; /* last one */
2075 atom_size = 16 + (entries * 8);
2076 avio_wb32(pb, atom_size); /* size */
2077 ffio_wfourcc(pb, "stts");
2078 avio_wb32(pb, 0); /* version & flags */
2079 avio_wb32(pb, entries); /* entry count */
2080 for (i = 0; i < entries; i++) {
2081 avio_wb32(pb, stts_entries[i].count);
2082 avio_wb32(pb, stts_entries[i].duration);
2084 av_free(stts_entries);
2088 static int mov_write_dref_tag(AVIOContext *pb)
2090 avio_wb32(pb, 28); /* size */
2091 ffio_wfourcc(pb, "dref");
2092 avio_wb32(pb, 0); /* version & flags */
2093 avio_wb32(pb, 1); /* entry count */
2095 avio_wb32(pb, 0xc); /* size */
2096 //FIXME add the alis and rsrc atom
2097 ffio_wfourcc(pb, "url ");
2098 avio_wb32(pb, 1); /* version & flags */
2103 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2105 int64_t pos = avio_tell(pb);
2108 avio_wb32(pb, 0); /* size */
2109 ffio_wfourcc(pb, "stbl");
2110 mov_write_stsd_tag(s, pb, mov, track);
2111 mov_write_stts_tag(pb, track);
2112 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2113 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2114 track->has_keyframes && track->has_keyframes < track->entry)
2115 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2116 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2117 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2118 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2119 track->flags & MOV_TRACK_CTTS && track->entry) {
2121 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2124 mov_write_stsc_tag(pb, track);
2125 mov_write_stsz_tag(pb, track);
2126 mov_write_stco_tag(pb, track);
2127 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
2128 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2130 return update_size(pb, pos);
2133 static int mov_write_dinf_tag(AVIOContext *pb)
2135 int64_t pos = avio_tell(pb);
2136 avio_wb32(pb, 0); /* size */
2137 ffio_wfourcc(pb, "dinf");
2138 mov_write_dref_tag(pb);
2139 return update_size(pb, pos);
2142 static int mov_write_nmhd_tag(AVIOContext *pb)
2145 ffio_wfourcc(pb, "nmhd");
2150 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2152 int64_t pos = avio_tell(pb);
2153 const char *font = "Lucida Grande";
2154 avio_wb32(pb, 0); /* size */
2155 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2156 avio_wb32(pb, 0); /* version & flags */
2157 avio_wb16(pb, 0); /* text font */
2158 avio_wb16(pb, 0); /* text face */
2159 avio_wb16(pb, 12); /* text size */
2160 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2161 avio_wb16(pb, 0x0000); /* text color (red) */
2162 avio_wb16(pb, 0x0000); /* text color (green) */
2163 avio_wb16(pb, 0x0000); /* text color (blue) */
2164 avio_wb16(pb, 0xffff); /* background color (red) */
2165 avio_wb16(pb, 0xffff); /* background color (green) */
2166 avio_wb16(pb, 0xffff); /* background color (blue) */
2167 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2168 avio_write(pb, font, strlen(font)); /* font name */
2169 return update_size(pb, pos);
2172 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2174 int64_t pos = avio_tell(pb);
2175 avio_wb32(pb, 0); /* size */
2176 ffio_wfourcc(pb, "gmhd");
2177 avio_wb32(pb, 0x18); /* gmin size */
2178 ffio_wfourcc(pb, "gmin");/* generic media info */
2179 avio_wb32(pb, 0); /* version & flags */
2180 avio_wb16(pb, 0x40); /* graphics mode = */
2181 avio_wb16(pb, 0x8000); /* opColor (r?) */
2182 avio_wb16(pb, 0x8000); /* opColor (g?) */
2183 avio_wb16(pb, 0x8000); /* opColor (b?) */
2184 avio_wb16(pb, 0); /* balance */
2185 avio_wb16(pb, 0); /* reserved */
2188 * This special text atom is required for
2189 * Apple Quicktime chapters. The contents
2190 * don't appear to be documented, so the
2191 * bytes are copied verbatim.
2193 if (track->tag != MKTAG('c','6','0','8')) {
2194 avio_wb32(pb, 0x2C); /* size */
2195 ffio_wfourcc(pb, "text");
2196 avio_wb16(pb, 0x01);
2197 avio_wb32(pb, 0x00);
2198 avio_wb32(pb, 0x00);
2199 avio_wb32(pb, 0x00);
2200 avio_wb32(pb, 0x01);
2201 avio_wb32(pb, 0x00);
2202 avio_wb32(pb, 0x00);
2203 avio_wb32(pb, 0x00);
2204 avio_wb32(pb, 0x00004000);
2205 avio_wb16(pb, 0x0000);
2208 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2209 int64_t tmcd_pos = avio_tell(pb);
2210 avio_wb32(pb, 0); /* size */
2211 ffio_wfourcc(pb, "tmcd");
2212 mov_write_tcmi_tag(pb, track);
2213 update_size(pb, tmcd_pos);
2215 return update_size(pb, pos);
2218 static int mov_write_smhd_tag(AVIOContext *pb)
2220 avio_wb32(pb, 16); /* size */
2221 ffio_wfourcc(pb, "smhd");
2222 avio_wb32(pb, 0); /* version & flags */
2223 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2224 avio_wb16(pb, 0); /* reserved */
2228 static int mov_write_vmhd_tag(AVIOContext *pb)
2230 avio_wb32(pb, 0x14); /* size (always 0x14) */
2231 ffio_wfourcc(pb, "vmhd");
2232 avio_wb32(pb, 0x01); /* version & flags */
2233 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2237 static int is_clcp_track(MOVTrack *track)
2239 return track->tag == MKTAG('c','7','0','8') ||
2240 track->tag == MKTAG('c','6','0','8');
2243 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2245 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2246 int64_t pos = avio_tell(pb);
2250 descr = "DataHandler";
2253 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2254 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2256 descr = "VideoHandler";
2257 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2259 descr = "SoundHandler";
2260 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2261 if (is_clcp_track(track)) {
2263 descr = "ClosedCaptionHandler";
2265 if (track->tag == MKTAG('t','x','3','g')) {
2267 } else if (track->tag == MKTAG('m','p','4','s')) {
2272 descr = "SubtitleHandler";
2274 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2276 descr = "HintHandler";
2277 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2279 descr = "TimeCodeHandler";
2282 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
2283 track->par->codec_tag);
2285 av_log(s, AV_LOG_WARNING,
2286 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
2287 tag_buf, track->par->codec_tag);
2290 // hdlr.name is used by some players to identify the content title
2291 // of the track. So if an alternate handler description is
2292 // specified, use it.
2293 AVDictionaryEntry *t;
2294 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2295 if (t && utf8len(t->value))
2300 avio_wb32(pb, 0); /* size */
2301 ffio_wfourcc(pb, "hdlr");
2302 avio_wb32(pb, 0); /* Version & flags */
2303 avio_write(pb, hdlr, 4); /* handler */
2304 ffio_wfourcc(pb, hdlr_type); /* handler type */
2305 avio_wb32(pb, 0); /* reserved */
2306 avio_wb32(pb, 0); /* reserved */
2307 avio_wb32(pb, 0); /* reserved */
2308 if (!track || track->mode == MODE_MOV)
2309 avio_w8(pb, strlen(descr)); /* pascal string */
2310 avio_write(pb, descr, strlen(descr)); /* handler description */
2311 if (track && track->mode != MODE_MOV)
2312 avio_w8(pb, 0); /* c string */
2313 return update_size(pb, pos);
2316 static int mov_write_hmhd_tag(AVIOContext *pb)
2318 /* This atom must be present, but leaving the values at zero
2319 * seems harmless. */
2320 avio_wb32(pb, 28); /* size */
2321 ffio_wfourcc(pb, "hmhd");
2322 avio_wb32(pb, 0); /* version, flags */
2323 avio_wb16(pb, 0); /* maxPDUsize */
2324 avio_wb16(pb, 0); /* avgPDUsize */
2325 avio_wb32(pb, 0); /* maxbitrate */
2326 avio_wb32(pb, 0); /* avgbitrate */
2327 avio_wb32(pb, 0); /* reserved */
2331 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2333 int64_t pos = avio_tell(pb);
2336 avio_wb32(pb, 0); /* size */
2337 ffio_wfourcc(pb, "minf");
2338 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2339 mov_write_vmhd_tag(pb);
2340 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2341 mov_write_smhd_tag(pb);
2342 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2343 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2344 mov_write_gmhd_tag(pb, track);
2346 mov_write_nmhd_tag(pb);
2348 } else if (track->tag == MKTAG('r','t','p',' ')) {
2349 mov_write_hmhd_tag(pb);
2350 } else if (track->tag == MKTAG('t','m','c','d')) {
2351 if (track->mode != MODE_MOV)
2352 mov_write_nmhd_tag(pb);
2354 mov_write_gmhd_tag(pb, track);
2356 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2357 mov_write_hdlr_tag(s, pb, NULL);
2358 mov_write_dinf_tag(pb);
2359 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2361 return update_size(pb, pos);
2364 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2367 int version = track->track_duration < INT32_MAX ? 0 : 1;
2369 if (track->mode == MODE_ISM)
2372 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2373 ffio_wfourcc(pb, "mdhd");
2374 avio_w8(pb, version);
2375 avio_wb24(pb, 0); /* flags */
2377 avio_wb64(pb, track->time);
2378 avio_wb64(pb, track->time);
2380 avio_wb32(pb, track->time); /* creation time */
2381 avio_wb32(pb, track->time); /* modification time */
2383 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2384 if (!track->entry && mov->mode == MODE_ISM)
2385 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2386 else if (!track->entry)
2387 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2389 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2390 avio_wb16(pb, track->language); /* language */
2391 avio_wb16(pb, 0); /* reserved (quality) */
2393 if (version != 0 && track->mode == MODE_MOV) {
2394 av_log(NULL, AV_LOG_ERROR,
2395 "FATAL error, file duration too long for timebase, this file will not be\n"
2396 "playable with quicktime. Choose a different timebase or a different\n"
2397 "container format\n");
2403 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2404 MOVMuxContext *mov, MOVTrack *track)
2406 int64_t pos = avio_tell(pb);
2409 avio_wb32(pb, 0); /* size */
2410 ffio_wfourcc(pb, "mdia");
2411 mov_write_mdhd_tag(pb, mov, track);
2412 mov_write_hdlr_tag(s, pb, track);
2413 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2415 return update_size(pb, pos);
2418 /* transformation matrix
2422 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2423 int16_t d, int16_t tx, int16_t ty)
2425 avio_wb32(pb, a << 16); /* 16.16 format */
2426 avio_wb32(pb, b << 16); /* 16.16 format */
2427 avio_wb32(pb, 0); /* u in 2.30 format */
2428 avio_wb32(pb, c << 16); /* 16.16 format */
2429 avio_wb32(pb, d << 16); /* 16.16 format */
2430 avio_wb32(pb, 0); /* v in 2.30 format */
2431 avio_wb32(pb, tx << 16); /* 16.16 format */
2432 avio_wb32(pb, ty << 16); /* 16.16 format */
2433 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2436 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2437 MOVTrack *track, AVStream *st)
2439 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2440 track->timescale, AV_ROUND_UP);
2441 int version = duration < INT32_MAX ? 0 : 1;
2442 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2446 uint32_t *display_matrix = NULL;
2447 int display_matrix_size, i;
2450 if (mov->per_stream_grouping)
2453 group = st->codecpar->codec_type;
2455 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2456 &display_matrix_size);
2457 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2458 display_matrix = NULL;
2461 if (track->flags & MOV_TRACK_ENABLED)
2462 flags |= MOV_TKHD_FLAG_ENABLED;
2464 if (track->mode == MODE_ISM)
2467 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2468 ffio_wfourcc(pb, "tkhd");
2469 avio_w8(pb, version);
2470 avio_wb24(pb, flags);
2472 avio_wb64(pb, track->time);
2473 avio_wb64(pb, track->time);
2475 avio_wb32(pb, track->time); /* creation time */
2476 avio_wb32(pb, track->time); /* modification time */
2478 avio_wb32(pb, track->track_id); /* track-id */
2479 avio_wb32(pb, 0); /* reserved */
2480 if (!track->entry && mov->mode == MODE_ISM)
2481 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2482 else if (!track->entry)
2483 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2485 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2487 avio_wb32(pb, 0); /* reserved */
2488 avio_wb32(pb, 0); /* reserved */
2489 avio_wb16(pb, 0); /* layer */
2490 avio_wb16(pb, group); /* alternate group) */
2491 /* Volume, only for audio */
2492 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2493 avio_wb16(pb, 0x0100);
2496 avio_wb16(pb, 0); /* reserved */
2498 /* Matrix structure */
2499 #if FF_API_OLD_ROTATE_API
2500 if (st && st->metadata) {
2501 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2502 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2505 if (display_matrix) {
2506 for (i = 0; i < 9; i++)
2507 avio_wb32(pb, display_matrix[i]);
2508 #if FF_API_OLD_ROTATE_API
2509 } else if (rotation == 90) {
2510 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2511 } else if (rotation == 180) {
2512 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2513 } else if (rotation == 270) {
2514 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2517 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2519 /* Track width and height, for visual only */
2520 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2521 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2522 int64_t track_width_1616;
2523 if (track->mode == MODE_MOV) {
2524 track_width_1616 = track->par->width * 0x10000ULL;
2526 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2527 track->par->width * 0x10000LL,
2528 st->sample_aspect_ratio.den);
2529 if (!track_width_1616 ||
2530 track->height != track->par->height ||
2531 track_width_1616 > UINT32_MAX)
2532 track_width_1616 = track->par->width * 0x10000ULL;
2534 if (track_width_1616 > UINT32_MAX) {
2535 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2536 track_width_1616 = 0;
2538 avio_wb32(pb, track_width_1616);
2539 if (track->height > 0xFFFF) {
2540 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2543 avio_wb32(pb, track->height * 0x10000U);
2551 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2553 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2554 track->par->sample_aspect_ratio.den);
2556 int64_t pos = avio_tell(pb);
2558 avio_wb32(pb, 0); /* size */
2559 ffio_wfourcc(pb, "tapt");
2562 ffio_wfourcc(pb, "clef");
2564 avio_wb32(pb, width << 16);
2565 avio_wb32(pb, track->par->height << 16);
2568 ffio_wfourcc(pb, "prof");
2570 avio_wb32(pb, width << 16);
2571 avio_wb32(pb, track->par->height << 16);
2574 ffio_wfourcc(pb, "enof");
2576 avio_wb32(pb, track->par->width << 16);
2577 avio_wb32(pb, track->par->height << 16);
2579 return update_size(pb, pos);
2582 // This box seems important for the psp playback ... without it the movie seems to hang
2583 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2586 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2587 track->timescale, AV_ROUND_UP);
2588 int version = duration < INT32_MAX ? 0 : 1;
2589 int entry_size, entry_count, size;
2590 int64_t delay, start_ct = track->start_cts;
2591 int64_t start_dts = track->start_dts;
2594 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2596 av_log(mov->fc, AV_LOG_DEBUG,
2597 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2598 track->cluster[0].dts, track->cluster[0].cts,
2599 start_dts, start_ct, track->track_id);
2600 start_dts = track->cluster[0].dts;
2601 start_ct = track->cluster[0].cts;
2605 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2606 track->timescale, AV_ROUND_DOWN);
2607 version |= delay < INT32_MAX ? 0 : 1;
2609 entry_size = (version == 1) ? 20 : 12;
2610 entry_count = 1 + (delay > 0);
2611 size = 24 + entry_count * entry_size;
2613 /* write the atom data */
2614 avio_wb32(pb, size);
2615 ffio_wfourcc(pb, "edts");
2616 avio_wb32(pb, size - 8);
2617 ffio_wfourcc(pb, "elst");
2618 avio_w8(pb, version);
2619 avio_wb24(pb, 0); /* flags */
2621 avio_wb32(pb, entry_count);
2622 if (delay > 0) { /* add an empty edit to delay presentation */
2623 /* In the positive delay case, the delay includes the cts
2624 * offset, and the second edit list entry below trims out
2625 * the same amount from the actual content. This makes sure
2626 * that the offset last sample is included in the edit
2627 * list duration as well. */
2629 avio_wb64(pb, delay);
2632 avio_wb32(pb, delay);
2635 avio_wb32(pb, 0x00010000);
2637 /* Avoid accidentally ending up with start_ct = -1 which has got a
2638 * special meaning. Normally start_ct should end up positive or zero
2639 * here, but use FFMIN in case dts is a small positive integer
2640 * rounded to 0 when represented in MOV_TIMESCALE units. */
2641 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2642 start_ct = -FFMIN(start_dts, 0);
2643 /* Note, this delay is calculated from the pts of the first sample,
2644 * ensuring that we don't reduce the duration for cases with
2649 /* For fragmented files, we don't know the full length yet. Setting
2650 * duration to 0 allows us to only specify the offset, including
2651 * the rest of the content (from all future fragments) without specifying
2652 * an explicit duration. */
2653 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2658 avio_wb64(pb, duration);
2659 avio_wb64(pb, start_ct);
2661 avio_wb32(pb, duration);
2662 avio_wb32(pb, start_ct);
2664 avio_wb32(pb, 0x00010000);
2668 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2670 avio_wb32(pb, 20); // size
2671 ffio_wfourcc(pb, "tref");
2672 avio_wb32(pb, 12); // size (subatom)
2673 avio_wl32(pb, track->tref_tag);
2674 avio_wb32(pb, track->tref_id);
2678 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2679 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2681 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2682 ffio_wfourcc(pb, "uuid");
2683 ffio_wfourcc(pb, "USMT");
2684 avio_wb32(pb, 0x21d24fce);
2685 avio_wb32(pb, 0xbb88695c);
2686 avio_wb32(pb, 0xfac9c740);
2687 avio_wb32(pb, 0x1c); // another size here!
2688 ffio_wfourcc(pb, "MTDT");
2689 avio_wb32(pb, 0x00010012);
2690 avio_wb32(pb, 0x0a);
2691 avio_wb32(pb, 0x55c40000);
2697 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2699 AVFormatContext *ctx = track->rtp_ctx;
2700 char buf[1000] = "";
2703 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2704 NULL, NULL, 0, 0, ctx);
2705 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2708 avio_wb32(pb, len + 24);
2709 ffio_wfourcc(pb, "udta");
2710 avio_wb32(pb, len + 16);
2711 ffio_wfourcc(pb, "hnti");
2712 avio_wb32(pb, len + 8);
2713 ffio_wfourcc(pb, "sdp ");
2714 avio_write(pb, buf, len);
2718 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2719 const char *tag, const char *str)
2721 int64_t pos = avio_tell(pb);
2722 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2723 if (!t || !utf8len(t->value))
2726 avio_wb32(pb, 0); /* size */
2727 ffio_wfourcc(pb, tag); /* type */
2728 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2729 return update_size(pb, pos);
2732 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2735 AVIOContext *pb_buf;
2742 ret = avio_open_dyn_buf(&pb_buf);
2746 if (mov->mode & MODE_MP4)
2747 mov_write_track_metadata(pb_buf, st, "name", "title");
2749 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2750 avio_wb32(pb, size + 8);
2751 ffio_wfourcc(pb, "udta");
2752 avio_write(pb, buf, size);
2759 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2760 MOVTrack *track, AVStream *st)
2762 int64_t pos = avio_tell(pb);
2763 int entry_backup = track->entry;
2764 int chunk_backup = track->chunkCount;
2767 /* If we want to have an empty moov, but some samples already have been
2768 * buffered (delay_moov), pretend that no samples have been written yet. */
2769 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2770 track->chunkCount = track->entry = 0;
2772 avio_wb32(pb, 0); /* size */
2773 ffio_wfourcc(pb, "trak");
2774 mov_write_tkhd_tag(pb, mov, track, st);
2776 av_assert2(mov->use_editlist >= 0);
2778 if (track->start_dts != AV_NOPTS_VALUE) {
2779 if (mov->use_editlist)
2780 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2781 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2782 av_log(mov->fc, AV_LOG_WARNING,
2783 "Not writing any edit list even though one would have been required\n");
2786 if (track->tref_tag)
2787 mov_write_tref_tag(pb, track);
2789 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
2791 if (track->mode == MODE_PSP)
2792 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2793 if (track->tag == MKTAG('r','t','p',' '))
2794 mov_write_udta_sdp(pb, track);
2795 if (track->mode == MODE_MOV) {
2796 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2797 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2798 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2799 mov_write_tapt_tag(pb, track);
2802 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2803 mov_write_tapt_tag(pb, track);
2806 mov_write_track_udta_tag(pb, mov, st);
2807 track->entry = entry_backup;
2808 track->chunkCount = chunk_backup;
2809 return update_size(pb, pos);
2812 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2814 int i, has_audio = 0, has_video = 0;
2815 int64_t pos = avio_tell(pb);
2816 int audio_profile = mov->iods_audio_profile;
2817 int video_profile = mov->iods_video_profile;
2818 for (i = 0; i < mov->nb_streams; i++) {
2819 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2820 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
2821 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
2824 if (audio_profile < 0)
2825 audio_profile = 0xFF - has_audio;
2826 if (video_profile < 0)
2827 video_profile = 0xFF - has_video;
2828 avio_wb32(pb, 0x0); /* size */
2829 ffio_wfourcc(pb, "iods");
2830 avio_wb32(pb, 0); /* version & flags */
2831 put_descr(pb, 0x10, 7);
2832 avio_wb16(pb, 0x004f);
2835 avio_w8(pb, audio_profile);
2836 avio_w8(pb, video_profile);
2838 return update_size(pb, pos);
2841 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2843 avio_wb32(pb, 0x20); /* size */
2844 ffio_wfourcc(pb, "trex");
2845 avio_wb32(pb, 0); /* version & flags */
2846 avio_wb32(pb, track->track_id); /* track ID */
2847 avio_wb32(pb, 1); /* default sample description index */
2848 avio_wb32(pb, 0); /* default sample duration */
2849 avio_wb32(pb, 0); /* default sample size */
2850 avio_wb32(pb, 0); /* default sample flags */
2854 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2856 int64_t pos = avio_tell(pb);
2858 avio_wb32(pb, 0x0); /* size */
2859 ffio_wfourcc(pb, "mvex");
2860 for (i = 0; i < mov->nb_streams; i++)
2861 mov_write_trex_tag(pb, &mov->tracks[i]);
2862 return update_size(pb, pos);
2865 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2867 int max_track_id = 1, i;
2868 int64_t max_track_len = 0;
2871 for (i = 0; i < mov->nb_streams; i++) {
2872 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2873 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2875 mov->tracks[i].timescale,
2877 if (max_track_len < max_track_len_temp)
2878 max_track_len = max_track_len_temp;
2879 if (max_track_id < mov->tracks[i].track_id)
2880 max_track_id = mov->tracks[i].track_id;
2883 /* If using delay_moov, make sure the output is the same as if no
2884 * samples had been written yet. */
2885 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2890 version = max_track_len < UINT32_MAX ? 0 : 1;
2891 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
2893 ffio_wfourcc(pb, "mvhd");
2894 avio_w8(pb, version);
2895 avio_wb24(pb, 0); /* flags */
2897 avio_wb64(pb, mov->time);
2898 avio_wb64(pb, mov->time);
2900 avio_wb32(pb, mov->time); /* creation time */
2901 avio_wb32(pb, mov->time); /* modification time */
2903 avio_wb32(pb, MOV_TIMESCALE);
2904 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2906 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2907 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2908 avio_wb16(pb, 0); /* reserved */
2909 avio_wb32(pb, 0); /* reserved */
2910 avio_wb32(pb, 0); /* reserved */
2912 /* Matrix structure */
2913 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2915 avio_wb32(pb, 0); /* reserved (preview time) */
2916 avio_wb32(pb, 0); /* reserved (preview duration) */
2917 avio_wb32(pb, 0); /* reserved (poster time) */
2918 avio_wb32(pb, 0); /* reserved (selection time) */
2919 avio_wb32(pb, 0); /* reserved (selection duration) */
2920 avio_wb32(pb, 0); /* reserved (current time) */
2921 avio_wb32(pb, max_track_id + 1); /* Next track id */
2925 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2928 avio_wb32(pb, 33); /* size */
2929 ffio_wfourcc(pb, "hdlr");
2932 ffio_wfourcc(pb, "mdir");
2933 ffio_wfourcc(pb, "appl");
2940 /* helper function to write a data tag with the specified string as data */
2941 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2944 int size = 16 + strlen(data);
2945 avio_wb32(pb, size); /* size */
2946 ffio_wfourcc(pb, "data");
2949 avio_write(pb, data, strlen(data));
2953 lang = ff_mov_iso639_to_lang("und", 1);
2954 avio_wb16(pb, strlen(data)); /* string length */
2955 avio_wb16(pb, lang);
2956 avio_write(pb, data, strlen(data));
2957 return strlen(data) + 4;
2961 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2962 const char *value, int lang, int long_style)
2965 if (value && value[0]) {
2966 int64_t pos = avio_tell(pb);
2967 avio_wb32(pb, 0); /* size */
2968 ffio_wfourcc(pb, name);
2969 mov_write_string_data_tag(pb, value, lang, long_style);
2970 size = update_size(pb, pos);
2975 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
2976 const char *tag, int *lang)
2979 AVDictionaryEntry *t, *t2 = NULL;
2984 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2987 len = strlen(t->key);
2988 snprintf(tag2, sizeof(tag2), "%s-", tag);
2989 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2990 len2 = strlen(t2->key);
2991 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2992 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3000 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3001 const char *name, const char *tag,
3005 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3008 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3011 /* iTunes bpm number */
3012 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3014 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3015 int size = 0, tmpo = t ? atoi(t->value) : 0;
3018 avio_wb32(pb, size);
3019 ffio_wfourcc(pb, "tmpo");
3020 avio_wb32(pb, size-8); /* size */
3021 ffio_wfourcc(pb, "data");
3022 avio_wb32(pb, 0x15); //type specifier
3024 avio_wb16(pb, tmpo); // data
3029 /* 3GPP TS 26.244 */
3030 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3033 int64_t pos = avio_tell(pb);
3034 double latitude, longitude, altitude;
3035 int32_t latitude_fix, longitude_fix, altitude_fix;
3036 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3037 const char *ptr, *place = "";
3039 static const char *astronomical_body = "earth";
3044 longitude = strtod(ptr, &end);
3046 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3050 latitude = strtod(ptr, &end);
3052 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3056 altitude = strtod(ptr, &end);
3057 /* If no altitude was present, the default 0 should be fine */
3061 latitude_fix = (int32_t) ((1 << 16) * latitude);
3062 longitude_fix = (int32_t) ((1 << 16) * longitude);
3063 altitude_fix = (int32_t) ((1 << 16) * altitude);
3065 avio_wb32(pb, 0); /* size */
3066 ffio_wfourcc(pb, "loci"); /* type */
3067 avio_wb32(pb, 0); /* version + flags */
3068 avio_wb16(pb, lang);
3069 avio_write(pb, place, strlen(place) + 1);
3070 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3071 avio_wb32(pb, latitude_fix);
3072 avio_wb32(pb, longitude_fix);
3073 avio_wb32(pb, altitude_fix);
3074 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3075 avio_w8(pb, 0); /* additional notes, null terminated string */
3077 return update_size(pb, pos);
3080 /* iTunes track or disc number */
3081 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3082 AVFormatContext *s, int disc)
3084 AVDictionaryEntry *t = av_dict_get(s->metadata,
3085 disc ? "disc" : "track",
3087 int size = 0, track = t ? atoi(t->value) : 0;
3090 char *slash = strchr(t->value, '/');
3092 tracks = atoi(slash + 1);
3093 avio_wb32(pb, 32); /* size */
3094 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3095 avio_wb32(pb, 24); /* size */
3096 ffio_wfourcc(pb, "data");
3097 avio_wb32(pb, 0); // 8 bytes empty
3099 avio_wb16(pb, 0); // empty
3100 avio_wb16(pb, track); // track / disc number
3101 avio_wb16(pb, tracks); // total track / disc number
3102 avio_wb16(pb, 0); // empty
3108 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3109 const char *name, const char *tag,
3112 AVDictionaryEntry *t = NULL;
3114 int size = 24 + len;
3116 if (len != 1 && len != 4)
3119 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3121 num = atoi(t->value);
3123 avio_wb32(pb, size);
3124 ffio_wfourcc(pb, name);
3125 avio_wb32(pb, size - 8);
3126 ffio_wfourcc(pb, "data");
3127 avio_wb32(pb, 0x15);
3129 if (len==4) avio_wb32(pb, num);
3130 else avio_w8 (pb, num);
3135 /* iTunes meta data list */
3136 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3139 int64_t pos = avio_tell(pb);
3140 avio_wb32(pb, 0); /* size */
3141 ffio_wfourcc(pb, "ilst");
3142 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3143 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3144 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3145 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3146 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3147 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3148 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3149 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3150 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3152 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3153 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3154 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3155 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3156 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3157 mov_write_string_metadata(s, pb, "desc", "description",1);
3158 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3159 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3160 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3161 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3162 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3163 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3164 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3165 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3166 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3167 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3168 mov_write_trkn_tag(pb, mov, s, 0); // track number
3169 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3170 mov_write_tmpo_tag(pb, s);
3171 return update_size(pb, pos);
3174 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3177 avio_wb32(pb, 33); /* size */
3178 ffio_wfourcc(pb, "hdlr");
3181 ffio_wfourcc(pb, "mdta");
3189 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3192 AVDictionaryEntry *t = NULL;
3193 int64_t pos = avio_tell(pb);
3194 int64_t curpos, entry_pos;
3197 avio_wb32(pb, 0); /* size */
3198 ffio_wfourcc(pb, "keys");
3200 entry_pos = avio_tell(pb);
3201 avio_wb32(pb, 0); /* entry count */
3203 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3204 avio_wb32(pb, strlen(t->key) + 8);
3205 ffio_wfourcc(pb, "mdta");
3206 avio_write(pb, t->key, strlen(t->key));
3209 curpos = avio_tell(pb);
3210 avio_seek(pb, entry_pos, SEEK_SET);
3211 avio_wb32(pb, count); // rewrite entry count
3212 avio_seek(pb, curpos, SEEK_SET);
3214 return update_size(pb, pos);
3217 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3220 AVDictionaryEntry *t = NULL;
3221 int64_t pos = avio_tell(pb);
3222 int count = 1; /* keys are 1-index based */
3224 avio_wb32(pb, 0); /* size */
3225 ffio_wfourcc(pb, "ilst");
3227 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3228 int64_t entry_pos = avio_tell(pb);
3229 avio_wb32(pb, 0); /* size */
3230 avio_wb32(pb, count); /* key */
3231 mov_write_string_data_tag(pb, t->value, 0, 1);
3232 update_size(pb, entry_pos);
3235 return update_size(pb, pos);
3238 /* meta data tags */
3239 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3243 int64_t pos = avio_tell(pb);
3244 avio_wb32(pb, 0); /* size */
3245 ffio_wfourcc(pb, "meta");
3247 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3248 mov_write_mdta_hdlr_tag(pb, mov, s);
3249 mov_write_mdta_keys_tag(pb, mov, s);
3250 mov_write_mdta_ilst_tag(pb, mov, s);
3253 /* iTunes metadata tag */
3254 mov_write_itunes_hdlr_tag(pb, mov, s);
3255 mov_write_ilst_tag(pb, mov, s);
3257 size = update_size(pb, pos);
3261 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3262 const char *name, const char *key)
3265 AVDictionaryEntry *t;
3267 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3270 len = strlen(t->value);
3273 avio_wb32(pb, size);
3274 ffio_wfourcc(pb, name);
3275 avio_write(pb, t->value, len);
3281 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3285 GET_UTF8(val, *b++, return -1;)
3288 avio_wb16(pb, 0x00);
3292 static uint16_t language_code(const char *str)
3294 return (((str[0] - 0x60) & 0x1F) << 10) +
3295 (((str[1] - 0x60) & 0x1F) << 5) +
3296 (( str[2] - 0x60) & 0x1F);
3299 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3300 const char *tag, const char *str)
3302 int64_t pos = avio_tell(pb);
3303 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3304 if (!t || !utf8len(t->value))
3306 avio_wb32(pb, 0); /* size */
3307 ffio_wfourcc(pb, tag); /* type */
3308 avio_wb32(pb, 0); /* version + flags */
3309 if (!strcmp(tag, "yrrc"))
3310 avio_wb16(pb, atoi(t->value));
3312 avio_wb16(pb, language_code("eng")); /* language */
3313 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3314 if (!strcmp(tag, "albm") &&
3315 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3316 avio_w8(pb, atoi(t->value));
3318 return update_size(pb, pos);
3321 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3323 int64_t pos = avio_tell(pb);
3324 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3326 avio_wb32(pb, 0); // size
3327 ffio_wfourcc(pb, "chpl");
3328 avio_wb32(pb, 0x01000000); // version + flags
3329 avio_wb32(pb, 0); // unknown
3330 avio_w8(pb, nb_chapters);
3332 for (i = 0; i < nb_chapters; i++) {
3333 AVChapter *c = s->chapters[i];
3334 AVDictionaryEntry *t;
3335 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3337 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3338 int len = FFMIN(strlen(t->value), 255);
3340 avio_write(pb, t->value, len);
3344 return update_size(pb, pos);
3347 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3350 AVIOContext *pb_buf;
3354 ret = avio_open_dyn_buf(&pb_buf);
3358 if (mov->mode & MODE_3GP) {
3359 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3360 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3361 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3362 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3363 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3364 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3365 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3366 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3367 mov_write_loci_tag(s, pb_buf);
3368 } 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
3369 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3370 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3371 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3372 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3373 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3374 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3375 // currently ignored by mov.c
3376 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3377 // add support for libquicktime, this atom is also actually read by mov.c
3378 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3379 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3380 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3381 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3382 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3383 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3384 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3386 /* iTunes meta data */
3387 mov_write_meta_tag(pb_buf, mov, s);
3388 mov_write_loci_tag(s, pb_buf);
3391 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3392 mov_write_chpl_tag(pb_buf, s);
3394 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3395 avio_wb32(pb, size + 8);
3396 ffio_wfourcc(pb, "udta");
3397 avio_write(pb, buf, size);
3404 static void mov_write_psp_udta_tag(AVIOContext *pb,
3405 const char *str, const char *lang, int type)
3407 int len = utf8len(str) + 1;
3410 avio_wb16(pb, len * 2 + 10); /* size */
3411 avio_wb32(pb, type); /* type */
3412 avio_wb16(pb, language_code(lang)); /* language */
3413 avio_wb16(pb, 0x01); /* ? */
3414 ascii_to_wc(pb, str);
3417 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3419 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3423 pos = avio_tell(pb);
3424 avio_wb32(pb, 0); /* size placeholder*/
3425 ffio_wfourcc(pb, "uuid");
3426 ffio_wfourcc(pb, "USMT");
3427 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3428 avio_wb32(pb, 0xbb88695c);
3429 avio_wb32(pb, 0xfac9c740);
3431 pos2 = avio_tell(pb);
3432 avio_wb32(pb, 0); /* size placeholder*/
3433 ffio_wfourcc(pb, "MTDT");
3437 avio_wb16(pb, 0x0C); /* size */
3438 avio_wb32(pb, 0x0B); /* type */
3439 avio_wb16(pb, language_code("und")); /* language */
3440 avio_wb16(pb, 0x0); /* ? */
3441 avio_wb16(pb, 0x021C); /* data */
3443 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3444 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3445 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3446 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3448 update_size(pb, pos2);
3449 return update_size(pb, pos);
3455 static void build_chunks(MOVTrack *trk)
3458 MOVIentry *chunk = &trk->cluster[0];
3459 uint64_t chunkSize = chunk->size;
3460 chunk->chunkNum = 1;
3461 if (trk->chunkCount)
3463 trk->chunkCount = 1;
3464 for (i = 1; i<trk->entry; i++){
3465 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3466 chunkSize + trk->cluster[i].size < (1<<20)){
3467 chunkSize += trk->cluster[i].size;
3468 chunk->samples_in_chunk += trk->cluster[i].entries;
3470 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3471 chunk=&trk->cluster[i];
3472 chunkSize = chunk->size;
3479 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3480 * the stream ids are used as track ids.
3482 * This assumes mov->tracks and s->streams are in the same order and
3483 * there are no gaps in either of them (so mov->tracks[n] refers to
3486 * As an exception, there can be more entries in
3487 * s->streams than in mov->tracks, in which case new track ids are
3488 * generated (starting after the largest found stream id).
3490 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3494 if (mov->track_ids_ok)
3497 if (mov->use_stream_ids_as_track_ids) {
3498 int next_generated_track_id = 0;
3499 for (i = 0; i < s->nb_streams; i++) {
3500 if (s->streams[i]->id > next_generated_track_id)
3501 next_generated_track_id = s->streams[i]->id;
3504 for (i = 0; i < mov->nb_streams; i++) {
3505 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3508 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3511 for (i = 0; i < mov->nb_streams; i++) {
3512 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3515 mov->tracks[i].track_id = i + 1;
3519 mov->track_ids_ok = 1;
3524 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3528 int64_t pos = avio_tell(pb);
3529 avio_wb32(pb, 0); /* size placeholder*/
3530 ffio_wfourcc(pb, "moov");
3532 mov_setup_track_ids(mov, s);
3534 for (i = 0; i < mov->nb_streams; i++) {
3535 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3538 mov->tracks[i].time = mov->time;
3540 if (mov->tracks[i].entry)
3541 build_chunks(&mov->tracks[i]);
3544 if (mov->chapter_track)
3545 for (i = 0; i < s->nb_streams; i++) {
3546 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3547 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3549 for (i = 0; i < mov->nb_streams; i++) {
3550 MOVTrack *track = &mov->tracks[i];
3551 if (track->tag == MKTAG('r','t','p',' ')) {
3552 track->tref_tag = MKTAG('h','i','n','t');
3553 track->tref_id = mov->tracks[track->src_track].track_id;
3554 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3555 int * fallback, size;
3556 fallback = (int*)av_stream_get_side_data(track->st,
3557 AV_PKT_DATA_FALLBACK_TRACK,
3559 if (fallback != NULL && size == sizeof(int)) {
3560 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3561 track->tref_tag = MKTAG('f','a','l','l');
3562 track->tref_id = mov->tracks[*fallback].track_id;
3567 for (i = 0; i < mov->nb_streams; i++) {
3568 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3569 int src_trk = mov->tracks[i].src_track;
3570 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3571 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3572 //src_trk may have a different timescale than the tmcd track
3573 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3574 mov->tracks[i].timescale,
3575 mov->tracks[src_trk].timescale);
3579 mov_write_mvhd_tag(pb, mov);
3580 if (mov->mode != MODE_MOV && !mov->iods_skip)
3581 mov_write_iods_tag(pb, mov);
3582 for (i = 0; i < mov->nb_streams; i++) {
3583 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3584 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3589 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3590 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3592 if (mov->mode == MODE_PSP)
3593 mov_write_uuidusmt_tag(pb, s);
3595 mov_write_udta_tag(pb, mov, s);
3597 return update_size(pb, pos);
3600 static void param_write_int(AVIOContext *pb, const char *name, int value)
3602 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3605 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3607 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3610 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3613 len = FFMIN(sizeof(buf) / 2 - 1, len);
3614 ff_data_to_hex(buf, value, len, 0);
3615 buf[2 * len] = '\0';
3616 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3619 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3621 int64_t pos = avio_tell(pb);
3623 int64_t manifest_bit_rate = 0;
3624 AVCPBProperties *props = NULL;
3626 static const uint8_t uuid[] = {
3627 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3628 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3632 ffio_wfourcc(pb, "uuid");
3633 avio_write(pb, uuid, sizeof(uuid));
3636 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3637 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3638 avio_printf(pb, "<head>\n");
3639 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3640 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3642 avio_printf(pb, "</head>\n");
3643 avio_printf(pb, "<body>\n");
3644 avio_printf(pb, "<switch>\n");
3646 mov_setup_track_ids(mov, s);
3648 for (i = 0; i < mov->nb_streams; i++) {
3649 MOVTrack *track = &mov->tracks[i];
3651 int track_id = track->track_id;
3652 char track_name_buf[32] = { 0 };
3654 AVStream *st = track->st;
3655 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3657 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3659 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3665 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3667 if (track->par->bit_rate) {
3668 manifest_bit_rate = track->par->bit_rate;
3670 manifest_bit_rate = props->max_bitrate;
3673 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3675 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3676 param_write_int(pb, "trackID", track_id);
3677 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3679 /* Build track name piece by piece: */
3681 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
3682 /* 2. track language, if available */
3684 av_strlcatf(track_name_buf, sizeof(track_name_buf),
3685 "_%s", lang->value);
3686 /* 3. special type suffix */
3687 /* "_cc" = closed captions, "_ad" = audio_description */
3688 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3689 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
3690 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3691 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
3693 param_write_string(pb, "trackName", track_name_buf);
3695 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3696 if (track->par->codec_id == AV_CODEC_ID_H264) {
3698 int size = track->par->extradata_size;
3699 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3701 param_write_hex(pb, "CodecPrivateData",
3702 ptr ? ptr : track->par->extradata,
3706 param_write_string(pb, "FourCC", "H264");
3707 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3708 param_write_string(pb, "FourCC", "WVC1");
3709 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3710 track->par->extradata_size);
3712 param_write_int(pb, "MaxWidth", track->par->width);
3713 param_write_int(pb, "MaxHeight", track->par->height);
3714 param_write_int(pb, "DisplayWidth", track->par->width);
3715 param_write_int(pb, "DisplayHeight", track->par->height);
3717 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3718 switch (track->par->profile)
3720 case FF_PROFILE_AAC_HE_V2:
3721 param_write_string(pb, "FourCC", "AACP");
3723 case FF_PROFILE_AAC_HE:
3724 param_write_string(pb, "FourCC", "AACH");
3727 param_write_string(pb, "FourCC", "AACL");
3729 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3730 param_write_string(pb, "FourCC", "WMAP");
3732 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3733 track->par->extradata_size);
3734 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3735 track->par->codec_id));
3736 param_write_int(pb, "Channels", track->par->channels);
3737 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3738 param_write_int(pb, "BitsPerSample", 16);
3739 param_write_int(pb, "PacketSize", track->par->block_align ?
3740 track->par->block_align : 4);
3742 avio_printf(pb, "</%s>\n", type);
3744 avio_printf(pb, "</switch>\n");
3745 avio_printf(pb, "</body>\n");
3746 avio_printf(pb, "</smil>\n");
3748 return update_size(pb, pos);
3751 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3754 ffio_wfourcc(pb, "mfhd");
3756 avio_wb32(pb, mov->fragments);
3760 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3762 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3763 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3766 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3767 MOVTrack *track, int64_t moof_offset)
3769 int64_t pos = avio_tell(pb);
3770 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3771 MOV_TFHD_BASE_DATA_OFFSET;
3772 if (!track->entry) {
3773 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3775 flags |= MOV_TFHD_DEFAULT_FLAGS;
3777 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3778 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3779 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3780 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3781 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3784 /* Don't set a default sample size, the silverlight player refuses
3785 * to play files with that set. Don't set a default sample duration,
3786 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3787 * file format says it MUST NOT be set. */
3788 if (track->mode == MODE_ISM)
3789 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3790 MOV_TFHD_BASE_DATA_OFFSET);
3792 avio_wb32(pb, 0); /* size placeholder */
3793 ffio_wfourcc(pb, "tfhd");
3794 avio_w8(pb, 0); /* version */
3795 avio_wb24(pb, flags);
3797 avio_wb32(pb, track->track_id); /* track-id */
3798 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3799 avio_wb64(pb, moof_offset);
3800 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3801 track->default_duration = get_cluster_duration(track, 0);
3802 avio_wb32(pb, track->default_duration);
3804 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3805 track->default_size = track->entry ? track->cluster[0].size : 1;
3806 avio_wb32(pb, track->default_size);
3808 track->default_size = -1;
3810 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3811 /* Set the default flags based on the second sample, if available.
3812 * If the first sample is different, that can be signaled via a separate field. */
3813 if (track->entry > 1)
3814 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
3816 track->default_sample_flags =
3817 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
3818 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3819 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3820 avio_wb32(pb, track->default_sample_flags);
3823 return update_size(pb, pos);
3826 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3827 MOVTrack *track, int moof_size,
3830 int64_t pos = avio_tell(pb);
3831 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3834 for (i = first; i < end; i++) {
3835 if (get_cluster_duration(track, i) != track->default_duration)
3836 flags |= MOV_TRUN_SAMPLE_DURATION;
3837 if (track->cluster[i].size != track->default_size)
3838 flags |= MOV_TRUN_SAMPLE_SIZE;
3839 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3840 flags |= MOV_TRUN_SAMPLE_FLAGS;
3842 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
3843 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
3844 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3845 if (track->flags & MOV_TRACK_CTTS)
3846 flags |= MOV_TRUN_SAMPLE_CTS;
3848 avio_wb32(pb, 0); /* size placeholder */
3849 ffio_wfourcc(pb, "trun");
3850 avio_w8(pb, 0); /* version */
3851 avio_wb24(pb, flags);
3853 avio_wb32(pb, end - first); /* sample count */
3854 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3855 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3857 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3859 avio_wb32(pb, moof_size + 8 + track->data_offset +
3860 track->cluster[first].pos); /* data offset */
3861 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3862 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
3864 for (i = first; i < end; i++) {
3865 if (flags & MOV_TRUN_SAMPLE_DURATION)
3866 avio_wb32(pb, get_cluster_duration(track, i));
3867 if (flags & MOV_TRUN_SAMPLE_SIZE)
3868 avio_wb32(pb, track->cluster[i].size);
3869 if (flags & MOV_TRUN_SAMPLE_FLAGS)
3870 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3871 if (flags & MOV_TRUN_SAMPLE_CTS)
3872 avio_wb32(pb, track->cluster[i].cts);
3875 mov->first_trun = 0;
3876 return update_size(pb, pos);
3879 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3881 int64_t pos = avio_tell(pb);
3882 static const uint8_t uuid[] = {
3883 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3884 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3887 avio_wb32(pb, 0); /* size placeholder */
3888 ffio_wfourcc(pb, "uuid");
3889 avio_write(pb, uuid, sizeof(uuid));
3892 avio_wb64(pb, track->start_dts + track->frag_start +
3893 track->cluster[0].cts);
3894 avio_wb64(pb, track->end_pts -
3895 (track->cluster[0].dts + track->cluster[0].cts));
3897 return update_size(pb, pos);
3900 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3901 MOVTrack *track, int entry)
3903 int n = track->nb_frag_info - 1 - entry, i;
3904 int size = 8 + 16 + 4 + 1 + 16*n;
3905 static const uint8_t uuid[] = {
3906 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3907 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3913 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3914 avio_wb32(pb, size);
3915 ffio_wfourcc(pb, "uuid");
3916 avio_write(pb, uuid, sizeof(uuid));
3920 for (i = 0; i < n; i++) {
3921 int index = entry + 1 + i;
3922 avio_wb64(pb, track->frag_info[index].time);
3923 avio_wb64(pb, track->frag_info[index].duration);
3925 if (n < mov->ism_lookahead) {
3926 int free_size = 16 * (mov->ism_lookahead - n);
3927 avio_wb32(pb, free_size);
3928 ffio_wfourcc(pb, "free");
3929 ffio_fill(pb, 0, free_size - 8);
3935 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3938 int64_t pos = avio_tell(pb);
3940 for (i = 0; i < mov->ism_lookahead; i++) {
3941 /* Update the tfrf tag for the last ism_lookahead fragments,
3942 * nb_frag_info - 1 is the next fragment to be written. */
3943 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3945 avio_seek(pb, pos, SEEK_SET);
3949 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3953 for (i = 0; i < mov->nb_streams; i++) {
3954 MOVTrack *track = &mov->tracks[i];
3955 MOVFragmentInfo *info;
3956 if ((tracks >= 0 && i != tracks) || !track->entry)
3958 track->nb_frag_info++;
3959 if (track->nb_frag_info >= track->frag_info_capacity) {
3960 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3961 if (av_reallocp_array(&track->frag_info,
3963 sizeof(*track->frag_info)))
3964 return AVERROR(ENOMEM);
3965 track->frag_info_capacity = new_capacity;
3967 info = &track->frag_info[track->nb_frag_info - 1];
3968 info->offset = avio_tell(pb);
3970 // Try to recreate the original pts for the first packet
3971 // from the fields we have stored
3972 info->time = track->start_dts + track->frag_start +
3973 track->cluster[0].cts;
3974 info->duration = track->end_pts -
3975 (track->cluster[0].dts + track->cluster[0].cts);
3976 // If the pts is less than zero, we will have trimmed
3977 // away parts of the media track using an edit list,
3978 // and the corresponding start presentation time is zero.
3979 if (info->time < 0) {
3980 info->duration += info->time;
3983 info->tfrf_offset = 0;
3984 mov_write_tfrf_tags(pb, mov, track);
3989 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
3992 for (i = 0; i < mov->nb_streams; i++) {
3993 MOVTrack *track = &mov->tracks[i];
3994 if ((tracks >= 0 && i != tracks) || !track->entry)
3996 if (track->nb_frag_info > max) {
3997 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
3998 track->nb_frag_info = max;
4003 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4005 int64_t pos = avio_tell(pb);
4007 avio_wb32(pb, 0); /* size */
4008 ffio_wfourcc(pb, "tfdt");
4009 avio_w8(pb, 1); /* version */
4011 avio_wb64(pb, track->frag_start);
4012 return update_size(pb, pos);
4015 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4016 MOVTrack *track, int64_t moof_offset,
4019 int64_t pos = avio_tell(pb);
4021 avio_wb32(pb, 0); /* size placeholder */
4022 ffio_wfourcc(pb, "traf");
4024 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4025 if (mov->mode != MODE_ISM)
4026 mov_write_tfdt_tag(pb, track);
4027 for (i = 1; i < track->entry; i++) {
4028 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4029 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4033 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4034 if (mov->mode == MODE_ISM) {
4035 mov_write_tfxd_tag(pb, track);
4037 if (mov->ism_lookahead) {
4038 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4040 if (track->nb_frag_info > 0) {
4041 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4042 if (!info->tfrf_offset)
4043 info->tfrf_offset = avio_tell(pb);
4045 avio_wb32(pb, 8 + size);
4046 ffio_wfourcc(pb, "free");
4047 for (i = 0; i < size; i++)
4052 return update_size(pb, pos);
4055 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4056 int tracks, int moof_size)
4058 int64_t pos = avio_tell(pb);
4061 avio_wb32(pb, 0); /* size placeholder */
4062 ffio_wfourcc(pb, "moof");
4063 mov->first_trun = 1;
4065 mov_write_mfhd_tag(pb, mov);
4066 for (i = 0; i < mov->nb_streams; i++) {
4067 MOVTrack *track = &mov->tracks[i];
4068 if (tracks >= 0 && i != tracks)
4072 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4075 return update_size(pb, pos);
4078 static int mov_write_sidx_tag(AVIOContext *pb,
4079 MOVTrack *track, int ref_size, int total_sidx_size)
4081 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4082 int64_t presentation_time, duration, offset;
4083 int starts_with_SAP, i, entries;
4087 presentation_time = track->start_dts + track->frag_start +
4088 track->cluster[0].cts;
4089 duration = track->end_pts -
4090 (track->cluster[0].dts + track->cluster[0].cts);
4091 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4093 // pts<0 should be cut away using edts
4094 if (presentation_time < 0) {
4095 duration += presentation_time;
4096 presentation_time = 0;
4099 entries = track->nb_frag_info;
4102 presentation_time = track->frag_info[0].time;
4105 avio_wb32(pb, 0); /* size */
4106 ffio_wfourcc(pb, "sidx");
4107 avio_w8(pb, 1); /* version */
4109 avio_wb32(pb, track->track_id); /* reference_ID */
4110 avio_wb32(pb, track->timescale); /* timescale */
4111 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4112 offset_pos = avio_tell(pb);
4113 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4114 avio_wb16(pb, 0); /* reserved */
4116 avio_wb16(pb, entries); /* reference_count */
4117 for (i = 0; i < entries; i++) {
4118 if (!track->entry) {
4119 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4120 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4122 duration = track->frag_info[i].duration;
4123 ref_size = track->frag_info[i].size;
4124 starts_with_SAP = 1;
4126 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4127 avio_wb32(pb, duration); /* subsegment_duration */
4128 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4131 end_pos = avio_tell(pb);
4132 offset = pos + total_sidx_size - end_pos;
4133 avio_seek(pb, offset_pos, SEEK_SET);
4134 avio_wb64(pb, offset);
4135 avio_seek(pb, end_pos, SEEK_SET);
4136 return update_size(pb, pos);
4139 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4140 int tracks, int ref_size)
4143 AVIOContext *avio_buf;
4145 for (round = 0; round < 2; round++) {
4146 // First run one round to calculate the total size of all
4148 // This would be much simpler if we'd only write one sidx
4149 // atom, for the first track in the moof.
4151 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4156 for (i = 0; i < mov->nb_streams; i++) {
4157 MOVTrack *track = &mov->tracks[i];
4158 if (tracks >= 0 && i != tracks)
4160 // When writing a sidx for the full file, entry is 0, but
4161 // we want to include all tracks. ref_size is 0 in this case,
4162 // since we read it from frag_info instead.
4163 if (!track->entry && ref_size > 0)
4165 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4169 total_size = ffio_close_null_buf(avio_buf);
4174 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4177 AVIOContext *avio_buf;
4180 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4182 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4183 moof_size = ffio_close_null_buf(avio_buf);
4185 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4186 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4188 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4189 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4190 mov->ism_lookahead) {
4191 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4193 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4194 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4195 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4199 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4202 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4204 int64_t pos = avio_tell(pb);
4207 avio_wb32(pb, 0); /* size placeholder */
4208 ffio_wfourcc(pb, "tfra");
4209 avio_w8(pb, 1); /* version */
4212 avio_wb32(pb, track->track_id);
4213 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4214 avio_wb32(pb, track->nb_frag_info);
4215 for (i = 0; i < track->nb_frag_info; i++) {
4216 avio_wb64(pb, track->frag_info[i].time);
4217 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4218 avio_w8(pb, 1); /* traf number */
4219 avio_w8(pb, 1); /* trun number */
4220 avio_w8(pb, 1); /* sample number */
4223 return update_size(pb, pos);
4226 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4228 int64_t pos = avio_tell(pb);
4231 avio_wb32(pb, 0); /* size placeholder */
4232 ffio_wfourcc(pb, "mfra");
4233 /* An empty mfra atom is enough to indicate to the publishing point that
4234 * the stream has ended. */
4235 if (mov->flags & FF_MOV_FLAG_ISML)
4236 return update_size(pb, pos);
4238 for (i = 0; i < mov->nb_streams; i++) {
4239 MOVTrack *track = &mov->tracks[i];
4240 if (track->nb_frag_info)
4241 mov_write_tfra_tag(pb, track);
4245 ffio_wfourcc(pb, "mfro");
4246 avio_wb32(pb, 0); /* version + flags */
4247 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4249 return update_size(pb, pos);
4252 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4254 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4255 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4257 mov->mdat_pos = avio_tell(pb);
4258 avio_wb32(pb, 0); /* size placeholder*/
4259 ffio_wfourcc(pb, "mdat");
4263 /* TODO: This needs to be more general */
4264 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4266 MOVMuxContext *mov = s->priv_data;
4267 int64_t pos = avio_tell(pb);
4268 int has_h264 = 0, has_video = 0;
4272 for (i = 0; i < s->nb_streams; i++) {
4273 AVStream *st = s->streams[i];
4274 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4276 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4280 avio_wb32(pb, 0); /* size */
4281 ffio_wfourcc(pb, "ftyp");
4283 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4284 ffio_wfourcc(pb, mov->major_brand);
4285 else if (mov->mode == MODE_3GP) {
4286 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4287 minor = has_h264 ? 0x100 : 0x200;
4288 } else if (mov->mode & MODE_3G2) {
4289 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4290 minor = has_h264 ? 0x20000 : 0x10000;
4291 } else if (mov->mode == MODE_PSP)
4292 ffio_wfourcc(pb, "MSNV");
4293 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4294 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4295 else if (mov->mode == MODE_MP4)
4296 ffio_wfourcc(pb, "isom");
4297 else if (mov->mode == MODE_IPOD)
4298 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4299 else if (mov->mode == MODE_ISM)
4300 ffio_wfourcc(pb, "isml");
4301 else if (mov->mode == MODE_F4V)
4302 ffio_wfourcc(pb, "f4v ");
4304 ffio_wfourcc(pb, "qt ");
4306 avio_wb32(pb, minor);
4308 if (mov->mode == MODE_MOV)
4309 ffio_wfourcc(pb, "qt ");
4310 else if (mov->mode == MODE_ISM) {
4311 ffio_wfourcc(pb, "piff");
4312 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4313 ffio_wfourcc(pb, "isom");
4314 ffio_wfourcc(pb, "iso2");
4316 ffio_wfourcc(pb, "avc1");
4319 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4320 // brand. This is compatible with users that don't understand tfdt.
4321 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4322 ffio_wfourcc(pb, "iso6");
4324 if (mov->mode == MODE_3GP)
4325 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4326 else if (mov->mode & MODE_3G2)
4327 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4328 else if (mov->mode == MODE_PSP)
4329 ffio_wfourcc(pb, "MSNV");
4330 else if (mov->mode == MODE_MP4)
4331 ffio_wfourcc(pb, "mp41");
4333 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4334 ffio_wfourcc(pb, "dash");
4336 return update_size(pb, pos);
4339 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4341 AVStream *video_st = s->streams[0];
4342 AVCodecParameters *video_par = s->streams[0]->codecpar;
4343 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4344 int audio_rate = audio_par->sample_rate;
4345 int64_t frame_rate = video_st->avg_frame_rate.den ?
4346 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4348 int audio_kbitrate = audio_par->bit_rate / 1000;
4349 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4351 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4352 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4353 return AVERROR(EINVAL);
4356 avio_wb32(pb, 0x94); /* size */
4357 ffio_wfourcc(pb, "uuid");
4358 ffio_wfourcc(pb, "PROF");
4360 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4361 avio_wb32(pb, 0xbb88695c);
4362 avio_wb32(pb, 0xfac9c740);
4364 avio_wb32(pb, 0x0); /* ? */
4365 avio_wb32(pb, 0x3); /* 3 sections ? */
4367 avio_wb32(pb, 0x14); /* size */
4368 ffio_wfourcc(pb, "FPRF");
4369 avio_wb32(pb, 0x0); /* ? */
4370 avio_wb32(pb, 0x0); /* ? */
4371 avio_wb32(pb, 0x0); /* ? */
4373 avio_wb32(pb, 0x2c); /* size */
4374 ffio_wfourcc(pb, "APRF"); /* audio */
4376 avio_wb32(pb, 0x2); /* TrackID */
4377 ffio_wfourcc(pb, "mp4a");
4378 avio_wb32(pb, 0x20f);
4380 avio_wb32(pb, audio_kbitrate);
4381 avio_wb32(pb, audio_kbitrate);
4382 avio_wb32(pb, audio_rate);
4383 avio_wb32(pb, audio_par->channels);
4385 avio_wb32(pb, 0x34); /* size */
4386 ffio_wfourcc(pb, "VPRF"); /* video */
4388 avio_wb32(pb, 0x1); /* TrackID */
4389 if (video_par->codec_id == AV_CODEC_ID_H264) {
4390 ffio_wfourcc(pb, "avc1");
4391 avio_wb16(pb, 0x014D);
4392 avio_wb16(pb, 0x0015);
4394 ffio_wfourcc(pb, "mp4v");
4395 avio_wb16(pb, 0x0000);
4396 avio_wb16(pb, 0x0103);
4399 avio_wb32(pb, video_kbitrate);
4400 avio_wb32(pb, video_kbitrate);
4401 avio_wb32(pb, frame_rate);
4402 avio_wb32(pb, frame_rate);
4403 avio_wb16(pb, video_par->width);
4404 avio_wb16(pb, video_par->height);
4405 avio_wb32(pb, 0x010001); /* ? */
4410 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4412 MOVMuxContext *mov = s->priv_data;
4415 mov_write_ftyp_tag(pb,s);
4416 if (mov->mode == MODE_PSP) {
4417 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4418 for (i = 0; i < s->nb_streams; i++) {
4419 AVStream *st = s->streams[i];
4420 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4422 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4428 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4429 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4430 return AVERROR(EINVAL);
4432 return mov_write_uuidprof_tag(pb, s);
4437 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4440 int i, closed_gop = 0;
4442 for (i = 0; i < pkt->size - 4; i++) {
4443 c = (c << 8) + pkt->data[i];
4444 if (c == 0x1b8) { // gop
4445 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4446 } else if (c == 0x100) { // pic
4447 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4448 if (!temp_ref || closed_gop) // I picture is not reordered
4449 *flags = MOV_SYNC_SAMPLE;
4451 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4458 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4460 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4461 int seq = 0, entry = 0;
4462 int key = pkt->flags & AV_PKT_FLAG_KEY;
4463 start = find_next_marker(pkt->data, end);
4464 for (next = start; next < end; start = next) {
4465 next = find_next_marker(start + 4, end);
4466 switch (AV_RB32(start)) {
4467 case VC1_CODE_SEQHDR:
4470 case VC1_CODE_ENTRYPOINT:
4473 case VC1_CODE_SLICE:
4474 trk->vc1_info.slices = 1;
4478 if (!trk->entry && trk->vc1_info.first_packet_seen)
4479 trk->vc1_info.first_frag_written = 1;
4480 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4481 /* First packet in first fragment */
4482 trk->vc1_info.first_packet_seq = seq;
4483 trk->vc1_info.first_packet_entry = entry;
4484 trk->vc1_info.first_packet_seen = 1;
4485 } else if ((seq && !trk->vc1_info.packet_seq) ||
4486 (entry && !trk->vc1_info.packet_entry)) {
4488 for (i = 0; i < trk->entry; i++)
4489 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4490 trk->has_keyframes = 0;
4492 trk->vc1_info.packet_seq = 1;
4494 trk->vc1_info.packet_entry = 1;
4495 if (!trk->vc1_info.first_frag_written) {
4496 /* First fragment */
4497 if ((!seq || trk->vc1_info.first_packet_seq) &&
4498 (!entry || trk->vc1_info.first_packet_entry)) {
4499 /* First packet had the same headers as this one, readd the
4500 * sync sample flag. */
4501 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4502 trk->has_keyframes = 1;
4506 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4508 else if (trk->vc1_info.packet_seq)
4510 else if (trk->vc1_info.packet_entry)
4513 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4514 trk->has_keyframes++;
4518 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4520 MOVMuxContext *mov = s->priv_data;
4525 if (!track->mdat_buf)
4527 if (!mov->mdat_buf) {
4528 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4531 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4532 track->mdat_buf = NULL;
4534 offset = avio_tell(mov->mdat_buf);
4535 avio_write(mov->mdat_buf, buf, buf_size);
4538 for (i = track->entries_flushed; i < track->entry; i++)
4539 track->cluster[i].pos += offset;
4540 track->entries_flushed = track->entry;
4544 static int mov_flush_fragment(AVFormatContext *s, int force)
4546 MOVMuxContext *mov = s->priv_data;
4547 int i, first_track = -1;
4548 int64_t mdat_size = 0;
4550 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4552 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4555 // Try to fill in the duration of the last packet in each stream
4556 // from queued packets in the interleave queues. If the flushing
4557 // of fragments was triggered automatically by an AVPacket, we
4558 // already have reliable info for the end of that track, but other
4559 // tracks may need to be filled in.
4560 for (i = 0; i < s->nb_streams; i++) {
4561 MOVTrack *track = &mov->tracks[i];
4562 if (!track->end_reliable) {
4564 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4565 track->track_duration = pkt.dts - track->start_dts;
4566 if (pkt.pts != AV_NOPTS_VALUE)
4567 track->end_pts = pkt.pts;
4569 track->end_pts = pkt.dts;
4574 for (i = 0; i < mov->nb_streams; i++) {
4575 MOVTrack *track = &mov->tracks[i];
4576 if (track->entry <= 1)
4578 // Sample durations are calculated as the diff of dts values,
4579 // but for the last sample in a fragment, we don't know the dts
4580 // of the first sample in the next fragment, so we have to rely
4581 // on what was set as duration in the AVPacket. Not all callers
4582 // set this though, so we might want to replace it with an
4583 // estimate if it currently is zero.
4584 if (get_cluster_duration(track, track->entry - 1) != 0)
4586 // Use the duration (i.e. dts diff) of the second last sample for
4587 // the last one. This is a wild guess (and fatal if it turns out
4588 // to be too long), but probably the best we can do - having a zero
4589 // duration is bad as well.
4590 track->track_duration += get_cluster_duration(track, track->entry - 2);
4591 track->end_pts += get_cluster_duration(track, track->entry - 2);
4592 if (!mov->missing_duration_warned) {
4593 av_log(s, AV_LOG_WARNING,
4594 "Estimating the duration of the last packet in a "
4595 "fragment, consider setting the duration field in "
4596 "AVPacket instead.\n");
4597 mov->missing_duration_warned = 1;
4601 if (!mov->moov_written) {
4602 int64_t pos = avio_tell(s->pb);
4604 int buf_size, moov_size;
4606 for (i = 0; i < mov->nb_streams; i++)
4607 if (!mov->tracks[i].entry)
4609 /* Don't write the initial moov unless all tracks have data */
4610 if (i < mov->nb_streams && !force)
4613 moov_size = get_moov_size(s);
4614 for (i = 0; i < mov->nb_streams; i++)
4615 mov->tracks[i].data_offset = pos + moov_size + 8;
4617 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4618 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4619 mov_write_identification(s->pb, s);
4620 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4623 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4624 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4625 mov->reserved_header_pos = avio_tell(s->pb);
4627 mov->moov_written = 1;
4631 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4632 mov->mdat_buf = NULL;
4633 avio_wb32(s->pb, buf_size + 8);
4634 ffio_wfourcc(s->pb, "mdat");
4635 avio_write(s->pb, buf, buf_size);
4638 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4639 mov->reserved_header_pos = avio_tell(s->pb);
4641 mov->moov_written = 1;
4643 for (i = 0; i < mov->nb_streams; i++) {
4644 if (mov->tracks[i].entry)
4645 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4646 mov->tracks[i].track_duration -
4647 mov->tracks[i].cluster[0].dts;
4648 mov->tracks[i].entry = 0;
4649 mov->tracks[i].end_reliable = 0;
4655 if (mov->frag_interleave) {
4656 for (i = 0; i < mov->nb_streams; i++) {
4657 MOVTrack *track = &mov->tracks[i];
4659 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4665 mdat_size = avio_tell(mov->mdat_buf);
4668 for (i = 0; i < mov->nb_streams; i++) {
4669 MOVTrack *track = &mov->tracks[i];
4670 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4671 track->data_offset = 0;
4673 track->data_offset = mdat_size;
4674 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4676 if (first_video_track) {
4678 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4679 first_video_track = 0;
4684 if (track->mdat_buf)
4685 mdat_size += avio_tell(track->mdat_buf);
4686 if (first_track < 0)
4693 avio_write_marker(s->pb,
4694 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4695 (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);
4697 for (i = 0; i < mov->nb_streams; i++) {
4698 MOVTrack *track = &mov->tracks[i];
4699 int buf_size, write_moof = 1, moof_tracks = -1;
4701 int64_t duration = 0;
4704 duration = track->start_dts + track->track_duration -
4705 track->cluster[0].dts;
4706 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4707 if (!track->mdat_buf)
4709 mdat_size = avio_tell(track->mdat_buf);
4712 write_moof = i == first_track;
4718 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4721 avio_wb32(s->pb, mdat_size + 8);
4722 ffio_wfourcc(s->pb, "mdat");
4726 track->frag_start += duration;
4728 track->entries_flushed = 0;
4729 track->end_reliable = 0;
4730 if (!mov->frag_interleave) {
4731 if (!track->mdat_buf)
4733 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4734 track->mdat_buf = NULL;
4738 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4739 mov->mdat_buf = NULL;
4742 avio_write(s->pb, buf, buf_size);
4752 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4754 MOVMuxContext *mov = s->priv_data;
4755 int had_moov = mov->moov_written;
4756 int ret = mov_flush_fragment(s, force);
4759 // If using delay_moov, the first flush only wrote the moov,
4760 // not the actual moof+mdat pair, thus flush once again.
4761 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4762 ret = mov_flush_fragment(s, force);
4766 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4768 MOVMuxContext *mov = s->priv_data;
4769 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4774 ref = trk->cluster[trk->entry - 1].dts;
4775 } else if ( trk->start_dts != AV_NOPTS_VALUE
4776 && !trk->frag_discont) {
4777 ref = trk->start_dts + trk->track_duration;
4779 ref = pkt->dts; // Skip tests for the first packet
4781 duration = pkt->dts - ref;
4782 if (pkt->dts < ref || duration >= INT_MAX) {
4783 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4788 pkt->pts = AV_NOPTS_VALUE;
4791 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
4792 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
4793 return AVERROR(EINVAL);
4798 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4800 MOVMuxContext *mov = s->priv_data;
4801 AVIOContext *pb = s->pb;
4802 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4803 AVCodecParameters *par = trk->par;
4804 unsigned int samples_in_chunk = 0;
4805 int size = pkt->size, ret = 0;
4806 uint8_t *reformatted_data = NULL;
4808 ret = check_pkt(s, pkt);
4812 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4814 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4815 if (mov->frag_interleave && mov->fragments > 0) {
4816 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
4817 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
4822 if (!trk->mdat_buf) {
4823 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4828 if (!mov->mdat_buf) {
4829 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4836 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
4837 /* We must find out how many AMR blocks there are in one packet */
4838 static const uint16_t packed_size[16] =
4839 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4842 while (len < size && samples_in_chunk < 100) {
4843 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4846 if (samples_in_chunk > 1) {
4847 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4850 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
4851 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4852 samples_in_chunk = trk->par->frame_size;
4853 } else if (trk->sample_size)
4854 samples_in_chunk = size / trk->sample_size;
4856 samples_in_chunk = 1;
4858 /* copy extradata if it exists */
4859 if (trk->vos_len == 0 && par->extradata_size > 0 &&
4860 !TAG_IS_AVCI(trk->tag) &&
4861 (par->codec_id != AV_CODEC_ID_DNXHD)) {
4862 trk->vos_len = par->extradata_size;
4863 trk->vos_data = av_malloc(trk->vos_len);
4864 if (!trk->vos_data) {
4865 ret = AVERROR(ENOMEM);
4868 memcpy(trk->vos_data, par->extradata, trk->vos_len);
4871 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4872 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4873 if (!s->streams[pkt->stream_index]->nb_frames) {
4874 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4875 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4876 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4879 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4881 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4882 /* from x264 or from bytestream H.264 */
4883 /* NAL reformatting needed */
4884 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4885 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4887 avio_write(pb, reformatted_data, size);
4889 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4890 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
4896 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4899 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4900 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4901 /* extradata is Annex B, assume the bitstream is too and convert it */
4902 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4903 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4904 avio_write(pb, reformatted_data, size);
4906 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4908 #if CONFIG_AC3_PARSER
4909 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
4910 size = handle_eac3(mov, pkt, trk);
4915 avio_write(pb, pkt->data, size);
4918 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4919 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
4920 int nal_size_length = (par->extradata[4] & 0x3) + 1;
4921 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
4923 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
4930 avio_write(pb, pkt->data, size);
4934 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
4935 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4936 /* copy frame to create needed atoms */
4937 trk->vos_len = size;
4938 trk->vos_data = av_malloc(size);
4939 if (!trk->vos_data) {
4940 ret = AVERROR(ENOMEM);
4943 memcpy(trk->vos_data, pkt->data, size);
4946 if (trk->entry >= trk->cluster_capacity) {
4947 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4948 if (av_reallocp_array(&trk->cluster, new_capacity,
4949 sizeof(*trk->cluster))) {
4950 ret = AVERROR(ENOMEM);
4953 trk->cluster_capacity = new_capacity;
4956 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
4957 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4958 trk->cluster[trk->entry].chunkNum = 0;
4959 trk->cluster[trk->entry].size = size;
4960 trk->cluster[trk->entry].entries = samples_in_chunk;
4961 trk->cluster[trk->entry].dts = pkt->dts;
4962 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4963 if (!trk->frag_discont) {
4964 /* First packet of a new fragment. We already wrote the duration
4965 * of the last packet of the previous fragment based on track_duration,
4966 * which might not exactly match our dts. Therefore adjust the dts
4967 * of this packet to be what the previous packets duration implies. */
4968 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4969 /* We also may have written the pts and the corresponding duration
4970 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
4971 * the next fragment. This means the cts of the first sample must
4972 * be the same in all fragments, unless end_pts was updated by
4973 * the packet causing the fragment to be written. */
4974 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
4975 mov->mode == MODE_ISM)
4976 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
4978 /* New fragment, but discontinuous from previous fragments.
4979 * Pretend the duration sum of the earlier fragments is
4980 * pkt->dts - trk->start_dts. */
4981 trk->frag_start = pkt->dts - trk->start_dts;
4982 trk->end_pts = AV_NOPTS_VALUE;
4983 trk->frag_discont = 0;
4987 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4988 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4989 /* Not using edit lists and shifting the first track to start from zero.
4990 * If the other streams start from a later timestamp, we won't be able
4991 * to signal the difference in starting time without an edit list.
4992 * Thus move the timestamp for this first sample to 0, increasing
4993 * its duration instead. */
4994 trk->cluster[trk->entry].dts = trk->start_dts = 0;
4996 if (trk->start_dts == AV_NOPTS_VALUE) {
4997 trk->start_dts = pkt->dts;
4998 if (trk->frag_discont) {
4999 if (mov->use_editlist) {
5000 /* Pretend the whole stream started at pts=0, with earlier fragments
5001 * already written. If the stream started at pts=0, the duration sum
5002 * of earlier fragments would have been pkt->pts. */
5003 trk->frag_start = pkt->pts;
5004 trk->start_dts = pkt->dts - pkt->pts;
5006 /* Pretend the whole stream started at dts=0, with earlier fragments
5007 * already written, with a duration summing up to pkt->dts. */
5008 trk->frag_start = pkt->dts;
5011 trk->frag_discont = 0;
5012 } else if (pkt->dts && mov->moov_written)
5013 av_log(s, AV_LOG_WARNING,
5014 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5015 "already has been written. Set the delay_moov flag to handle "
5017 pkt->stream_index, pkt->dts);
5019 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5020 trk->last_sample_is_subtitle_end = 0;
5022 if (pkt->pts == AV_NOPTS_VALUE) {
5023 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5024 pkt->pts = pkt->dts;
5026 if (pkt->dts != pkt->pts)
5027 trk->flags |= MOV_TRACK_CTTS;
5028 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5029 trk->cluster[trk->entry].flags = 0;
5030 if (trk->start_cts == AV_NOPTS_VALUE)
5031 trk->start_cts = pkt->pts - pkt->dts;
5032 if (trk->end_pts == AV_NOPTS_VALUE)
5033 trk->end_pts = trk->cluster[trk->entry].dts +
5034 trk->cluster[trk->entry].cts + pkt->duration;
5036 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5037 trk->cluster[trk->entry].cts +
5040 if (par->codec_id == AV_CODEC_ID_VC1) {
5041 mov_parse_vc1_frame(pkt, trk);
5042 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5043 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5044 trk->entry > 0) { // force sync sample for the first key frame
5045 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5046 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5047 trk->flags |= MOV_TRACK_STPS;
5049 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5051 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5052 trk->has_keyframes++;
5055 trk->sample_count += samples_in_chunk;
5056 mov->mdat_size += size;
5058 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5059 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5060 reformatted_data, size);
5065 av_free(reformatted_data);
5069 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5071 MOVMuxContext *mov = s->priv_data;
5072 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5073 AVCodecParameters *par = trk->par;
5074 int64_t frag_duration = 0;
5075 int size = pkt->size;
5077 int ret = check_pkt(s, pkt);
5081 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5083 for (i = 0; i < s->nb_streams; i++)
5084 mov->tracks[i].frag_discont = 1;
5085 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5089 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5090 trk->start_dts = pkt->dts;
5091 if (pkt->pts != AV_NOPTS_VALUE)
5092 trk->start_cts = pkt->pts - pkt->dts;
5097 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5098 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5100 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5101 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5102 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5104 return AVERROR(ENOMEM);
5105 av_free(par->extradata);
5106 par->extradata = newextra;
5107 memcpy(par->extradata, side, side_size);
5108 par->extradata_size = side_size;
5109 mov->need_rewrite_extradata = 1;
5113 return 0; /* Discard 0 sized packets */
5116 if (trk->entry && pkt->stream_index < s->nb_streams)
5117 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5118 s->streams[pkt->stream_index]->time_base,
5120 if ((mov->max_fragment_duration &&
5121 frag_duration >= mov->max_fragment_duration) ||
5122 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5123 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5124 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5125 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5126 if (frag_duration >= mov->min_fragment_duration) {
5127 // Set the duration of this track to line up with the next
5128 // sample in this track. This avoids relying on AVPacket
5129 // duration, but only helps for this particular track, not
5130 // for the other ones that are flushed at the same time.
5131 trk->track_duration = pkt->dts - trk->start_dts;
5132 if (pkt->pts != AV_NOPTS_VALUE)
5133 trk->end_pts = pkt->pts;
5135 trk->end_pts = pkt->dts;
5136 trk->end_reliable = 1;
5137 mov_auto_flush_fragment(s, 0);
5141 return ff_mov_write_packet(s, pkt);
5144 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5148 uint8_t data[2] = {0};
5151 av_init_packet(&end);
5152 end.size = sizeof(data);
5157 end.stream_index = stream_index;
5159 ret = mov_write_single_packet(s, &end);
5160 av_packet_unref(&end);
5165 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5168 mov_flush_fragment(s, 1);
5172 MOVMuxContext *mov = s->priv_data;
5173 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5176 return mov_write_single_packet(s, pkt); /* Passthrough. */
5179 * Subtitles require special handling.
5181 * 1) For full complaince, every track must have a sample at
5182 * dts == 0, which is rarely true for subtitles. So, as soon
5183 * as we see any packet with dts > 0, write an empty subtitle
5184 * at dts == 0 for any subtitle track with no samples in it.
5186 * 2) For each subtitle track, check if the current packet's
5187 * dts is past the duration of the last subtitle sample. If
5188 * so, we now need to write an end sample for that subtitle.
5190 * This must be done conditionally to allow for subtitles that
5191 * immediately replace each other, in which case an end sample
5192 * is not needed, and is, in fact, actively harmful.
5194 * 3) See mov_write_trailer for how the final end sample is
5197 for (i = 0; i < mov->nb_streams; i++) {
5198 MOVTrack *trk = &mov->tracks[i];
5201 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5202 trk->track_duration < pkt->dts &&
5203 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5204 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5205 if (ret < 0) return ret;
5206 trk->last_sample_is_subtitle_end = 1;
5210 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5211 AVPacket *opkt = pkt;
5212 int reshuffle_ret, ret;
5213 if (trk->is_unaligned_qt_rgb) {
5214 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5215 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5216 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5217 if (reshuffle_ret < 0)
5218 return reshuffle_ret;
5221 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5222 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5227 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5228 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5229 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5230 for (i = 0; i < pkt->size; i++)
5231 pkt->data[i] = ~pkt->data[i];
5233 if (reshuffle_ret) {
5234 ret = mov_write_single_packet(s, pkt);
5237 av_packet_free(&pkt);
5242 return mov_write_single_packet(s, pkt);
5246 // QuickTime chapters involve an additional text track with the chapter names
5247 // as samples, and a tref pointing from the other tracks to the chapter one.
5248 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5252 MOVMuxContext *mov = s->priv_data;
5253 MOVTrack *track = &mov->tracks[tracknum];
5254 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5257 track->mode = mov->mode;
5258 track->tag = MKTAG('t','e','x','t');
5259 track->timescale = MOV_TIMESCALE;
5260 track->par = avcodec_parameters_alloc();
5262 return AVERROR(ENOMEM);
5263 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5265 // These properties are required to make QT recognize the chapter track
5266 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5267 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5268 return AVERROR(ENOMEM);
5269 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5271 if (avio_open_dyn_buf(&pb) >= 0) {
5275 /* Stub header (usually for Quicktime chapter track) */
5277 avio_wb32(pb, 0x01); // displayFlags
5278 avio_w8(pb, 0x00); // horizontal justification
5279 avio_w8(pb, 0x00); // vertical justification
5280 avio_w8(pb, 0x00); // bgColourRed
5281 avio_w8(pb, 0x00); // bgColourGreen
5282 avio_w8(pb, 0x00); // bgColourBlue
5283 avio_w8(pb, 0x00); // bgColourAlpha
5285 avio_wb16(pb, 0x00); // defTextBoxTop
5286 avio_wb16(pb, 0x00); // defTextBoxLeft
5287 avio_wb16(pb, 0x00); // defTextBoxBottom
5288 avio_wb16(pb, 0x00); // defTextBoxRight
5290 avio_wb16(pb, 0x00); // startChar
5291 avio_wb16(pb, 0x00); // endChar
5292 avio_wb16(pb, 0x01); // fontID
5293 avio_w8(pb, 0x00); // fontStyleFlags
5294 avio_w8(pb, 0x00); // fontSize
5295 avio_w8(pb, 0x00); // fgColourRed
5296 avio_w8(pb, 0x00); // fgColourGreen
5297 avio_w8(pb, 0x00); // fgColourBlue
5298 avio_w8(pb, 0x00); // fgColourAlpha
5300 avio_wb32(pb, 0x0D); // box size
5301 ffio_wfourcc(pb, "ftab"); // box atom name
5302 avio_wb16(pb, 0x01); // entry count
5304 avio_wb16(pb, 0x01); // font ID
5305 avio_w8(pb, 0x00); // font name length
5307 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5308 track->par->extradata = buf;
5309 track->par->extradata_size = size;
5316 for (i = 0; i < s->nb_chapters; i++) {
5317 AVChapter *c = s->chapters[i];
5318 AVDictionaryEntry *t;
5320 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5321 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5322 pkt.duration = end - pkt.dts;
5324 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5325 static const char encd[12] = {
5326 0x00, 0x00, 0x00, 0x0C,
5328 0x00, 0x00, 0x01, 0x00 };
5329 len = strlen(t->value);
5330 pkt.size = len + 2 + 12;
5331 pkt.data = av_malloc(pkt.size);
5333 return AVERROR(ENOMEM);
5334 AV_WB16(pkt.data, len);
5335 memcpy(pkt.data + 2, t->value, len);
5336 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5337 ff_mov_write_packet(s, &pkt);
5338 av_freep(&pkt.data);
5346 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5350 /* compute the frame number */
5351 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5355 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5358 MOVMuxContext *mov = s->priv_data;
5359 MOVTrack *track = &mov->tracks[index];
5360 AVStream *src_st = s->streams[src_index];
5361 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5362 AVRational rate = find_fps(s, src_st);
5364 /* tmcd track based on video stream */
5365 track->mode = mov->mode;
5366 track->tag = MKTAG('t','m','c','d');
5367 track->src_track = src_index;
5368 track->timescale = mov->tracks[src_index].timescale;
5369 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5370 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5372 /* set st to src_st for metadata access*/
5375 /* encode context: tmcd data stream */
5376 track->par = avcodec_parameters_alloc();
5378 return AVERROR(ENOMEM);
5379 track->par->codec_type = AVMEDIA_TYPE_DATA;
5380 track->par->codec_tag = track->tag;
5381 track->st->avg_frame_rate = av_inv_q(rate);
5383 /* the tmcd track just contains one packet with the frame number */
5384 pkt.data = av_malloc(pkt.size);
5386 return AVERROR(ENOMEM);
5387 AV_WB32(pkt.data, tc.start);
5388 ret = ff_mov_write_packet(s, &pkt);
5394 * st->disposition controls the "enabled" flag in the tkhd tag.
5395 * QuickTime will not play a track if it is not enabled. So make sure
5396 * that one track of each type (audio, video, subtitle) is enabled.
5398 * Subtitles are special. For audio and video, setting "enabled" also
5399 * makes the track "default" (i.e. it is rendered when played). For
5400 * subtitles, an "enabled" subtitle is not rendered by default, but
5401 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5404 static void enable_tracks(AVFormatContext *s)
5406 MOVMuxContext *mov = s->priv_data;
5408 int enabled[AVMEDIA_TYPE_NB];
5409 int first[AVMEDIA_TYPE_NB];
5411 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5416 for (i = 0; i < s->nb_streams; i++) {
5417 AVStream *st = s->streams[i];
5419 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5420 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5423 if (first[st->codecpar->codec_type] < 0)
5424 first[st->codecpar->codec_type] = i;
5425 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5426 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5427 enabled[st->codecpar->codec_type]++;
5431 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5433 case AVMEDIA_TYPE_VIDEO:
5434 case AVMEDIA_TYPE_AUDIO:
5435 case AVMEDIA_TYPE_SUBTITLE:
5437 mov->per_stream_grouping = 1;
5438 if (!enabled[i] && first[i] >= 0)
5439 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5445 static void mov_free(AVFormatContext *s)
5447 MOVMuxContext *mov = s->priv_data;
5450 if (mov->chapter_track) {
5451 if (mov->tracks[mov->chapter_track].par)
5452 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5453 av_freep(&mov->tracks[mov->chapter_track].par);
5456 for (i = 0; i < mov->nb_streams; i++) {
5457 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5458 ff_mov_close_hinting(&mov->tracks[i]);
5459 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5460 av_freep(&mov->tracks[i].par);
5461 av_freep(&mov->tracks[i].cluster);
5462 av_freep(&mov->tracks[i].frag_info);
5464 if (mov->tracks[i].vos_len)
5465 av_freep(&mov->tracks[i].vos_data);
5467 ff_mov_cenc_free(&mov->tracks[i].cenc);
5470 av_freep(&mov->tracks);
5473 static uint32_t rgb_to_yuv(uint32_t rgb)
5478 r = (rgb >> 16) & 0xFF;
5479 g = (rgb >> 8) & 0xFF;
5482 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5483 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5484 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5486 return (y << 16) | (cr << 8) | cb;
5489 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5492 int i, width = 720, height = 480;
5493 int have_palette = 0, have_size = 0;
5494 uint32_t palette[16];
5495 char *cur = st->codecpar->extradata;
5497 while (cur && *cur) {
5498 if (strncmp("palette:", cur, 8) == 0) {
5500 count = sscanf(cur + 8,
5501 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5502 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5503 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5504 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5505 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5506 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5507 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5508 &palette[12], &palette[13], &palette[14], &palette[15]);
5510 for (i = 0; i < count; i++) {
5511 palette[i] = rgb_to_yuv(palette[i]);
5514 } else if (!strncmp("size:", cur, 5)) {
5515 sscanf(cur + 5, "%dx%d", &width, &height);
5518 if (have_palette && have_size)
5520 cur += strcspn(cur, "\n\r");
5521 cur += strspn(cur, "\n\r");
5524 track->vos_data = av_malloc(16*4);
5525 if (!track->vos_data)
5526 return AVERROR(ENOMEM);
5527 for (i = 0; i < 16; i++) {
5528 AV_WB32(track->vos_data + i * 4, palette[i]);
5530 track->vos_len = 16 * 4;
5532 st->codecpar->width = width;
5533 st->codecpar->height = track->height = height;
5538 static int mov_init(AVFormatContext *s)
5540 MOVMuxContext *mov = s->priv_data;
5541 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5546 /* Default mode == MP4 */
5547 mov->mode = MODE_MP4;
5550 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5551 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5552 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5553 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5554 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5555 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5556 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5559 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5560 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5562 /* Set the FRAGMENT flag if any of the fragmentation methods are
5564 if (mov->max_fragment_duration || mov->max_fragment_size ||
5565 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5566 FF_MOV_FLAG_FRAG_KEYFRAME |
5567 FF_MOV_FLAG_FRAG_CUSTOM))
5568 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5570 /* Set other implicit flags immediately */
5571 if (mov->mode == MODE_ISM)
5572 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5573 FF_MOV_FLAG_FRAGMENT;
5574 if (mov->flags & FF_MOV_FLAG_DASH)
5575 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5576 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5578 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5579 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5580 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5583 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5584 mov->reserved_moov_size = -1;
5587 if (mov->use_editlist < 0) {
5588 mov->use_editlist = 1;
5589 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5590 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5591 // If we can avoid needing an edit list by shifting the
5592 // tracks, prefer that over (trying to) write edit lists
5593 // in fragmented output.
5594 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5595 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5596 mov->use_editlist = 0;
5599 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5600 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5601 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5603 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5604 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5606 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5607 * if the latter is set that's enough and omit_tfhd_offset doesn't
5608 * add anything extra on top of that. */
5609 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5610 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5611 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5613 if (mov->frag_interleave &&
5614 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5615 av_log(s, AV_LOG_ERROR,
5616 "Sample interleaving in fragments is mutually exclusive with "
5617 "omit_tfhd_offset and separate_moof\n");
5618 return AVERROR(EINVAL);
5621 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5622 * is enabled, we don't support non-seekable output at all. */
5623 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
5624 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5625 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5626 return AVERROR(EINVAL);
5629 mov->nb_streams = s->nb_streams;
5630 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5631 mov->chapter_track = mov->nb_streams++;
5633 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5634 /* Add hint tracks for each audio and video stream */
5635 for (i = 0; i < s->nb_streams; i++) {
5636 AVStream *st = s->streams[i];
5637 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5638 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5644 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5645 || mov->write_tmcd == 1) {
5646 /* +1 tmcd track for each video stream with a timecode */
5647 for (i = 0; i < s->nb_streams; i++) {
5648 AVStream *st = s->streams[i];
5649 AVDictionaryEntry *t = global_tcr;
5650 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5651 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5653 ret = mov_check_timecode_track(s, &tc, i, t->value);
5655 mov->nb_meta_tmcd++;
5659 /* check if there is already a tmcd track to remux */
5660 if (mov->nb_meta_tmcd) {
5661 for (i = 0; i < s->nb_streams; i++) {
5662 AVStream *st = s->streams[i];
5663 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5664 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5665 "so timecode metadata are now ignored\n");
5666 mov->nb_meta_tmcd = 0;
5671 mov->nb_streams += mov->nb_meta_tmcd;
5674 // Reserve an extra stream for chapters for the case where chapters
5675 // are written in the trailer
5676 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5678 return AVERROR(ENOMEM);
5680 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5681 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5682 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5684 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5685 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5686 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5687 return AVERROR(EINVAL);
5690 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5691 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5692 mov->encryption_kid_len, CENC_KID_SIZE);
5693 return AVERROR(EINVAL);
5696 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5697 mov->encryption_scheme_str);
5698 return AVERROR(EINVAL);
5702 for (i = 0; i < s->nb_streams; i++) {
5703 AVStream *st= s->streams[i];
5704 MOVTrack *track= &mov->tracks[i];
5705 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5708 track->par = st->codecpar;
5709 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5710 if (track->language < 0)
5711 track->language = 0;
5712 track->mode = mov->mode;
5713 track->tag = mov_find_codec_tag(s, track);
5715 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5716 "codec not currently supported in container\n",
5717 avcodec_get_name(st->codecpar->codec_id), i);
5718 return AVERROR(EINVAL);
5720 /* If hinting of this track is enabled by a later hint track,
5721 * this is updated. */
5722 track->hint_track = -1;
5723 track->start_dts = AV_NOPTS_VALUE;
5724 track->start_cts = AV_NOPTS_VALUE;
5725 track->end_pts = AV_NOPTS_VALUE;
5726 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5727 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5728 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5729 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5730 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5731 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5732 return AVERROR(EINVAL);
5734 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5736 if (mov->video_track_timescale) {
5737 track->timescale = mov->video_track_timescale;
5739 track->timescale = st->time_base.den;
5740 while(track->timescale < 10000)
5741 track->timescale *= 2;
5743 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5744 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5745 return AVERROR(EINVAL);
5747 if (track->mode == MODE_MOV && track->timescale > 100000)
5748 av_log(s, AV_LOG_WARNING,
5749 "WARNING codec timebase is very high. If duration is too long,\n"
5750 "file may not be playable by quicktime. Specify a shorter timebase\n"
5751 "or choose different container.\n");
5752 if (track->mode == MODE_MOV &&
5753 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5754 track->tag == MKTAG('r','a','w',' ')) {
5755 enum AVPixelFormat pix_fmt = track->par->format;
5756 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5757 pix_fmt = AV_PIX_FMT_MONOWHITE;
5758 track->is_unaligned_qt_rgb =
5759 pix_fmt == AV_PIX_FMT_RGB24 ||
5760 pix_fmt == AV_PIX_FMT_BGR24 ||
5761 pix_fmt == AV_PIX_FMT_PAL8 ||
5762 pix_fmt == AV_PIX_FMT_GRAY8 ||
5763 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5764 pix_fmt == AV_PIX_FMT_MONOBLACK;
5766 if (track->par->codec_id == AV_CODEC_ID_VP9) {
5767 if (track->mode != MODE_MP4) {
5768 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
5769 return AVERROR(EINVAL);
5771 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
5772 av_log(s, AV_LOG_ERROR,
5773 "VP9 in MP4 support is experimental, add "
5774 "'-strict %d' if you want to use it.\n",
5775 FF_COMPLIANCE_EXPERIMENTAL);
5776 return AVERROR_EXPERIMENTAL;
5779 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5780 track->timescale = st->codecpar->sample_rate;
5781 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
5782 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
5783 track->audio_vbr = 1;
5784 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
5785 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
5786 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
5787 if (!st->codecpar->block_align) {
5788 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
5789 return AVERROR(EINVAL);
5791 track->sample_size = st->codecpar->block_align;
5792 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
5793 track->audio_vbr = 1;
5795 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
5797 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
5798 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
5799 track->audio_vbr = 1;
5801 if (track->mode != MODE_MOV &&
5802 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
5803 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
5804 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
5805 i, track->par->sample_rate);
5806 return AVERROR(EINVAL);
5808 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
5809 i, track->par->sample_rate);
5812 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
5813 if (track->mode != MODE_MP4) {
5814 av_log(s, AV_LOG_ERROR, "FLAC only supported in MP4.\n");
5815 return AVERROR(EINVAL);
5817 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
5818 av_log(s, AV_LOG_ERROR,
5819 "FLAC in MP4 support is experimental, add "
5820 "'-strict %d' if you want to use it.\n",
5821 FF_COMPLIANCE_EXPERIMENTAL);
5822 return AVERROR_EXPERIMENTAL;
5825 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5826 track->timescale = st->time_base.den;
5827 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
5828 track->timescale = st->time_base.den;
5830 track->timescale = MOV_TIMESCALE;
5833 track->height = st->codecpar->height;
5834 /* The ism specific timescale isn't mandatory, but is assumed by
5835 * some tools, such as mp4split. */
5836 if (mov->mode == MODE_ISM)
5837 track->timescale = 10000000;
5839 avpriv_set_pts_info(st, 64, 1, track->timescale);
5841 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5842 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
5843 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
5853 static int mov_write_header(AVFormatContext *s)
5855 AVIOContext *pb = s->pb;
5856 MOVMuxContext *mov = s->priv_data;
5857 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5858 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
5860 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5863 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5864 /* Add hint tracks for each audio and video stream */
5865 hint_track = nb_tracks;
5866 for (i = 0; i < s->nb_streams; i++) {
5867 AVStream *st = s->streams[i];
5868 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5869 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5875 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5876 tmcd_track = nb_tracks;
5878 for (i = 0; i < s->nb_streams; i++) {
5880 AVStream *st= s->streams[i];
5881 MOVTrack *track= &mov->tracks[i];
5883 /* copy extradata if it exists */
5884 if (st->codecpar->extradata_size) {
5885 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
5886 mov_create_dvd_sub_decoder_specific_info(track, st);
5887 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
5888 track->vos_len = st->codecpar->extradata_size;
5889 track->vos_data = av_malloc(track->vos_len);
5890 if (!track->vos_data) {
5891 return AVERROR(ENOMEM);
5893 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
5897 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5898 track->par->channel_layout != AV_CH_LAYOUT_MONO)
5901 for (j = 0; j < s->nb_streams; j++) {
5902 AVStream *stj= s->streams[j];
5903 MOVTrack *trackj= &mov->tracks[j];
5907 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5908 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
5909 trackj->language != track->language ||
5910 trackj->tag != track->tag
5913 track->multichannel_as_mono++;
5917 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5918 if ((ret = mov_write_identification(pb, s)) < 0)
5922 if (mov->reserved_moov_size){
5923 mov->reserved_header_pos = avio_tell(pb);
5924 if (mov->reserved_moov_size > 0)
5925 avio_skip(pb, mov->reserved_moov_size);
5928 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5929 /* If no fragmentation options have been set, set a default. */
5930 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
5931 FF_MOV_FLAG_FRAG_CUSTOM)) &&
5932 !mov->max_fragment_duration && !mov->max_fragment_size)
5933 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
5935 if (mov->flags & FF_MOV_FLAG_FASTSTART)
5936 mov->reserved_header_pos = avio_tell(pb);
5937 mov_write_mdat_tag(pb, mov);
5940 ff_parse_creation_time_metadata(s, &mov->time, 1);
5942 mov->time += 0x7C25B080; // 1970 based -> 1904 based
5944 if (mov->chapter_track)
5945 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5948 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5949 /* Initialize the hint tracks for each audio and video stream */
5950 for (i = 0; i < s->nb_streams; i++) {
5951 AVStream *st = s->streams[i];
5952 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5953 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5954 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
5961 if (mov->nb_meta_tmcd) {
5962 /* Initialize the tmcd tracks */
5963 for (i = 0; i < s->nb_streams; i++) {
5964 AVStream *st = s->streams[i];
5967 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5970 t = av_dict_get(st->metadata, "timecode", NULL, 0);
5973 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
5975 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
5984 if (mov->flags & FF_MOV_FLAG_ISML)
5985 mov_write_isml_manifest(pb, mov, s);
5987 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5988 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5989 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
5992 mov->moov_written = 1;
5993 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5994 mov->reserved_header_pos = avio_tell(pb);
6000 static int get_moov_size(AVFormatContext *s)
6003 AVIOContext *moov_buf;
6004 MOVMuxContext *mov = s->priv_data;
6006 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6008 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6010 return ffio_close_null_buf(moov_buf);
6013 static int get_sidx_size(AVFormatContext *s)
6017 MOVMuxContext *mov = s->priv_data;
6019 if ((ret = ffio_open_null_buf(&buf)) < 0)
6021 mov_write_sidx_tags(buf, mov, -1, 0);
6022 return ffio_close_null_buf(buf);
6026 * This function gets the moov size if moved to the top of the file: the chunk
6027 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6028 * entries) when the moov is moved to the beginning, so the size of the moov
6029 * would change. It also updates the chunk offset tables.
6031 static int compute_moov_size(AVFormatContext *s)
6033 int i, moov_size, moov_size2;
6034 MOVMuxContext *mov = s->priv_data;
6036 moov_size = get_moov_size(s);
6040 for (i = 0; i < mov->nb_streams; i++)
6041 mov->tracks[i].data_offset += moov_size;
6043 moov_size2 = get_moov_size(s);
6047 /* if the size changed, we just switched from stco to co64 and need to
6048 * update the offsets */
6049 if (moov_size2 != moov_size)
6050 for (i = 0; i < mov->nb_streams; i++)
6051 mov->tracks[i].data_offset += moov_size2 - moov_size;
6056 static int compute_sidx_size(AVFormatContext *s)
6059 MOVMuxContext *mov = s->priv_data;
6061 sidx_size = get_sidx_size(s);
6065 for (i = 0; i < mov->nb_streams; i++)
6066 mov->tracks[i].data_offset += sidx_size;
6071 static int shift_data(AVFormatContext *s)
6073 int ret = 0, moov_size;
6074 MOVMuxContext *mov = s->priv_data;
6075 int64_t pos, pos_end = avio_tell(s->pb);
6076 uint8_t *buf, *read_buf[2];
6077 int read_buf_id = 0;
6079 AVIOContext *read_pb;
6081 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6082 moov_size = compute_sidx_size(s);
6084 moov_size = compute_moov_size(s);
6088 buf = av_malloc(moov_size * 2);
6090 return AVERROR(ENOMEM);
6092 read_buf[1] = buf + moov_size;
6094 /* Shift the data: the AVIO context of the output can only be used for
6095 * writing, so we re-open the same output, but for reading. It also avoids
6096 * a read/seek/write/seek back and forth. */
6098 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6100 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6101 "the second pass (faststart)\n", s->filename);
6105 /* mark the end of the shift to up to the last data we wrote, and get ready
6107 pos_end = avio_tell(s->pb);
6108 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6110 /* start reading at where the new moov will be placed */
6111 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6112 pos = avio_tell(read_pb);
6114 #define READ_BLOCK do { \
6115 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6119 /* shift data by chunk of at most moov_size */
6124 n = read_size[read_buf_id];
6127 avio_write(s->pb, read_buf[read_buf_id], n);
6129 } while (pos < pos_end);
6130 ff_format_io_close(s, &read_pb);
6137 static int mov_write_trailer(AVFormatContext *s)
6139 MOVMuxContext *mov = s->priv_data;
6140 AVIOContext *pb = s->pb;
6145 if (mov->need_rewrite_extradata) {
6146 for (i = 0; i < s->nb_streams; i++) {
6147 MOVTrack *track = &mov->tracks[i];
6148 AVCodecParameters *par = track->par;
6150 track->vos_len = par->extradata_size;
6151 track->vos_data = av_malloc(track->vos_len);
6152 if (!track->vos_data)
6153 return AVERROR(ENOMEM);
6154 memcpy(track->vos_data, par->extradata, track->vos_len);
6156 mov->need_rewrite_extradata = 0;
6160 * Before actually writing the trailer, make sure that there are no
6161 * dangling subtitles, that need a terminating sample.
6163 for (i = 0; i < mov->nb_streams; i++) {
6164 MOVTrack *trk = &mov->tracks[i];
6165 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6166 !trk->last_sample_is_subtitle_end) {
6167 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6168 trk->last_sample_is_subtitle_end = 1;
6172 // If there were no chapters when the header was written, but there
6173 // are chapters now, write them in the trailer. This only works
6174 // when we are not doing fragments.
6175 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6176 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6177 mov->chapter_track = mov->nb_streams++;
6178 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6183 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6184 moov_pos = avio_tell(pb);
6186 /* Write size of mdat tag */
6187 if (mov->mdat_size + 8 <= UINT32_MAX) {
6188 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6189 avio_wb32(pb, mov->mdat_size + 8);
6191 /* overwrite 'wide' placeholder atom */
6192 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6193 /* special value: real atom size will be 64 bit value after
6196 ffio_wfourcc(pb, "mdat");
6197 avio_wb64(pb, mov->mdat_size + 16);
6199 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6201 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6202 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6203 res = shift_data(s);
6206 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6207 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6209 } else if (mov->reserved_moov_size > 0) {
6211 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6213 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6215 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6216 return AVERROR(EINVAL);
6218 avio_wb32(pb, size);
6219 ffio_wfourcc(pb, "free");
6220 ffio_fill(pb, 0, size - 8);
6221 avio_seek(pb, moov_pos, SEEK_SET);
6223 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6228 mov_auto_flush_fragment(s, 1);
6229 for (i = 0; i < mov->nb_streams; i++)
6230 mov->tracks[i].data_offset = 0;
6231 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6233 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6234 res = shift_data(s);
6237 end = avio_tell(pb);
6238 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6239 mov_write_sidx_tags(pb, mov, -1, 0);
6240 avio_seek(pb, end, SEEK_SET);
6241 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6242 mov_write_mfra_tag(pb, mov);
6243 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6244 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6245 mov_write_mfra_tag(pb, mov);
6252 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6255 AVStream *st = s->streams[pkt->stream_index];
6257 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6258 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6259 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6265 #if CONFIG_MOV_MUXER
6267 AVOutputFormat ff_mov_muxer = {
6269 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6270 .extensions = "mov",
6271 .priv_data_size = sizeof(MOVMuxContext),
6272 .audio_codec = AV_CODEC_ID_AAC,
6273 .video_codec = CONFIG_LIBX264_ENCODER ?
6274 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6276 .write_header = mov_write_header,
6277 .write_packet = mov_write_packet,
6278 .write_trailer = mov_write_trailer,
6280 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6281 .codec_tag = (const AVCodecTag* const []){
6282 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6284 .check_bitstream = mov_check_bitstream,
6285 .priv_class = &mov_muxer_class,
6288 #if CONFIG_TGP_MUXER
6290 AVOutputFormat ff_tgp_muxer = {
6292 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6293 .extensions = "3gp",
6294 .priv_data_size = sizeof(MOVMuxContext),
6295 .audio_codec = AV_CODEC_ID_AMR_NB,
6296 .video_codec = AV_CODEC_ID_H263,
6298 .write_header = mov_write_header,
6299 .write_packet = mov_write_packet,
6300 .write_trailer = mov_write_trailer,
6302 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6303 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6304 .check_bitstream = mov_check_bitstream,
6305 .priv_class = &tgp_muxer_class,
6308 #if CONFIG_MP4_MUXER
6310 AVOutputFormat ff_mp4_muxer = {
6312 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6313 .mime_type = "video/mp4",
6314 .extensions = "mp4",
6315 .priv_data_size = sizeof(MOVMuxContext),
6316 .audio_codec = AV_CODEC_ID_AAC,
6317 .video_codec = CONFIG_LIBX264_ENCODER ?
6318 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6320 .write_header = mov_write_header,
6321 .write_packet = mov_write_packet,
6322 .write_trailer = mov_write_trailer,
6324 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6325 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6326 .check_bitstream = mov_check_bitstream,
6327 .priv_class = &mp4_muxer_class,
6330 #if CONFIG_PSP_MUXER
6332 AVOutputFormat ff_psp_muxer = {
6334 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6335 .extensions = "mp4,psp",
6336 .priv_data_size = sizeof(MOVMuxContext),
6337 .audio_codec = AV_CODEC_ID_AAC,
6338 .video_codec = CONFIG_LIBX264_ENCODER ?
6339 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6341 .write_header = mov_write_header,
6342 .write_packet = mov_write_packet,
6343 .write_trailer = mov_write_trailer,
6345 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6346 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6347 .check_bitstream = mov_check_bitstream,
6348 .priv_class = &psp_muxer_class,
6351 #if CONFIG_TG2_MUXER
6353 AVOutputFormat ff_tg2_muxer = {
6355 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6356 .extensions = "3g2",
6357 .priv_data_size = sizeof(MOVMuxContext),
6358 .audio_codec = AV_CODEC_ID_AMR_NB,
6359 .video_codec = AV_CODEC_ID_H263,
6361 .write_header = mov_write_header,
6362 .write_packet = mov_write_packet,
6363 .write_trailer = mov_write_trailer,
6365 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6366 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6367 .check_bitstream = mov_check_bitstream,
6368 .priv_class = &tg2_muxer_class,
6371 #if CONFIG_IPOD_MUXER
6373 AVOutputFormat ff_ipod_muxer = {
6375 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6376 .mime_type = "video/mp4",
6377 .extensions = "m4v,m4a",
6378 .priv_data_size = sizeof(MOVMuxContext),
6379 .audio_codec = AV_CODEC_ID_AAC,
6380 .video_codec = AV_CODEC_ID_H264,
6382 .write_header = mov_write_header,
6383 .write_packet = mov_write_packet,
6384 .write_trailer = mov_write_trailer,
6386 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6387 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6388 .check_bitstream = mov_check_bitstream,
6389 .priv_class = &ipod_muxer_class,
6392 #if CONFIG_ISMV_MUXER
6394 AVOutputFormat ff_ismv_muxer = {
6396 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6397 .mime_type = "video/mp4",
6398 .extensions = "ismv,isma",
6399 .priv_data_size = sizeof(MOVMuxContext),
6400 .audio_codec = AV_CODEC_ID_AAC,
6401 .video_codec = AV_CODEC_ID_H264,
6403 .write_header = mov_write_header,
6404 .write_packet = mov_write_packet,
6405 .write_trailer = mov_write_trailer,
6407 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6408 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6409 .check_bitstream = mov_check_bitstream,
6410 .priv_class = &ismv_muxer_class,
6413 #if CONFIG_F4V_MUXER
6415 AVOutputFormat ff_f4v_muxer = {
6417 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6418 .mime_type = "application/f4v",
6419 .extensions = "f4v",
6420 .priv_data_size = sizeof(MOVMuxContext),
6421 .audio_codec = AV_CODEC_ID_AAC,
6422 .video_codec = AV_CODEC_ID_H264,
6424 .write_header = mov_write_header,
6425 .write_packet = mov_write_packet,
6426 .write_trailer = mov_write_trailer,
6428 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6429 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6430 .check_bitstream = mov_check_bitstream,
6431 .priv_class = &f4v_muxer_class,