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/get_bits.h"
37 #include "libavcodec/put_bits.h"
38 #include "libavcodec/vc1_common.h"
39 #include "libavcodec/raw.h"
41 #include "libavutil/avstring.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/libm.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/dict.h"
47 #include "libavutil/pixdesc.h"
48 #include "libavutil/timecode.h"
49 #include "libavutil/color_utils.h"
55 static const AVOption options[] = {
56 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
57 { "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" },
58 { "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 },
59 { "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" },
60 { "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" },
61 { "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" },
62 { "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" },
63 { "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" },
64 { "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" },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 { "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" },
73 { "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" },
74 { "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" },
75 { "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" },
76 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
77 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
78 { "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},
79 { "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},
80 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
81 { "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},
82 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
83 { "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},
84 { "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},
85 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
86 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
87 { "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},
88 { "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},
89 { "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 },
90 { "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 },
91 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
92 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
93 { "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},
94 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
98 #define MOV_CLASS(flavor)\
99 static const AVClass flavor ## _muxer_class = {\
100 .class_name = #flavor " muxer",\
101 .item_name = av_default_item_name,\
103 .version = LIBAVUTIL_VERSION_INT,\
106 static int get_moov_size(AVFormatContext *s);
108 static int utf8len(const uint8_t *b)
113 GET_UTF8(val, *b++, return -1;)
119 //FIXME support 64 bit variant with wide placeholders
120 static int64_t update_size(AVIOContext *pb, int64_t pos)
122 int64_t curpos = avio_tell(pb);
123 avio_seek(pb, pos, SEEK_SET);
124 avio_wb32(pb, curpos - pos); /* rewrite size */
125 avio_seek(pb, curpos, SEEK_SET);
130 static int co64_required(const MOVTrack *track)
132 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
137 /* Chunk offset atom */
138 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
141 int mode64 = co64_required(track); // use 32 bit size variant if possible
142 int64_t pos = avio_tell(pb);
143 avio_wb32(pb, 0); /* size */
145 ffio_wfourcc(pb, "co64");
147 ffio_wfourcc(pb, "stco");
148 avio_wb32(pb, 0); /* version & flags */
149 avio_wb32(pb, track->chunkCount); /* entry count */
150 for (i = 0; i < track->entry; i++) {
151 if (!track->cluster[i].chunkNum)
154 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
156 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
158 return update_size(pb, pos);
161 /* Sample size atom */
162 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
165 int i, j, entries = 0, tst = -1, oldtst = -1;
167 int64_t pos = avio_tell(pb);
168 avio_wb32(pb, 0); /* size */
169 ffio_wfourcc(pb, "stsz");
170 avio_wb32(pb, 0); /* version & flags */
172 for (i = 0; i < track->entry; i++) {
173 tst = track->cluster[i].size / track->cluster[i].entries;
174 if (oldtst != -1 && tst != oldtst)
177 entries += track->cluster[i].entries;
179 if (equalChunks && track->entry) {
180 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
181 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
182 avio_wb32(pb, sSize); // sample size
183 avio_wb32(pb, entries); // sample count
185 avio_wb32(pb, 0); // sample size
186 avio_wb32(pb, entries); // sample count
187 for (i = 0; i < track->entry; i++) {
188 for (j = 0; j < track->cluster[i].entries; j++) {
189 avio_wb32(pb, track->cluster[i].size /
190 track->cluster[i].entries);
194 return update_size(pb, pos);
197 /* Sample to chunk atom */
198 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
200 int index = 0, oldval = -1, i;
201 int64_t entryPos, curpos;
203 int64_t pos = avio_tell(pb);
204 avio_wb32(pb, 0); /* size */
205 ffio_wfourcc(pb, "stsc");
206 avio_wb32(pb, 0); // version & flags
207 entryPos = avio_tell(pb);
208 avio_wb32(pb, track->chunkCount); // entry count
209 for (i = 0; i < track->entry; i++) {
210 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
211 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
212 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
213 avio_wb32(pb, 0x1); // sample description index
214 oldval = track->cluster[i].samples_in_chunk;
218 curpos = avio_tell(pb);
219 avio_seek(pb, entryPos, SEEK_SET);
220 avio_wb32(pb, index); // rewrite size
221 avio_seek(pb, curpos, SEEK_SET);
223 return update_size(pb, pos);
226 /* Sync sample atom */
227 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
229 int64_t curpos, entryPos;
231 int64_t pos = avio_tell(pb);
232 avio_wb32(pb, 0); // size
233 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
234 avio_wb32(pb, 0); // version & flags
235 entryPos = avio_tell(pb);
236 avio_wb32(pb, track->entry); // entry count
237 for (i = 0; i < track->entry; i++) {
238 if (track->cluster[i].flags & flag) {
239 avio_wb32(pb, i + 1);
243 curpos = avio_tell(pb);
244 avio_seek(pb, entryPos, SEEK_SET);
245 avio_wb32(pb, index); // rewrite size
246 avio_seek(pb, curpos, SEEK_SET);
247 return update_size(pb, pos);
250 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
252 avio_wb32(pb, 0x11); /* size */
253 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
254 else ffio_wfourcc(pb, "damr");
255 ffio_wfourcc(pb, "FFMP");
256 avio_w8(pb, 0); /* decoder version */
258 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
259 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
260 avio_w8(pb, 0x01); /* Frames per sample */
264 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
269 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
271 if (track->vos_len < 7)
275 ffio_wfourcc(pb, "dac3");
277 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
278 fscod = get_bits(&gbc, 2);
279 frmsizecod = get_bits(&gbc, 6);
280 bsid = get_bits(&gbc, 5);
281 bsmod = get_bits(&gbc, 3);
282 acmod = get_bits(&gbc, 3);
284 skip_bits(&gbc, 2); // dsurmod
286 if ((acmod & 1) && acmod != 1)
287 skip_bits(&gbc, 2); // cmixlev
289 skip_bits(&gbc, 2); // surmixlev
291 lfeon = get_bits1(&gbc);
293 init_put_bits(&pbc, buf, sizeof(buf));
294 put_bits(&pbc, 2, fscod);
295 put_bits(&pbc, 5, bsid);
296 put_bits(&pbc, 3, bsmod);
297 put_bits(&pbc, 3, acmod);
298 put_bits(&pbc, 1, lfeon);
299 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
300 put_bits(&pbc, 5, 0); // reserved
302 flush_put_bits(&pbc);
303 avio_write(pb, buf, sizeof(buf));
313 /* Layout of the EC3SpecificBox */
314 /* maximum bitrate */
316 /* number of independent substreams */
319 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
321 /* bit stream identification 5 bits */
323 /* one bit reserved */
324 /* audio service mixing (not supported yet) 1 bit */
325 /* bit stream mode 3 bits */
327 /* audio coding mode 3 bits */
329 /* sub woofer on 1 bit */
331 /* 3 bits reserved */
332 /* number of dependent substreams associated with this substream 4 bits */
334 /* channel locations of the dependent substream(s), if any, 9 bits */
336 /* if there is no dependent substream, then one bit reserved instead */
337 } substream[1]; /* TODO: support 8 independent substreams */
340 #if CONFIG_AC3_PARSER
341 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
344 AC3HeaderInfo tmp, *hdr = &tmp;
345 struct eac3_info *info;
348 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
349 return AVERROR(ENOMEM);
350 info = track->eac3_priv;
352 init_get_bits(&gbc, pkt->data, pkt->size * 8);
353 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
354 /* drop the packets until we see a good one */
356 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
359 return AVERROR_INVALIDDATA;
362 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
363 num_blocks = hdr->num_blocks;
365 if (!info->ec3_done) {
366 /* AC-3 substream must be the first one */
367 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
368 return AVERROR(EINVAL);
370 /* this should always be the case, given that our AC-3 parser
371 * concatenates dependent frames to their independent parent */
372 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
373 /* substream ids must be incremental */
374 if (hdr->substreamid > info->num_ind_sub + 1)
375 return AVERROR(EINVAL);
377 if (hdr->substreamid == info->num_ind_sub + 1) {
378 //info->num_ind_sub++;
379 avpriv_request_sample(track->par, "Multiple independent substreams");
380 return AVERROR_PATCHWELCOME;
381 } else if (hdr->substreamid < info->num_ind_sub ||
382 hdr->substreamid == 0 && info->substream[0].bsid) {
388 /* fill the info needed for the "dec3" atom */
389 info->substream[hdr->substreamid].fscod = hdr->sr_code;
390 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
391 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
392 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
393 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
395 /* Parse dependent substream(s), if any */
396 if (pkt->size != hdr->frame_size) {
397 int cumul_size = hdr->frame_size;
398 int parent = hdr->substreamid;
400 while (cumul_size != pkt->size) {
402 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
403 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
404 return AVERROR_INVALIDDATA;
405 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
406 return AVERROR(EINVAL);
407 cumul_size += hdr->frame_size;
408 info->substream[parent].num_dep_sub++;
410 /* header is parsed up to lfeon, but custom channel map may be needed */
413 /* skip volume control params */
414 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
415 skip_bits(&gbc, 5); // skip dialog normalization
416 if (get_bits1(&gbc)) {
417 skip_bits(&gbc, 8); // skip compression gain word
420 /* get the dependent stream channel map, if exists */
422 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
424 info->substream[parent].chan_loc |= hdr->channel_mode;
430 if (!info->num_blocks && num_blocks == 6)
432 else if (info->num_blocks + num_blocks > 6)
433 return AVERROR_INVALIDDATA;
435 if (!info->num_blocks) {
437 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
439 info->num_blocks = num_blocks;
443 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
445 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
446 info->num_blocks += num_blocks;
447 info->pkt.duration += pkt->duration;
448 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
450 if (info->num_blocks != 6)
452 av_packet_unref(pkt);
453 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
455 av_packet_unref(&info->pkt);
456 info->num_blocks = 0;
463 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
467 struct eac3_info *info;
470 if (!track->eac3_priv)
471 return AVERROR(EINVAL);
473 info = track->eac3_priv;
474 size = 2 + 4 * (info->num_ind_sub + 1);
475 buf = av_malloc(size);
477 size = AVERROR(ENOMEM);
481 init_put_bits(&pbc, buf, size);
482 put_bits(&pbc, 13, info->data_rate);
483 put_bits(&pbc, 3, info->num_ind_sub);
484 for (i = 0; i <= info->num_ind_sub; i++) {
485 put_bits(&pbc, 2, info->substream[i].fscod);
486 put_bits(&pbc, 5, info->substream[i].bsid);
487 put_bits(&pbc, 1, 0); /* reserved */
488 put_bits(&pbc, 1, 0); /* asvc */
489 put_bits(&pbc, 3, info->substream[i].bsmod);
490 put_bits(&pbc, 3, info->substream[i].acmod);
491 put_bits(&pbc, 1, info->substream[i].lfeon);
492 put_bits(&pbc, 5, 0); /* reserved */
493 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
494 if (!info->substream[i].num_dep_sub) {
495 put_bits(&pbc, 1, 0); /* reserved */
498 put_bits(&pbc, 9, info->substream[i].chan_loc);
501 flush_put_bits(&pbc);
503 avio_wb32(pb, size + 8);
504 ffio_wfourcc(pb, "dec3");
505 avio_write(pb, buf, size);
510 av_packet_unref(&info->pkt);
511 av_freep(&track->eac3_priv);
517 * This function writes extradata "as is".
518 * Extradata must be formatted like a valid atom (with size and tag).
520 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
522 avio_write(pb, track->par->extradata, track->par->extradata_size);
523 return track->par->extradata_size;
526 static int mov_write_enda_tag(AVIOContext *pb)
529 ffio_wfourcc(pb, "enda");
530 avio_wb16(pb, 1); /* little endian */
534 static int mov_write_enda_tag_be(AVIOContext *pb)
537 ffio_wfourcc(pb, "enda");
538 avio_wb16(pb, 0); /* big endian */
542 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
547 avio_w8(pb, (size >> (7 * i)) | 0x80);
548 avio_w8(pb, size & 0x7F);
551 static unsigned compute_avg_bitrate(MOVTrack *track)
555 if (!track->track_duration)
557 for (i = 0; i < track->entry; i++)
558 size += track->cluster[i].size;
559 return size * 8 * track->timescale / track->track_duration;
562 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
564 AVCPBProperties *props;
565 int64_t pos = avio_tell(pb);
566 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
567 unsigned avg_bitrate;
569 avio_wb32(pb, 0); // size
570 ffio_wfourcc(pb, "esds");
571 avio_wb32(pb, 0); // Version
574 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
575 avio_wb16(pb, track->track_id);
576 avio_w8(pb, 0x00); // flags (= no flags)
578 // DecoderConfig descriptor
579 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
581 // Object type indication
582 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
583 track->par->codec_id == AV_CODEC_ID_MP3) &&
584 track->par->sample_rate > 24000)
585 avio_w8(pb, 0x6B); // 11172-3
587 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
589 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
590 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
591 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
592 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
593 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
594 avio_w8(pb, 0x15); // flags (= Audiostream)
596 avio_w8(pb, 0x11); // flags (= Visualstream)
598 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
601 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
603 avg_bitrate = compute_avg_bitrate(track);
604 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)
605 avio_wb32(pb, avg_bitrate);
607 if (track->vos_len) {
608 // DecoderSpecific info descriptor
609 put_descr(pb, 0x05, track->vos_len);
610 avio_write(pb, track->vos_data, track->vos_len);
614 put_descr(pb, 0x06, 1);
616 return update_size(pb, pos);
619 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
621 return codec_id == AV_CODEC_ID_PCM_S24LE ||
622 codec_id == AV_CODEC_ID_PCM_S32LE ||
623 codec_id == AV_CODEC_ID_PCM_F32LE ||
624 codec_id == AV_CODEC_ID_PCM_F64LE;
627 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
629 return codec_id == AV_CODEC_ID_PCM_S24BE ||
630 codec_id == AV_CODEC_ID_PCM_S32BE ||
631 codec_id == AV_CODEC_ID_PCM_F32BE ||
632 codec_id == AV_CODEC_ID_PCM_F64BE;
635 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
638 int64_t pos = avio_tell(pb);
640 avio_wl32(pb, track->tag); // store it byteswapped
641 track->par->codec_tag = av_bswap16(track->tag >> 16);
642 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
644 return update_size(pb, pos);
647 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
650 int64_t pos = avio_tell(pb);
652 ffio_wfourcc(pb, "wfex");
653 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
655 return update_size(pb, pos);
658 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
660 uint32_t layout_tag, bitmap;
661 int64_t pos = avio_tell(pb);
663 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
664 track->par->channel_layout,
667 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
668 "lack of channel information\n");
672 if (track->multichannel_as_mono)
675 avio_wb32(pb, 0); // Size
676 ffio_wfourcc(pb, "chan"); // Type
677 avio_w8(pb, 0); // Version
678 avio_wb24(pb, 0); // Flags
679 avio_wb32(pb, layout_tag); // mChannelLayoutTag
680 avio_wb32(pb, bitmap); // mChannelBitmap
681 avio_wb32(pb, 0); // mNumberChannelDescriptions
683 return update_size(pb, pos);
686 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
688 int64_t pos = avio_tell(pb);
690 avio_wb32(pb, 0); /* size */
691 ffio_wfourcc(pb, "wave");
693 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
694 avio_wb32(pb, 12); /* size */
695 ffio_wfourcc(pb, "frma");
696 avio_wl32(pb, track->tag);
699 if (track->par->codec_id == AV_CODEC_ID_AAC) {
700 /* useless atom needed by mplayer, ipod, not needed by quicktime */
701 avio_wb32(pb, 12); /* size */
702 ffio_wfourcc(pb, "mp4a");
704 mov_write_esds_tag(pb, track);
705 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
706 mov_write_enda_tag(pb);
707 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
708 mov_write_enda_tag_be(pb);
709 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
710 mov_write_amr_tag(pb, track);
711 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
712 mov_write_ac3_tag(pb, track);
713 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
714 mov_write_eac3_tag(pb, track);
715 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
716 track->par->codec_id == AV_CODEC_ID_QDM2) {
717 mov_write_extradata_tag(pb, track);
718 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
719 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
720 mov_write_ms_tag(s, pb, track);
723 avio_wb32(pb, 8); /* size */
724 avio_wb32(pb, 0); /* null tag */
726 return update_size(pb, pos);
729 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
732 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
733 int unescaped_size, seq_found = 0;
734 int level = 0, interlace = 0;
735 int packet_seq = track->vc1_info.packet_seq;
736 int packet_entry = track->vc1_info.packet_entry;
737 int slices = track->vc1_info.slices;
740 if (track->start_dts == AV_NOPTS_VALUE) {
741 /* No packets written yet, vc1_info isn't authoritative yet. */
742 /* Assume inline sequence and entry headers. */
743 packet_seq = packet_entry = 1;
744 av_log(NULL, AV_LOG_WARNING,
745 "moov atom written before any packets, unable to write correct "
746 "dvc1 atom. Set the delay_moov flag to fix this.\n");
749 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
751 return AVERROR(ENOMEM);
752 start = find_next_marker(track->vos_data, end);
753 for (next = start; next < end; start = next) {
756 next = find_next_marker(start + 4, end);
757 size = next - start - 4;
760 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
761 init_get_bits(&gb, unescaped, 8 * unescaped_size);
762 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
763 int profile = get_bits(&gb, 2);
764 if (profile != PROFILE_ADVANCED) {
766 return AVERROR(ENOSYS);
769 level = get_bits(&gb, 3);
770 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
772 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
773 skip_bits(&gb, 1); /* broadcast */
774 interlace = get_bits1(&gb);
775 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
780 return AVERROR(ENOSYS);
783 init_put_bits(&pbc, buf, 7);
784 /* VC1DecSpecStruc */
785 put_bits(&pbc, 4, 12); /* profile - advanced */
786 put_bits(&pbc, 3, level);
787 put_bits(&pbc, 1, 0); /* reserved */
788 /* VC1AdvDecSpecStruc */
789 put_bits(&pbc, 3, level);
790 put_bits(&pbc, 1, 0); /* cbr */
791 put_bits(&pbc, 6, 0); /* reserved */
792 put_bits(&pbc, 1, !interlace); /* no interlace */
793 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
794 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
795 put_bits(&pbc, 1, !slices); /* no slice code */
796 put_bits(&pbc, 1, 0); /* no bframe */
797 put_bits(&pbc, 1, 0); /* reserved */
800 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
801 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
803 put_bits32(&pbc, 0xffffffff);
805 flush_put_bits(&pbc);
812 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
814 uint8_t buf[7] = { 0 };
817 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
820 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
821 ffio_wfourcc(pb, "dvc1");
822 avio_write(pb, buf, sizeof(buf));
823 avio_write(pb, track->vos_data, track->vos_len);
828 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
830 avio_wb32(pb, track->vos_len + 8);
831 ffio_wfourcc(pb, "glbl");
832 avio_write(pb, track->vos_data, track->vos_len);
833 return 8 + track->vos_len;
837 * Compute flags for 'lpcm' tag.
838 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
840 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
843 case AV_CODEC_ID_PCM_F32BE:
844 case AV_CODEC_ID_PCM_F64BE:
846 case AV_CODEC_ID_PCM_F32LE:
847 case AV_CODEC_ID_PCM_F64LE:
849 case AV_CODEC_ID_PCM_U8:
851 case AV_CODEC_ID_PCM_S16BE:
852 case AV_CODEC_ID_PCM_S24BE:
853 case AV_CODEC_ID_PCM_S32BE:
855 case AV_CODEC_ID_PCM_S8:
856 case AV_CODEC_ID_PCM_S16LE:
857 case AV_CODEC_ID_PCM_S24LE:
858 case AV_CODEC_ID_PCM_S32LE:
865 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
869 if (cluster_idx >= track->entry)
872 if (cluster_idx + 1 == track->entry)
873 next_dts = track->track_duration + track->start_dts;
875 next_dts = track->cluster[cluster_idx + 1].dts;
877 next_dts -= track->cluster[cluster_idx].dts;
879 av_assert0(next_dts >= 0);
880 av_assert0(next_dts <= INT_MAX);
885 static int get_samples_per_packet(MOVTrack *track)
887 int i, first_duration;
889 // return track->par->frame_size;
891 /* use 1 for raw PCM */
892 if (!track->audio_vbr)
895 /* check to see if duration is constant for all clusters */
898 first_duration = get_cluster_duration(track, 0);
899 for (i = 1; i < track->entry; i++) {
900 if (get_cluster_duration(track, i) != first_duration)
903 return first_duration;
906 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
908 int64_t pos = avio_tell(pb);
910 uint32_t tag = track->tag;
912 if (track->mode == MODE_MOV) {
913 if (track->timescale > UINT16_MAX) {
914 if (mov_get_lpcm_flags(track->par->codec_id))
915 tag = AV_RL32("lpcm");
917 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
918 mov_pcm_be_gt16(track->par->codec_id) ||
919 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
920 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
921 track->par->codec_id == AV_CODEC_ID_QDM2) {
926 avio_wb32(pb, 0); /* size */
927 if (mov->encryption_scheme != MOV_ENC_NONE) {
928 ffio_wfourcc(pb, "enca");
930 avio_wl32(pb, tag); // store it byteswapped
932 avio_wb32(pb, 0); /* Reserved */
933 avio_wb16(pb, 0); /* Reserved */
934 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
936 /* SoundDescription */
937 avio_wb16(pb, version); /* Version */
938 avio_wb16(pb, 0); /* Revision level */
939 avio_wb32(pb, 0); /* Reserved */
944 avio_wb16(pb, 0xfffe);
946 avio_wb32(pb, 0x00010000);
948 avio_wb64(pb, av_double2int(track->par->sample_rate));
949 avio_wb32(pb, track->par->channels);
950 avio_wb32(pb, 0x7F000000);
951 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
952 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
953 avio_wb32(pb, track->sample_size);
954 avio_wb32(pb, get_samples_per_packet(track));
956 if (track->mode == MODE_MOV) {
957 avio_wb16(pb, track->par->channels);
958 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
959 track->par->codec_id == AV_CODEC_ID_PCM_S8)
960 avio_wb16(pb, 8); /* bits per sample */
961 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
962 avio_wb16(pb, track->par->bits_per_coded_sample);
965 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
966 } else { /* reserved for mp4/3gp */
972 avio_wb16(pb, 0); /* packet size (= 0) */
973 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
974 track->par->sample_rate : 0);
975 avio_wb16(pb, 0); /* Reserved */
978 if (version == 1) { /* SoundDescription V1 extended info */
979 if (mov_pcm_le_gt16(track->par->codec_id) ||
980 mov_pcm_be_gt16(track->par->codec_id))
981 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
983 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
984 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
985 avio_wb32(pb, track->sample_size); /* Bytes per frame */
986 avio_wb32(pb, 2); /* Bytes per sample */
989 if (track->mode == MODE_MOV &&
990 (track->par->codec_id == AV_CODEC_ID_AAC ||
991 track->par->codec_id == AV_CODEC_ID_AC3 ||
992 track->par->codec_id == AV_CODEC_ID_EAC3 ||
993 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
994 track->par->codec_id == AV_CODEC_ID_ALAC ||
995 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
996 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
997 track->par->codec_id == AV_CODEC_ID_QDM2 ||
998 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
999 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1000 mov_write_wave_tag(s, pb, track);
1001 else if (track->tag == MKTAG('m','p','4','a'))
1002 mov_write_esds_tag(pb, track);
1003 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1004 mov_write_amr_tag(pb, track);
1005 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1006 mov_write_ac3_tag(pb, track);
1007 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1008 mov_write_eac3_tag(pb, track);
1009 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1010 mov_write_extradata_tag(pb, track);
1011 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1012 mov_write_wfex_tag(s, pb, track);
1013 else if (track->vos_len > 0)
1014 mov_write_glbl_tag(pb, track);
1016 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1017 mov_write_chan_tag(s, pb, track);
1019 if (mov->encryption_scheme != MOV_ENC_NONE) {
1020 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1023 return update_size(pb, pos);
1026 static int mov_write_d263_tag(AVIOContext *pb)
1028 avio_wb32(pb, 0xf); /* size */
1029 ffio_wfourcc(pb, "d263");
1030 ffio_wfourcc(pb, "FFMP");
1031 avio_w8(pb, 0); /* decoder version */
1032 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1033 avio_w8(pb, 0xa); /* level */
1034 avio_w8(pb, 0); /* profile */
1038 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1040 int64_t pos = avio_tell(pb);
1043 ffio_wfourcc(pb, "avcC");
1044 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1045 return update_size(pb, pos);
1048 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1050 int64_t pos = avio_tell(pb);
1053 ffio_wfourcc(pb, "vpcC");
1054 avio_wb32(pb, 0); /* version & flags */
1055 ff_isom_write_vpcc(s, pb, track->par);
1056 return update_size(pb, pos);
1059 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1061 int64_t pos = avio_tell(pb);
1064 ffio_wfourcc(pb, "hvcC");
1065 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1066 return update_size(pb, pos);
1069 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1070 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1075 int display_width = track->par->width;
1077 if (track->vos_data && track->vos_len > 0x29) {
1078 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1079 /* looks like a DNxHD bit stream */
1080 interlaced = (track->vos_data[5] & 2);
1081 cid = AV_RB32(track->vos_data + 0x28);
1083 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1087 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1091 avio_wb32(pb, 24); /* size */
1092 ffio_wfourcc(pb, "ACLR");
1093 ffio_wfourcc(pb, "ACLR");
1094 ffio_wfourcc(pb, "0001");
1095 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1096 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1097 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1098 } else { /* Full range (0-255) */
1099 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1101 avio_wb32(pb, 0); /* unknown */
1103 if (track->tag == MKTAG('A','V','d','h')) {
1105 ffio_wfourcc(pb, "ADHR");
1106 ffio_wfourcc(pb, "0001");
1108 avio_wb32(pb, 0); /* unknown */
1109 avio_wb32(pb, 1); /* unknown */
1110 avio_wb32(pb, 0); /* unknown */
1111 avio_wb32(pb, 0); /* unknown */
1115 avio_wb32(pb, 24); /* size */
1116 ffio_wfourcc(pb, "APRG");
1117 ffio_wfourcc(pb, "APRG");
1118 ffio_wfourcc(pb, "0001");
1119 avio_wb32(pb, 1); /* unknown */
1120 avio_wb32(pb, 0); /* unknown */
1122 avio_wb32(pb, 120); /* size */
1123 ffio_wfourcc(pb, "ARES");
1124 ffio_wfourcc(pb, "ARES");
1125 ffio_wfourcc(pb, "0001");
1126 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1127 if ( track->par->sample_aspect_ratio.num > 0
1128 && track->par->sample_aspect_ratio.den > 0)
1129 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1130 avio_wb32(pb, display_width);
1131 /* values below are based on samples created with quicktime and avid codecs */
1133 avio_wb32(pb, track->par->height / 2);
1134 avio_wb32(pb, 2); /* unknown */
1135 avio_wb32(pb, 0); /* unknown */
1136 avio_wb32(pb, 4); /* unknown */
1138 avio_wb32(pb, track->par->height);
1139 avio_wb32(pb, 1); /* unknown */
1140 avio_wb32(pb, 0); /* unknown */
1141 if (track->par->height == 1080)
1142 avio_wb32(pb, 5); /* unknown */
1144 avio_wb32(pb, 6); /* unknown */
1147 for (i = 0; i < 10; i++)
1153 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1156 ffio_wfourcc(pb, "DpxE");
1157 if (track->par->extradata_size >= 12 &&
1158 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1159 avio_wb32(pb, track->par->extradata[11]);
1166 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1168 int tag = track->par->codec_tag;
1170 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
1173 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1174 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1175 else if (track->par->codec_id == AV_CODEC_ID_VP9) tag = MKTAG('v','p','0','9');
1176 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1177 else if (track->par->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1178 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1179 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1180 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1181 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1182 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1183 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1188 static const AVCodecTag codec_ipod_tags[] = {
1189 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1190 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1191 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1192 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1193 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1194 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1195 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1196 { AV_CODEC_ID_NONE, 0 },
1199 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1201 int tag = track->par->codec_tag;
1203 // keep original tag for subs, ipod supports both formats
1204 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1205 (tag == MKTAG('t', 'x', '3', 'g') ||
1206 tag == MKTAG('t', 'e', 'x', 't'))))
1207 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
1209 if (!av_match_ext(s->filename, "m4a") &&
1210 !av_match_ext(s->filename, "m4b") &&
1211 !av_match_ext(s->filename, "m4v"))
1212 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1213 "Quicktime/Ipod might not play the file\n");
1218 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1222 if (track->par->width == 720) { /* SD */
1223 if (track->par->height == 480) { /* NTSC */
1224 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1225 else tag = MKTAG('d','v','c',' ');
1226 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1227 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1228 else tag = MKTAG('d','v','p','p');
1229 } else if (track->par->height == 720) { /* HD 720 line */
1230 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1231 else tag = MKTAG('d','v','h','p');
1232 } else if (track->par->height == 1080) { /* HD 1080 line */
1233 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1234 else tag = MKTAG('d','v','h','6');
1236 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1243 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1245 AVRational rate = st->avg_frame_rate;
1247 #if FF_API_LAVF_AVCTX
1248 FF_DISABLE_DEPRECATION_WARNINGS
1249 rate = av_inv_q(st->codec->time_base);
1250 if (av_timecode_check_frame_rate(rate) < 0) {
1251 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1252 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1253 rate = st->avg_frame_rate;
1255 FF_ENABLE_DEPRECATION_WARNINGS
1261 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1263 int tag = track->par->codec_tag;
1264 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1265 AVStream *st = track->st;
1266 int rate = av_q2d(find_fps(s, st));
1269 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1271 if (track->par->format == AV_PIX_FMT_YUV420P) {
1272 if (track->par->width == 1280 && track->par->height == 720) {
1274 if (rate == 24) tag = MKTAG('x','d','v','4');
1275 else if (rate == 25) tag = MKTAG('x','d','v','5');
1276 else if (rate == 30) tag = MKTAG('x','d','v','1');
1277 else if (rate == 50) tag = MKTAG('x','d','v','a');
1278 else if (rate == 60) tag = MKTAG('x','d','v','9');
1280 } else if (track->par->width == 1440 && track->par->height == 1080) {
1282 if (rate == 24) tag = MKTAG('x','d','v','6');
1283 else if (rate == 25) tag = MKTAG('x','d','v','7');
1284 else if (rate == 30) tag = MKTAG('x','d','v','8');
1286 if (rate == 25) tag = MKTAG('x','d','v','3');
1287 else if (rate == 30) tag = MKTAG('x','d','v','2');
1289 } else if (track->par->width == 1920 && track->par->height == 1080) {
1291 if (rate == 24) tag = MKTAG('x','d','v','d');
1292 else if (rate == 25) tag = MKTAG('x','d','v','e');
1293 else if (rate == 30) tag = MKTAG('x','d','v','f');
1295 if (rate == 25) tag = MKTAG('x','d','v','c');
1296 else if (rate == 30) tag = MKTAG('x','d','v','b');
1299 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1300 if (track->par->width == 1280 && track->par->height == 720) {
1302 if (rate == 24) tag = MKTAG('x','d','5','4');
1303 else if (rate == 25) tag = MKTAG('x','d','5','5');
1304 else if (rate == 30) tag = MKTAG('x','d','5','1');
1305 else if (rate == 50) tag = MKTAG('x','d','5','a');
1306 else if (rate == 60) tag = MKTAG('x','d','5','9');
1308 } else if (track->par->width == 1920 && track->par->height == 1080) {
1310 if (rate == 24) tag = MKTAG('x','d','5','d');
1311 else if (rate == 25) tag = MKTAG('x','d','5','e');
1312 else if (rate == 30) tag = MKTAG('x','d','5','f');
1314 if (rate == 25) tag = MKTAG('x','d','5','c');
1315 else if (rate == 30) tag = MKTAG('x','d','5','b');
1323 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1325 int tag = track->par->codec_tag;
1326 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1327 AVStream *st = track->st;
1328 int rate = av_q2d(find_fps(s, st));
1331 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1333 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1334 if (track->par->width == 960 && track->par->height == 720) {
1336 if (rate == 24) tag = MKTAG('a','i','5','p');
1337 else if (rate == 25) tag = MKTAG('a','i','5','q');
1338 else if (rate == 30) tag = MKTAG('a','i','5','p');
1339 else if (rate == 50) tag = MKTAG('a','i','5','q');
1340 else if (rate == 60) tag = MKTAG('a','i','5','p');
1342 } else if (track->par->width == 1440 && track->par->height == 1080) {
1344 if (rate == 24) tag = MKTAG('a','i','5','3');
1345 else if (rate == 25) tag = MKTAG('a','i','5','2');
1346 else if (rate == 30) tag = MKTAG('a','i','5','3');
1348 if (rate == 50) tag = MKTAG('a','i','5','5');
1349 else if (rate == 60) tag = MKTAG('a','i','5','6');
1352 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1353 if (track->par->width == 1280 && track->par->height == 720) {
1355 if (rate == 24) tag = MKTAG('a','i','1','p');
1356 else if (rate == 25) tag = MKTAG('a','i','1','q');
1357 else if (rate == 30) tag = MKTAG('a','i','1','p');
1358 else if (rate == 50) tag = MKTAG('a','i','1','q');
1359 else if (rate == 60) tag = MKTAG('a','i','1','p');
1361 } else if (track->par->width == 1920 && track->par->height == 1080) {
1363 if (rate == 24) tag = MKTAG('a','i','1','3');
1364 else if (rate == 25) tag = MKTAG('a','i','1','2');
1365 else if (rate == 30) tag = MKTAG('a','i','1','3');
1367 if (rate == 25) tag = MKTAG('a','i','1','5');
1368 else if (rate == 50) tag = MKTAG('a','i','1','5');
1369 else if (rate == 60) tag = MKTAG('a','i','1','6');
1371 } else if ( track->par->width == 4096 && track->par->height == 2160
1372 || track->par->width == 3840 && track->par->height == 2160
1373 || track->par->width == 2048 && track->par->height == 1080) {
1374 tag = MKTAG('a','i','v','x');
1381 static const struct {
1382 enum AVPixelFormat pix_fmt;
1385 } mov_pix_fmt_tags[] = {
1386 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1387 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1388 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1389 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1390 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1391 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1392 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1393 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1394 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1395 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1396 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1397 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1398 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1399 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1400 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1403 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1405 int tag = MKTAG('A','V','d','n');
1406 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1407 track->par->profile != FF_PROFILE_DNXHD)
1408 tag = MKTAG('A','V','d','h');
1412 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1414 int tag = track->par->codec_tag;
1416 enum AVPixelFormat pix_fmt;
1418 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1419 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1420 tag = mov_pix_fmt_tags[i].tag;
1421 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1422 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1427 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1428 track->par->bits_per_coded_sample);
1429 if (tag == MKTAG('r','a','w',' ') &&
1430 track->par->format != pix_fmt &&
1431 track->par->format != AV_PIX_FMT_GRAY8 &&
1432 track->par->format != AV_PIX_FMT_NONE)
1433 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1434 av_get_pix_fmt_name(track->par->format));
1438 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1440 int tag = track->par->codec_tag;
1442 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1443 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1444 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1445 track->par->codec_id == AV_CODEC_ID_H263 ||
1446 track->par->codec_id == AV_CODEC_ID_H264 ||
1447 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1448 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1449 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1450 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1451 tag = mov_get_dv_codec_tag(s, track);
1452 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1453 tag = mov_get_rawvideo_codec_tag(s, track);
1454 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1455 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1456 else if (track->par->codec_id == AV_CODEC_ID_H264)
1457 tag = mov_get_h264_codec_tag(s, track);
1458 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1459 tag = mov_get_dnxhd_codec_tag(s, track);
1460 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1461 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1462 if (!tag) { // if no mac fcc found, try with Microsoft tags
1463 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1465 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1466 "the file may be unplayable!\n");
1468 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1469 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1470 if (!tag) { // if no mac fcc found, try with Microsoft tags
1471 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1473 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1474 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1475 "the file may be unplayable!\n");
1478 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1479 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1485 static const AVCodecTag codec_3gp_tags[] = {
1486 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1487 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1488 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1489 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1490 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1491 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1492 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1493 { AV_CODEC_ID_NONE, 0 },
1496 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1497 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1498 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1499 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1500 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1501 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1502 { AV_CODEC_ID_NONE, 0 },
1505 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1509 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1510 tag = mp4_get_codec_tag(s, track);
1511 else if (track->mode == MODE_ISM) {
1512 tag = mp4_get_codec_tag(s, track);
1513 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
1514 tag = MKTAG('w', 'm', 'a', ' ');
1515 } else if (track->mode == MODE_IPOD)
1516 tag = ipod_get_codec_tag(s, track);
1517 else if (track->mode & MODE_3GP)
1518 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
1519 else if (track->mode == MODE_F4V)
1520 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
1522 tag = mov_get_codec_tag(s, track);
1527 /** Write uuid atom.
1528 * Needed to make file play in iPods running newest firmware
1529 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1531 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1534 ffio_wfourcc(pb, "uuid");
1535 avio_wb32(pb, 0x6b6840f2);
1536 avio_wb32(pb, 0x5f244fc5);
1537 avio_wb32(pb, 0xba39a51b);
1538 avio_wb32(pb, 0xcf0323f3);
1543 static const uint16_t fiel_data[] = {
1544 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1547 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1549 unsigned mov_field_order = 0;
1550 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1551 mov_field_order = fiel_data[field_order];
1555 ffio_wfourcc(pb, "fiel");
1556 avio_wb16(pb, mov_field_order);
1560 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1562 int64_t pos = avio_tell(pb);
1563 avio_wb32(pb, 0); /* size */
1564 avio_wl32(pb, track->tag); // store it byteswapped
1565 avio_wb32(pb, 0); /* Reserved */
1566 avio_wb16(pb, 0); /* Reserved */
1567 avio_wb16(pb, 1); /* Data-reference index */
1569 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1570 mov_write_esds_tag(pb, track);
1571 else if (track->par->extradata_size)
1572 avio_write(pb, track->par->extradata, track->par->extradata_size);
1574 return update_size(pb, pos);
1577 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1580 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1581 track->par->sample_aspect_ratio.den, INT_MAX);
1584 ffio_wfourcc(pb, "pasp");
1585 avio_wb32(pb, sar.num);
1586 avio_wb32(pb, sar.den);
1590 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1595 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1597 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1600 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1601 av_log(pb, AV_LOG_DEBUG, "writing gama value %d\n", gama);
1603 av_assert0(track->mode == MODE_MOV);
1605 ffio_wfourcc(pb, "gama");
1606 avio_wb32(pb, gama);
1610 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1615 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1617 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1618 // Ref (MP4): ISO/IEC 14496-12:2012
1620 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1621 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1622 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1623 if ((track->par->width >= 1920 && track->par->height >= 1080)
1624 || (track->par->width == 1280 && track->par->height == 720)) {
1625 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1626 track->par->color_primaries = AVCOL_PRI_BT709;
1627 } else if (track->par->width == 720 && track->height == 576) {
1628 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1629 track->par->color_primaries = AVCOL_PRI_BT470BG;
1630 } else if (track->par->width == 720 &&
1631 (track->height == 486 || track->height == 480)) {
1632 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1633 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1635 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1637 switch (track->par->color_primaries) {
1638 case AVCOL_PRI_BT709:
1639 track->par->color_trc = AVCOL_TRC_BT709;
1640 track->par->color_space = AVCOL_SPC_BT709;
1642 case AVCOL_PRI_SMPTE170M:
1643 case AVCOL_PRI_BT470BG:
1644 track->par->color_trc = AVCOL_TRC_BT709;
1645 track->par->color_space = AVCOL_SPC_SMPTE170M;
1650 /* We should only ever be called by MOV or MP4. */
1651 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1653 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1654 ffio_wfourcc(pb, "colr");
1655 if (track->mode == MODE_MP4)
1656 ffio_wfourcc(pb, "nclx");
1658 ffio_wfourcc(pb, "nclc");
1659 switch (track->par->color_primaries) {
1660 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1661 case AVCOL_PRI_SMPTE170M:
1662 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1663 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1664 default: avio_wb16(pb, 2);
1666 switch (track->par->color_trc) {
1667 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1668 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1669 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1670 default: avio_wb16(pb, 2);
1672 switch (track->par->color_space) {
1673 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1674 case AVCOL_SPC_BT470BG:
1675 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1676 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1677 default: avio_wb16(pb, 2);
1680 if (track->mode == MODE_MP4) {
1681 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1682 avio_w8(pb, full_range << 7);
1689 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1691 AVDictionaryEntry *encoder;
1692 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1693 || (track->par->width == 1440 && track->par->height == 1080)
1694 || (track->par->width == 1920 && track->par->height == 1080);
1696 if (track->mode == MODE_MOV &&
1697 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1698 av_strlcpy(compressor_name, encoder->value, 32);
1699 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1700 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1701 AVStream *st = track->st;
1702 int rate = av_q2d(find_fps(NULL, st));
1703 av_strlcatf(compressor_name, len, "XDCAM");
1704 if (track->par->format == AV_PIX_FMT_YUV422P) {
1705 av_strlcatf(compressor_name, len, " HD422");
1706 } else if(track->par->width == 1440) {
1707 av_strlcatf(compressor_name, len, " HD");
1709 av_strlcatf(compressor_name, len, " EX");
1711 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1713 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1717 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1719 int64_t pos = avio_tell(pb);
1720 char compressor_name[32] = { 0 };
1723 avio_wb32(pb, 0); /* size */
1724 if (mov->encryption_scheme != MOV_ENC_NONE) {
1725 ffio_wfourcc(pb, "encv");
1727 avio_wl32(pb, track->tag); // store it byteswapped
1729 avio_wb32(pb, 0); /* Reserved */
1730 avio_wb16(pb, 0); /* Reserved */
1731 avio_wb16(pb, 1); /* Data-reference index */
1733 avio_wb16(pb, 0); /* Codec stream version */
1734 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1735 if (track->mode == MODE_MOV) {
1736 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1737 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1738 avio_wb32(pb, 0); /* Temporal Quality */
1739 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1741 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1742 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1745 avio_wb32(pb, 0); /* Reserved */
1746 avio_wb32(pb, 0); /* Reserved */
1747 avio_wb32(pb, 0); /* Reserved */
1749 avio_wb16(pb, track->par->width); /* Video width */
1750 avio_wb16(pb, track->height); /* Video height */
1751 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1752 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1753 avio_wb32(pb, 0); /* Data size (= 0) */
1754 avio_wb16(pb, 1); /* Frame count (= 1) */
1756 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1757 find_compressor(compressor_name, 32, track);
1758 avio_w8(pb, strlen(compressor_name));
1759 avio_write(pb, compressor_name, 31);
1761 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1762 avio_wb16(pb, track->par->bits_per_coded_sample |
1763 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1765 avio_wb16(pb, 0x18); /* Reserved */
1767 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1768 int pal_size = 1 << track->par->bits_per_coded_sample;
1770 avio_wb16(pb, 0); /* Color table ID */
1771 avio_wb32(pb, 0); /* Color table seed */
1772 avio_wb16(pb, 0x8000); /* Color table flags */
1773 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1774 for (i = 0; i < pal_size; i++) {
1775 uint32_t rgb = track->palette[i];
1776 uint16_t r = (rgb >> 16) & 0xff;
1777 uint16_t g = (rgb >> 8) & 0xff;
1778 uint16_t b = rgb & 0xff;
1780 avio_wb16(pb, (r << 8) | r);
1781 avio_wb16(pb, (g << 8) | g);
1782 avio_wb16(pb, (b << 8) | b);
1785 avio_wb16(pb, 0xffff); /* Reserved */
1787 if (track->tag == MKTAG('m','p','4','v'))
1788 mov_write_esds_tag(pb, track);
1789 else if (track->par->codec_id == AV_CODEC_ID_H263)
1790 mov_write_d263_tag(pb);
1791 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1792 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1793 mov_write_extradata_tag(pb, track);
1795 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1796 mov_write_avid_tag(pb, track);
1798 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1799 mov_write_hvcc_tag(pb, track);
1800 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1801 mov_write_avcc_tag(pb, track);
1802 if (track->mode == MODE_IPOD)
1803 mov_write_uuid_tag_ipod(pb);
1804 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1805 mov_write_vpcc_tag(mov->fc, pb, track);
1806 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1807 mov_write_dvc1_tag(pb, track);
1808 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1809 track->par->codec_id == AV_CODEC_ID_VP6A) {
1810 /* Don't write any potential extradata here - the cropping
1811 * is signalled via the normal width/height fields. */
1812 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1813 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1814 mov_write_dpxe_tag(pb, track);
1815 } else if (track->vos_len > 0)
1816 mov_write_glbl_tag(pb, track);
1818 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1819 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1820 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1821 int field_order = track->par->field_order;
1823 #if FF_API_LAVF_AVCTX
1824 FF_DISABLE_DEPRECATION_WARNINGS
1825 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1826 field_order = track->st->codec->field_order;
1827 FF_ENABLE_DEPRECATION_WARNINGS
1830 if (field_order != AV_FIELD_UNKNOWN)
1831 mov_write_fiel_tag(pb, track, field_order);
1834 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1835 if (track->mode == MODE_MOV)
1836 mov_write_gama_tag(pb, track, mov->gamma);
1838 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1840 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1841 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1842 mov_write_colr_tag(pb, track);
1844 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1847 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
1848 mov_write_pasp_tag(pb, track);
1851 if (mov->encryption_scheme != MOV_ENC_NONE) {
1852 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1855 /* extra padding for avid stsd */
1856 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1860 return update_size(pb, pos);
1863 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1865 int64_t pos = avio_tell(pb);
1866 avio_wb32(pb, 0); /* size */
1867 ffio_wfourcc(pb, "rtp ");
1868 avio_wb32(pb, 0); /* Reserved */
1869 avio_wb16(pb, 0); /* Reserved */
1870 avio_wb16(pb, 1); /* Data-reference index */
1872 avio_wb16(pb, 1); /* Hint track version */
1873 avio_wb16(pb, 1); /* Highest compatible version */
1874 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1876 avio_wb32(pb, 12); /* size */
1877 ffio_wfourcc(pb, "tims");
1878 avio_wb32(pb, track->timescale);
1880 return update_size(pb, pos);
1883 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1885 uint64_t str_size =strlen(reel_name);
1886 int64_t pos = avio_tell(pb);
1888 if (str_size >= UINT16_MAX){
1889 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1891 return AVERROR(EINVAL);
1894 avio_wb32(pb, 0); /* size */
1895 ffio_wfourcc(pb, "name"); /* Data format */
1896 avio_wb16(pb, str_size); /* string size */
1897 avio_wb16(pb, track->language); /* langcode */
1898 avio_write(pb, reel_name, str_size); /* reel name */
1899 return update_size(pb,pos);
1902 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1904 int64_t pos = avio_tell(pb);
1908 AVDictionaryEntry *t = NULL;
1910 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
1911 #if FF_API_LAVF_AVCTX
1912 FF_DISABLE_DEPRECATION_WARNINGS
1913 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
1914 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
1915 FF_ENABLE_DEPRECATION_WARNINGS
1917 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
1918 return AVERROR(EINVAL);
1921 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
1922 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
1925 if (nb_frames > 255) {
1926 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1927 return AVERROR(EINVAL);
1930 avio_wb32(pb, 0); /* size */
1931 ffio_wfourcc(pb, "tmcd"); /* Data format */
1932 avio_wb32(pb, 0); /* Reserved */
1933 avio_wb32(pb, 1); /* Data reference index */
1934 avio_wb32(pb, 0); /* Flags */
1935 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1936 avio_wb32(pb, track->timescale); /* Timescale */
1937 avio_wb32(pb, frame_duration); /* Frame duration */
1938 avio_w8(pb, nb_frames); /* Number of frames */
1939 avio_w8(pb, 0); /* Reserved */
1941 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1942 if (t && utf8len(t->value) && track->mode != MODE_MP4)
1943 mov_write_source_reference_tag(pb, track, t->value);
1945 avio_wb16(pb, 0); /* zero size */
1948 avio_wb32(pb, 0); /* size */
1949 ffio_wfourcc(pb, "tmcd"); /* Data format */
1950 avio_wb32(pb, 0); /* Reserved */
1951 avio_wb32(pb, 1); /* Data reference index */
1952 if (track->par->extradata_size)
1953 avio_write(pb, track->par->extradata, track->par->extradata_size);
1955 return update_size(pb, pos);
1958 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1960 int64_t pos = avio_tell(pb);
1961 avio_wb32(pb, 0); /* size */
1962 ffio_wfourcc(pb, "stsd");
1963 avio_wb32(pb, 0); /* version & flags */
1964 avio_wb32(pb, 1); /* entry count */
1965 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
1966 mov_write_video_tag(pb, mov, track);
1967 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1968 mov_write_audio_tag(s, pb, mov, track);
1969 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1970 mov_write_subtitle_tag(pb, track);
1971 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
1972 mov_write_rtp_tag(pb, track);
1973 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
1974 mov_write_tmcd_tag(pb, track);
1975 return update_size(pb, pos);
1978 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1980 MOVStts *ctts_entries;
1981 uint32_t entries = 0;
1985 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1987 return AVERROR(ENOMEM);
1988 ctts_entries[0].count = 1;
1989 ctts_entries[0].duration = track->cluster[0].cts;
1990 for (i = 1; i < track->entry; i++) {
1991 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1992 ctts_entries[entries].count++; /* compress */
1995 ctts_entries[entries].duration = track->cluster[i].cts;
1996 ctts_entries[entries].count = 1;
1999 entries++; /* last one */
2000 atom_size = 16 + (entries * 8);
2001 avio_wb32(pb, atom_size); /* size */
2002 ffio_wfourcc(pb, "ctts");
2003 avio_wb32(pb, 0); /* version & flags */
2004 avio_wb32(pb, entries); /* entry count */
2005 for (i = 0; i < entries; i++) {
2006 avio_wb32(pb, ctts_entries[i].count);
2007 avio_wb32(pb, ctts_entries[i].duration);
2009 av_free(ctts_entries);
2013 /* Time to sample atom */
2014 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2016 MOVStts *stts_entries = NULL;
2017 uint32_t entries = -1;
2021 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2022 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2024 return AVERROR(ENOMEM);
2025 stts_entries[0].count = track->sample_count;
2026 stts_entries[0].duration = 1;
2030 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2032 return AVERROR(ENOMEM);
2034 for (i = 0; i < track->entry; i++) {
2035 int duration = get_cluster_duration(track, i);
2036 if (i && duration == stts_entries[entries].duration) {
2037 stts_entries[entries].count++; /* compress */
2040 stts_entries[entries].duration = duration;
2041 stts_entries[entries].count = 1;
2044 entries++; /* last one */
2046 atom_size = 16 + (entries * 8);
2047 avio_wb32(pb, atom_size); /* size */
2048 ffio_wfourcc(pb, "stts");
2049 avio_wb32(pb, 0); /* version & flags */
2050 avio_wb32(pb, entries); /* entry count */
2051 for (i = 0; i < entries; i++) {
2052 avio_wb32(pb, stts_entries[i].count);
2053 avio_wb32(pb, stts_entries[i].duration);
2055 av_free(stts_entries);
2059 static int mov_write_dref_tag(AVIOContext *pb)
2061 avio_wb32(pb, 28); /* size */
2062 ffio_wfourcc(pb, "dref");
2063 avio_wb32(pb, 0); /* version & flags */
2064 avio_wb32(pb, 1); /* entry count */
2066 avio_wb32(pb, 0xc); /* size */
2067 //FIXME add the alis and rsrc atom
2068 ffio_wfourcc(pb, "url ");
2069 avio_wb32(pb, 1); /* version & flags */
2074 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2076 int64_t pos = avio_tell(pb);
2079 avio_wb32(pb, 0); /* size */
2080 ffio_wfourcc(pb, "stbl");
2081 mov_write_stsd_tag(s, pb, mov, track);
2082 mov_write_stts_tag(pb, track);
2083 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2084 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2085 track->has_keyframes && track->has_keyframes < track->entry)
2086 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2087 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2088 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2089 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2090 track->flags & MOV_TRACK_CTTS && track->entry) {
2092 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2095 mov_write_stsc_tag(pb, track);
2096 mov_write_stsz_tag(pb, track);
2097 mov_write_stco_tag(pb, track);
2098 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
2099 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2101 return update_size(pb, pos);
2104 static int mov_write_dinf_tag(AVIOContext *pb)
2106 int64_t pos = avio_tell(pb);
2107 avio_wb32(pb, 0); /* size */
2108 ffio_wfourcc(pb, "dinf");
2109 mov_write_dref_tag(pb);
2110 return update_size(pb, pos);
2113 static int mov_write_nmhd_tag(AVIOContext *pb)
2116 ffio_wfourcc(pb, "nmhd");
2121 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2123 int64_t pos = avio_tell(pb);
2124 const char *font = "Lucida Grande";
2125 avio_wb32(pb, 0); /* size */
2126 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2127 avio_wb32(pb, 0); /* version & flags */
2128 avio_wb16(pb, 0); /* text font */
2129 avio_wb16(pb, 0); /* text face */
2130 avio_wb16(pb, 12); /* text size */
2131 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2132 avio_wb16(pb, 0x0000); /* text color (red) */
2133 avio_wb16(pb, 0x0000); /* text color (green) */
2134 avio_wb16(pb, 0x0000); /* text color (blue) */
2135 avio_wb16(pb, 0xffff); /* background color (red) */
2136 avio_wb16(pb, 0xffff); /* background color (green) */
2137 avio_wb16(pb, 0xffff); /* background color (blue) */
2138 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2139 avio_write(pb, font, strlen(font)); /* font name */
2140 return update_size(pb, pos);
2143 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2145 int64_t pos = avio_tell(pb);
2146 avio_wb32(pb, 0); /* size */
2147 ffio_wfourcc(pb, "gmhd");
2148 avio_wb32(pb, 0x18); /* gmin size */
2149 ffio_wfourcc(pb, "gmin");/* generic media info */
2150 avio_wb32(pb, 0); /* version & flags */
2151 avio_wb16(pb, 0x40); /* graphics mode = */
2152 avio_wb16(pb, 0x8000); /* opColor (r?) */
2153 avio_wb16(pb, 0x8000); /* opColor (g?) */
2154 avio_wb16(pb, 0x8000); /* opColor (b?) */
2155 avio_wb16(pb, 0); /* balance */
2156 avio_wb16(pb, 0); /* reserved */
2159 * This special text atom is required for
2160 * Apple Quicktime chapters. The contents
2161 * don't appear to be documented, so the
2162 * bytes are copied verbatim.
2164 if (track->tag != MKTAG('c','6','0','8')) {
2165 avio_wb32(pb, 0x2C); /* size */
2166 ffio_wfourcc(pb, "text");
2167 avio_wb16(pb, 0x01);
2168 avio_wb32(pb, 0x00);
2169 avio_wb32(pb, 0x00);
2170 avio_wb32(pb, 0x00);
2171 avio_wb32(pb, 0x01);
2172 avio_wb32(pb, 0x00);
2173 avio_wb32(pb, 0x00);
2174 avio_wb32(pb, 0x00);
2175 avio_wb32(pb, 0x00004000);
2176 avio_wb16(pb, 0x0000);
2179 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2180 int64_t tmcd_pos = avio_tell(pb);
2181 avio_wb32(pb, 0); /* size */
2182 ffio_wfourcc(pb, "tmcd");
2183 mov_write_tcmi_tag(pb, track);
2184 update_size(pb, tmcd_pos);
2186 return update_size(pb, pos);
2189 static int mov_write_smhd_tag(AVIOContext *pb)
2191 avio_wb32(pb, 16); /* size */
2192 ffio_wfourcc(pb, "smhd");
2193 avio_wb32(pb, 0); /* version & flags */
2194 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2195 avio_wb16(pb, 0); /* reserved */
2199 static int mov_write_vmhd_tag(AVIOContext *pb)
2201 avio_wb32(pb, 0x14); /* size (always 0x14) */
2202 ffio_wfourcc(pb, "vmhd");
2203 avio_wb32(pb, 0x01); /* version & flags */
2204 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2208 static int is_clcp_track(MOVTrack *track)
2210 return track->tag == MKTAG('c','7','0','8') ||
2211 track->tag == MKTAG('c','6','0','8');
2214 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2216 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2217 int64_t pos = avio_tell(pb);
2221 descr = "DataHandler";
2224 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2225 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2227 descr = "VideoHandler";
2228 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2230 descr = "SoundHandler";
2231 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2232 if (is_clcp_track(track)) {
2234 descr = "ClosedCaptionHandler";
2236 if (track->tag == MKTAG('t','x','3','g')) {
2238 } else if (track->tag == MKTAG('m','p','4','s')) {
2243 descr = "SubtitleHandler";
2245 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2247 descr = "HintHandler";
2248 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2250 descr = "TimeCodeHandler";
2253 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
2254 track->par->codec_tag);
2256 av_log(s, AV_LOG_WARNING,
2257 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
2258 tag_buf, track->par->codec_tag);
2261 // hdlr.name is used by some players to identify the content title
2262 // of the track. So if an alternate handler description is
2263 // specified, use it.
2264 AVDictionaryEntry *t;
2265 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2266 if (t && utf8len(t->value))
2271 avio_wb32(pb, 0); /* size */
2272 ffio_wfourcc(pb, "hdlr");
2273 avio_wb32(pb, 0); /* Version & flags */
2274 avio_write(pb, hdlr, 4); /* handler */
2275 ffio_wfourcc(pb, hdlr_type); /* handler type */
2276 avio_wb32(pb, 0); /* reserved */
2277 avio_wb32(pb, 0); /* reserved */
2278 avio_wb32(pb, 0); /* reserved */
2279 if (!track || track->mode == MODE_MOV)
2280 avio_w8(pb, strlen(descr)); /* pascal string */
2281 avio_write(pb, descr, strlen(descr)); /* handler description */
2282 if (track && track->mode != MODE_MOV)
2283 avio_w8(pb, 0); /* c string */
2284 return update_size(pb, pos);
2287 static int mov_write_hmhd_tag(AVIOContext *pb)
2289 /* This atom must be present, but leaving the values at zero
2290 * seems harmless. */
2291 avio_wb32(pb, 28); /* size */
2292 ffio_wfourcc(pb, "hmhd");
2293 avio_wb32(pb, 0); /* version, flags */
2294 avio_wb16(pb, 0); /* maxPDUsize */
2295 avio_wb16(pb, 0); /* avgPDUsize */
2296 avio_wb32(pb, 0); /* maxbitrate */
2297 avio_wb32(pb, 0); /* avgbitrate */
2298 avio_wb32(pb, 0); /* reserved */
2302 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2304 int64_t pos = avio_tell(pb);
2307 avio_wb32(pb, 0); /* size */
2308 ffio_wfourcc(pb, "minf");
2309 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2310 mov_write_vmhd_tag(pb);
2311 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2312 mov_write_smhd_tag(pb);
2313 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2314 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2315 mov_write_gmhd_tag(pb, track);
2317 mov_write_nmhd_tag(pb);
2319 } else if (track->tag == MKTAG('r','t','p',' ')) {
2320 mov_write_hmhd_tag(pb);
2321 } else if (track->tag == MKTAG('t','m','c','d')) {
2322 if (track->mode != MODE_MOV)
2323 mov_write_nmhd_tag(pb);
2325 mov_write_gmhd_tag(pb, track);
2327 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2328 mov_write_hdlr_tag(s, pb, NULL);
2329 mov_write_dinf_tag(pb);
2330 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2332 return update_size(pb, pos);
2335 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2338 int version = track->track_duration < INT32_MAX ? 0 : 1;
2340 if (track->mode == MODE_ISM)
2343 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2344 ffio_wfourcc(pb, "mdhd");
2345 avio_w8(pb, version);
2346 avio_wb24(pb, 0); /* flags */
2348 avio_wb64(pb, track->time);
2349 avio_wb64(pb, track->time);
2351 avio_wb32(pb, track->time); /* creation time */
2352 avio_wb32(pb, track->time); /* modification time */
2354 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2355 if (!track->entry && mov->mode == MODE_ISM)
2356 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2357 else if (!track->entry)
2358 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2360 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2361 avio_wb16(pb, track->language); /* language */
2362 avio_wb16(pb, 0); /* reserved (quality) */
2364 if (version != 0 && track->mode == MODE_MOV) {
2365 av_log(NULL, AV_LOG_ERROR,
2366 "FATAL error, file duration too long for timebase, this file will not be\n"
2367 "playable with quicktime. Choose a different timebase or a different\n"
2368 "container format\n");
2374 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2375 MOVMuxContext *mov, MOVTrack *track)
2377 int64_t pos = avio_tell(pb);
2380 avio_wb32(pb, 0); /* size */
2381 ffio_wfourcc(pb, "mdia");
2382 mov_write_mdhd_tag(pb, mov, track);
2383 mov_write_hdlr_tag(s, pb, track);
2384 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2386 return update_size(pb, pos);
2389 /* transformation matrix
2393 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2394 int16_t d, int16_t tx, int16_t ty)
2396 avio_wb32(pb, a << 16); /* 16.16 format */
2397 avio_wb32(pb, b << 16); /* 16.16 format */
2398 avio_wb32(pb, 0); /* u in 2.30 format */
2399 avio_wb32(pb, c << 16); /* 16.16 format */
2400 avio_wb32(pb, d << 16); /* 16.16 format */
2401 avio_wb32(pb, 0); /* v in 2.30 format */
2402 avio_wb32(pb, tx << 16); /* 16.16 format */
2403 avio_wb32(pb, ty << 16); /* 16.16 format */
2404 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2407 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2408 MOVTrack *track, AVStream *st)
2410 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2411 track->timescale, AV_ROUND_UP);
2412 int version = duration < INT32_MAX ? 0 : 1;
2413 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2417 uint32_t *display_matrix = NULL;
2418 int display_matrix_size, i;
2421 if (mov->per_stream_grouping)
2424 group = st->codecpar->codec_type;
2426 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2427 &display_matrix_size);
2428 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2429 display_matrix = NULL;
2432 if (track->flags & MOV_TRACK_ENABLED)
2433 flags |= MOV_TKHD_FLAG_ENABLED;
2435 if (track->mode == MODE_ISM)
2438 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2439 ffio_wfourcc(pb, "tkhd");
2440 avio_w8(pb, version);
2441 avio_wb24(pb, flags);
2443 avio_wb64(pb, track->time);
2444 avio_wb64(pb, track->time);
2446 avio_wb32(pb, track->time); /* creation time */
2447 avio_wb32(pb, track->time); /* modification time */
2449 avio_wb32(pb, track->track_id); /* track-id */
2450 avio_wb32(pb, 0); /* reserved */
2451 if (!track->entry && mov->mode == MODE_ISM)
2452 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2453 else if (!track->entry)
2454 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2456 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2458 avio_wb32(pb, 0); /* reserved */
2459 avio_wb32(pb, 0); /* reserved */
2460 avio_wb16(pb, 0); /* layer */
2461 avio_wb16(pb, group); /* alternate group) */
2462 /* Volume, only for audio */
2463 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2464 avio_wb16(pb, 0x0100);
2467 avio_wb16(pb, 0); /* reserved */
2469 /* Matrix structure */
2470 if (st && st->metadata) {
2471 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2472 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2474 if (display_matrix) {
2475 for (i = 0; i < 9; i++)
2476 avio_wb32(pb, display_matrix[i]);
2477 } else if (rotation == 90) {
2478 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2479 } else if (rotation == 180) {
2480 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2481 } else if (rotation == 270) {
2482 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2484 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2486 /* Track width and height, for visual only */
2487 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2488 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2489 int64_t track_width_1616;
2490 if (track->mode == MODE_MOV) {
2491 track_width_1616 = track->par->width * 0x10000ULL;
2493 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2494 track->par->width * 0x10000LL,
2495 st->sample_aspect_ratio.den);
2496 if (!track_width_1616 ||
2497 track->height != track->par->height ||
2498 track_width_1616 > UINT32_MAX)
2499 track_width_1616 = track->par->width * 0x10000ULL;
2501 if (track_width_1616 > UINT32_MAX) {
2502 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2503 track_width_1616 = 0;
2505 avio_wb32(pb, track_width_1616);
2506 if (track->height > 0xFFFF) {
2507 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2510 avio_wb32(pb, track->height * 0x10000U);
2518 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2520 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2521 track->par->sample_aspect_ratio.den);
2523 int64_t pos = avio_tell(pb);
2525 avio_wb32(pb, 0); /* size */
2526 ffio_wfourcc(pb, "tapt");
2529 ffio_wfourcc(pb, "clef");
2531 avio_wb32(pb, width << 16);
2532 avio_wb32(pb, track->par->height << 16);
2535 ffio_wfourcc(pb, "prof");
2537 avio_wb32(pb, width << 16);
2538 avio_wb32(pb, track->par->height << 16);
2541 ffio_wfourcc(pb, "enof");
2543 avio_wb32(pb, track->par->width << 16);
2544 avio_wb32(pb, track->par->height << 16);
2546 return update_size(pb, pos);
2549 // This box seems important for the psp playback ... without it the movie seems to hang
2550 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2553 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2554 track->timescale, AV_ROUND_UP);
2555 int version = duration < INT32_MAX ? 0 : 1;
2556 int entry_size, entry_count, size;
2557 int64_t delay, start_ct = track->start_cts;
2558 int64_t start_dts = track->start_dts;
2561 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2563 av_log(mov->fc, AV_LOG_DEBUG,
2564 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2565 track->cluster[0].dts, track->cluster[0].cts,
2566 start_dts, start_ct, track->track_id);
2567 start_dts = track->cluster[0].dts;
2568 start_ct = track->cluster[0].cts;
2572 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2573 track->timescale, AV_ROUND_DOWN);
2574 version |= delay < INT32_MAX ? 0 : 1;
2576 entry_size = (version == 1) ? 20 : 12;
2577 entry_count = 1 + (delay > 0);
2578 size = 24 + entry_count * entry_size;
2580 /* write the atom data */
2581 avio_wb32(pb, size);
2582 ffio_wfourcc(pb, "edts");
2583 avio_wb32(pb, size - 8);
2584 ffio_wfourcc(pb, "elst");
2585 avio_w8(pb, version);
2586 avio_wb24(pb, 0); /* flags */
2588 avio_wb32(pb, entry_count);
2589 if (delay > 0) { /* add an empty edit to delay presentation */
2590 /* In the positive delay case, the delay includes the cts
2591 * offset, and the second edit list entry below trims out
2592 * the same amount from the actual content. This makes sure
2593 * that the offset last sample is included in the edit
2594 * list duration as well. */
2596 avio_wb64(pb, delay);
2599 avio_wb32(pb, delay);
2602 avio_wb32(pb, 0x00010000);
2604 /* Avoid accidentally ending up with start_ct = -1 which has got a
2605 * special meaning. Normally start_ct should end up positive or zero
2606 * here, but use FFMIN in case dts is a small positive integer
2607 * rounded to 0 when represented in MOV_TIMESCALE units. */
2608 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2609 start_ct = -FFMIN(start_dts, 0);
2610 /* Note, this delay is calculated from the pts of the first sample,
2611 * ensuring that we don't reduce the duration for cases with
2616 /* For fragmented files, we don't know the full length yet. Setting
2617 * duration to 0 allows us to only specify the offset, including
2618 * the rest of the content (from all future fragments) without specifying
2619 * an explicit duration. */
2620 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2625 avio_wb64(pb, duration);
2626 avio_wb64(pb, start_ct);
2628 avio_wb32(pb, duration);
2629 avio_wb32(pb, start_ct);
2631 avio_wb32(pb, 0x00010000);
2635 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2637 avio_wb32(pb, 20); // size
2638 ffio_wfourcc(pb, "tref");
2639 avio_wb32(pb, 12); // size (subatom)
2640 avio_wl32(pb, track->tref_tag);
2641 avio_wb32(pb, track->tref_id);
2645 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2646 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2648 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2649 ffio_wfourcc(pb, "uuid");
2650 ffio_wfourcc(pb, "USMT");
2651 avio_wb32(pb, 0x21d24fce);
2652 avio_wb32(pb, 0xbb88695c);
2653 avio_wb32(pb, 0xfac9c740);
2654 avio_wb32(pb, 0x1c); // another size here!
2655 ffio_wfourcc(pb, "MTDT");
2656 avio_wb32(pb, 0x00010012);
2657 avio_wb32(pb, 0x0a);
2658 avio_wb32(pb, 0x55c40000);
2664 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2666 AVFormatContext *ctx = track->rtp_ctx;
2667 char buf[1000] = "";
2670 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2671 NULL, NULL, 0, 0, ctx);
2672 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2675 avio_wb32(pb, len + 24);
2676 ffio_wfourcc(pb, "udta");
2677 avio_wb32(pb, len + 16);
2678 ffio_wfourcc(pb, "hnti");
2679 avio_wb32(pb, len + 8);
2680 ffio_wfourcc(pb, "sdp ");
2681 avio_write(pb, buf, len);
2685 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2686 const char *tag, const char *str)
2688 int64_t pos = avio_tell(pb);
2689 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2690 if (!t || !utf8len(t->value))
2693 avio_wb32(pb, 0); /* size */
2694 ffio_wfourcc(pb, tag); /* type */
2695 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2696 return update_size(pb, pos);
2699 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2702 AVIOContext *pb_buf;
2709 ret = avio_open_dyn_buf(&pb_buf);
2713 if (mov->mode & MODE_MP4)
2714 mov_write_track_metadata(pb_buf, st, "name", "title");
2716 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2717 avio_wb32(pb, size + 8);
2718 ffio_wfourcc(pb, "udta");
2719 avio_write(pb, buf, size);
2726 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2727 MOVTrack *track, AVStream *st)
2729 int64_t pos = avio_tell(pb);
2730 int entry_backup = track->entry;
2731 int chunk_backup = track->chunkCount;
2734 /* If we want to have an empty moov, but some samples already have been
2735 * buffered (delay_moov), pretend that no samples have been written yet. */
2736 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2737 track->chunkCount = track->entry = 0;
2739 avio_wb32(pb, 0); /* size */
2740 ffio_wfourcc(pb, "trak");
2741 mov_write_tkhd_tag(pb, mov, track, st);
2743 av_assert2(mov->use_editlist >= 0);
2745 if (track->start_dts != AV_NOPTS_VALUE) {
2746 if (mov->use_editlist)
2747 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2748 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2749 av_log(mov->fc, AV_LOG_WARNING,
2750 "Not writing any edit list even though one would have been required\n");
2753 if (track->tref_tag)
2754 mov_write_tref_tag(pb, track);
2756 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
2758 if (track->mode == MODE_PSP)
2759 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2760 if (track->tag == MKTAG('r','t','p',' '))
2761 mov_write_udta_sdp(pb, track);
2762 if (track->mode == MODE_MOV) {
2763 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2764 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2765 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2766 mov_write_tapt_tag(pb, track);
2769 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2770 mov_write_tapt_tag(pb, track);
2773 mov_write_track_udta_tag(pb, mov, st);
2774 track->entry = entry_backup;
2775 track->chunkCount = chunk_backup;
2776 return update_size(pb, pos);
2779 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2781 int i, has_audio = 0, has_video = 0;
2782 int64_t pos = avio_tell(pb);
2783 int audio_profile = mov->iods_audio_profile;
2784 int video_profile = mov->iods_video_profile;
2785 for (i = 0; i < mov->nb_streams; i++) {
2786 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2787 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
2788 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
2791 if (audio_profile < 0)
2792 audio_profile = 0xFF - has_audio;
2793 if (video_profile < 0)
2794 video_profile = 0xFF - has_video;
2795 avio_wb32(pb, 0x0); /* size */
2796 ffio_wfourcc(pb, "iods");
2797 avio_wb32(pb, 0); /* version & flags */
2798 put_descr(pb, 0x10, 7);
2799 avio_wb16(pb, 0x004f);
2802 avio_w8(pb, audio_profile);
2803 avio_w8(pb, video_profile);
2805 return update_size(pb, pos);
2808 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2810 avio_wb32(pb, 0x20); /* size */
2811 ffio_wfourcc(pb, "trex");
2812 avio_wb32(pb, 0); /* version & flags */
2813 avio_wb32(pb, track->track_id); /* track ID */
2814 avio_wb32(pb, 1); /* default sample description index */
2815 avio_wb32(pb, 0); /* default sample duration */
2816 avio_wb32(pb, 0); /* default sample size */
2817 avio_wb32(pb, 0); /* default sample flags */
2821 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2823 int64_t pos = avio_tell(pb);
2825 avio_wb32(pb, 0x0); /* size */
2826 ffio_wfourcc(pb, "mvex");
2827 for (i = 0; i < mov->nb_streams; i++)
2828 mov_write_trex_tag(pb, &mov->tracks[i]);
2829 return update_size(pb, pos);
2832 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2834 int max_track_id = 1, i;
2835 int64_t max_track_len = 0;
2838 for (i = 0; i < mov->nb_streams; i++) {
2839 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2840 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2842 mov->tracks[i].timescale,
2844 if (max_track_len < max_track_len_temp)
2845 max_track_len = max_track_len_temp;
2846 if (max_track_id < mov->tracks[i].track_id)
2847 max_track_id = mov->tracks[i].track_id;
2850 /* If using delay_moov, make sure the output is the same as if no
2851 * samples had been written yet. */
2852 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2857 version = max_track_len < UINT32_MAX ? 0 : 1;
2858 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
2860 ffio_wfourcc(pb, "mvhd");
2861 avio_w8(pb, version);
2862 avio_wb24(pb, 0); /* flags */
2864 avio_wb64(pb, mov->time);
2865 avio_wb64(pb, mov->time);
2867 avio_wb32(pb, mov->time); /* creation time */
2868 avio_wb32(pb, mov->time); /* modification time */
2870 avio_wb32(pb, MOV_TIMESCALE);
2871 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2873 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2874 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2875 avio_wb16(pb, 0); /* reserved */
2876 avio_wb32(pb, 0); /* reserved */
2877 avio_wb32(pb, 0); /* reserved */
2879 /* Matrix structure */
2880 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2882 avio_wb32(pb, 0); /* reserved (preview time) */
2883 avio_wb32(pb, 0); /* reserved (preview duration) */
2884 avio_wb32(pb, 0); /* reserved (poster time) */
2885 avio_wb32(pb, 0); /* reserved (selection time) */
2886 avio_wb32(pb, 0); /* reserved (selection duration) */
2887 avio_wb32(pb, 0); /* reserved (current time) */
2888 avio_wb32(pb, max_track_id + 1); /* Next track id */
2892 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2895 avio_wb32(pb, 33); /* size */
2896 ffio_wfourcc(pb, "hdlr");
2899 ffio_wfourcc(pb, "mdir");
2900 ffio_wfourcc(pb, "appl");
2907 /* helper function to write a data tag with the specified string as data */
2908 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2911 int size = 16 + strlen(data);
2912 avio_wb32(pb, size); /* size */
2913 ffio_wfourcc(pb, "data");
2916 avio_write(pb, data, strlen(data));
2920 lang = ff_mov_iso639_to_lang("und", 1);
2921 avio_wb16(pb, strlen(data)); /* string length */
2922 avio_wb16(pb, lang);
2923 avio_write(pb, data, strlen(data));
2924 return strlen(data) + 4;
2928 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2929 const char *value, int lang, int long_style)
2932 if (value && value[0]) {
2933 int64_t pos = avio_tell(pb);
2934 avio_wb32(pb, 0); /* size */
2935 ffio_wfourcc(pb, name);
2936 mov_write_string_data_tag(pb, value, lang, long_style);
2937 size = update_size(pb, pos);
2942 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
2943 const char *tag, int *lang)
2946 AVDictionaryEntry *t, *t2 = NULL;
2951 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2954 len = strlen(t->key);
2955 snprintf(tag2, sizeof(tag2), "%s-", tag);
2956 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2957 len2 = strlen(t2->key);
2958 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2959 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2967 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2968 const char *name, const char *tag,
2972 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
2975 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2978 /* iTunes bpm number */
2979 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2981 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2982 int size = 0, tmpo = t ? atoi(t->value) : 0;
2985 avio_wb32(pb, size);
2986 ffio_wfourcc(pb, "tmpo");
2987 avio_wb32(pb, size-8); /* size */
2988 ffio_wfourcc(pb, "data");
2989 avio_wb32(pb, 0x15); //type specifier
2991 avio_wb16(pb, tmpo); // data
2996 /* 3GPP TS 26.244 */
2997 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3000 int64_t pos = avio_tell(pb);
3001 double latitude, longitude, altitude;
3002 int32_t latitude_fix, longitude_fix, altitude_fix;
3003 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3004 const char *ptr, *place = "";
3006 static const char *astronomical_body = "earth";
3011 longitude = strtod(ptr, &end);
3013 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3017 latitude = strtod(ptr, &end);
3019 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3023 altitude = strtod(ptr, &end);
3024 /* If no altitude was present, the default 0 should be fine */
3028 latitude_fix = (int32_t) ((1 << 16) * latitude);
3029 longitude_fix = (int32_t) ((1 << 16) * longitude);
3030 altitude_fix = (int32_t) ((1 << 16) * altitude);
3032 avio_wb32(pb, 0); /* size */
3033 ffio_wfourcc(pb, "loci"); /* type */
3034 avio_wb32(pb, 0); /* version + flags */
3035 avio_wb16(pb, lang);
3036 avio_write(pb, place, strlen(place) + 1);
3037 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3038 avio_wb32(pb, latitude_fix);
3039 avio_wb32(pb, longitude_fix);
3040 avio_wb32(pb, altitude_fix);
3041 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3042 avio_w8(pb, 0); /* additional notes, null terminated string */
3044 return update_size(pb, pos);
3047 /* iTunes track or disc number */
3048 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3049 AVFormatContext *s, int disc)
3051 AVDictionaryEntry *t = av_dict_get(s->metadata,
3052 disc ? "disc" : "track",
3054 int size = 0, track = t ? atoi(t->value) : 0;
3057 char *slash = strchr(t->value, '/');
3059 tracks = atoi(slash + 1);
3060 avio_wb32(pb, 32); /* size */
3061 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3062 avio_wb32(pb, 24); /* size */
3063 ffio_wfourcc(pb, "data");
3064 avio_wb32(pb, 0); // 8 bytes empty
3066 avio_wb16(pb, 0); // empty
3067 avio_wb16(pb, track); // track / disc number
3068 avio_wb16(pb, tracks); // total track / disc number
3069 avio_wb16(pb, 0); // empty
3075 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3076 const char *name, const char *tag,
3079 AVDictionaryEntry *t = NULL;
3081 int size = 24 + len;
3083 if (len != 1 && len != 4)
3086 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3088 num = atoi(t->value);
3090 avio_wb32(pb, size);
3091 ffio_wfourcc(pb, name);
3092 avio_wb32(pb, size - 8);
3093 ffio_wfourcc(pb, "data");
3094 avio_wb32(pb, 0x15);
3096 if (len==4) avio_wb32(pb, num);
3097 else avio_w8 (pb, num);
3102 /* iTunes meta data list */
3103 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3106 int64_t pos = avio_tell(pb);
3107 avio_wb32(pb, 0); /* size */
3108 ffio_wfourcc(pb, "ilst");
3109 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3110 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3111 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3112 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3113 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3114 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3115 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3116 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3117 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3119 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3120 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3121 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3122 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3123 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3124 mov_write_string_metadata(s, pb, "desc", "description",1);
3125 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3126 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3127 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3128 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3129 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3130 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3131 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3132 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3133 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3134 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3135 mov_write_trkn_tag(pb, mov, s, 0); // track number
3136 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3137 mov_write_tmpo_tag(pb, s);
3138 return update_size(pb, pos);
3141 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3144 avio_wb32(pb, 33); /* size */
3145 ffio_wfourcc(pb, "hdlr");
3148 ffio_wfourcc(pb, "mdta");
3156 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3159 AVDictionaryEntry *t = NULL;
3160 int64_t pos = avio_tell(pb);
3161 int64_t curpos, entry_pos;
3164 avio_wb32(pb, 0); /* size */
3165 ffio_wfourcc(pb, "keys");
3167 entry_pos = avio_tell(pb);
3168 avio_wb32(pb, 0); /* entry count */
3170 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3171 avio_wb32(pb, strlen(t->key) + 8);
3172 ffio_wfourcc(pb, "mdta");
3173 avio_write(pb, t->key, strlen(t->key));
3176 curpos = avio_tell(pb);
3177 avio_seek(pb, entry_pos, SEEK_SET);
3178 avio_wb32(pb, count); // rewrite entry count
3179 avio_seek(pb, curpos, SEEK_SET);
3181 return update_size(pb, pos);
3184 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3187 AVDictionaryEntry *t = NULL;
3188 int64_t pos = avio_tell(pb);
3189 int count = 1; /* keys are 1-index based */
3191 avio_wb32(pb, 0); /* size */
3192 ffio_wfourcc(pb, "ilst");
3194 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3195 int64_t entry_pos = avio_tell(pb);
3196 avio_wb32(pb, 0); /* size */
3197 avio_wb32(pb, count); /* key */
3198 mov_write_string_data_tag(pb, t->value, 0, 1);
3199 update_size(pb, entry_pos);
3202 return update_size(pb, pos);
3205 /* meta data tags */
3206 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3210 int64_t pos = avio_tell(pb);
3211 avio_wb32(pb, 0); /* size */
3212 ffio_wfourcc(pb, "meta");
3214 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3215 mov_write_mdta_hdlr_tag(pb, mov, s);
3216 mov_write_mdta_keys_tag(pb, mov, s);
3217 mov_write_mdta_ilst_tag(pb, mov, s);
3220 /* iTunes metadata tag */
3221 mov_write_itunes_hdlr_tag(pb, mov, s);
3222 mov_write_ilst_tag(pb, mov, s);
3224 size = update_size(pb, pos);
3228 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3229 const char *name, const char *key)
3232 AVDictionaryEntry *t;
3234 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3237 len = strlen(t->value);
3240 avio_wb32(pb, size);
3241 ffio_wfourcc(pb, name);
3242 avio_write(pb, t->value, len);
3248 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3252 GET_UTF8(val, *b++, return -1;)
3255 avio_wb16(pb, 0x00);
3259 static uint16_t language_code(const char *str)
3261 return (((str[0] - 0x60) & 0x1F) << 10) +
3262 (((str[1] - 0x60) & 0x1F) << 5) +
3263 (( str[2] - 0x60) & 0x1F);
3266 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3267 const char *tag, const char *str)
3269 int64_t pos = avio_tell(pb);
3270 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3271 if (!t || !utf8len(t->value))
3273 avio_wb32(pb, 0); /* size */
3274 ffio_wfourcc(pb, tag); /* type */
3275 avio_wb32(pb, 0); /* version + flags */
3276 if (!strcmp(tag, "yrrc"))
3277 avio_wb16(pb, atoi(t->value));
3279 avio_wb16(pb, language_code("eng")); /* language */
3280 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3281 if (!strcmp(tag, "albm") &&
3282 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3283 avio_w8(pb, atoi(t->value));
3285 return update_size(pb, pos);
3288 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3290 int64_t pos = avio_tell(pb);
3291 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3293 avio_wb32(pb, 0); // size
3294 ffio_wfourcc(pb, "chpl");
3295 avio_wb32(pb, 0x01000000); // version + flags
3296 avio_wb32(pb, 0); // unknown
3297 avio_w8(pb, nb_chapters);
3299 for (i = 0; i < nb_chapters; i++) {
3300 AVChapter *c = s->chapters[i];
3301 AVDictionaryEntry *t;
3302 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3304 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3305 int len = FFMIN(strlen(t->value), 255);
3307 avio_write(pb, t->value, len);
3311 return update_size(pb, pos);
3314 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3317 AVIOContext *pb_buf;
3321 ret = avio_open_dyn_buf(&pb_buf);
3325 if (mov->mode & MODE_3GP) {
3326 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3327 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3328 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3329 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3330 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3331 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3332 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3333 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3334 mov_write_loci_tag(s, pb_buf);
3335 } 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
3336 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3337 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3338 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3339 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3340 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3341 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3342 // currently ignored by mov.c
3343 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3344 // add support for libquicktime, this atom is also actually read by mov.c
3345 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3346 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3347 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3348 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3349 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3350 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3351 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3353 /* iTunes meta data */
3354 mov_write_meta_tag(pb_buf, mov, s);
3355 mov_write_loci_tag(s, pb_buf);
3358 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3359 mov_write_chpl_tag(pb_buf, s);
3361 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3362 avio_wb32(pb, size + 8);
3363 ffio_wfourcc(pb, "udta");
3364 avio_write(pb, buf, size);
3371 static void mov_write_psp_udta_tag(AVIOContext *pb,
3372 const char *str, const char *lang, int type)
3374 int len = utf8len(str) + 1;
3377 avio_wb16(pb, len * 2 + 10); /* size */
3378 avio_wb32(pb, type); /* type */
3379 avio_wb16(pb, language_code(lang)); /* language */
3380 avio_wb16(pb, 0x01); /* ? */
3381 ascii_to_wc(pb, str);
3384 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3386 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3390 pos = avio_tell(pb);
3391 avio_wb32(pb, 0); /* size placeholder*/
3392 ffio_wfourcc(pb, "uuid");
3393 ffio_wfourcc(pb, "USMT");
3394 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3395 avio_wb32(pb, 0xbb88695c);
3396 avio_wb32(pb, 0xfac9c740);
3398 pos2 = avio_tell(pb);
3399 avio_wb32(pb, 0); /* size placeholder*/
3400 ffio_wfourcc(pb, "MTDT");
3404 avio_wb16(pb, 0x0C); /* size */
3405 avio_wb32(pb, 0x0B); /* type */
3406 avio_wb16(pb, language_code("und")); /* language */
3407 avio_wb16(pb, 0x0); /* ? */
3408 avio_wb16(pb, 0x021C); /* data */
3410 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3411 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3412 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3413 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3415 update_size(pb, pos2);
3416 return update_size(pb, pos);
3422 static void build_chunks(MOVTrack *trk)
3425 MOVIentry *chunk = &trk->cluster[0];
3426 uint64_t chunkSize = chunk->size;
3427 chunk->chunkNum = 1;
3428 if (trk->chunkCount)
3430 trk->chunkCount = 1;
3431 for (i = 1; i<trk->entry; i++){
3432 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3433 chunkSize + trk->cluster[i].size < (1<<20)){
3434 chunkSize += trk->cluster[i].size;
3435 chunk->samples_in_chunk += trk->cluster[i].entries;
3437 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3438 chunk=&trk->cluster[i];
3439 chunkSize = chunk->size;
3446 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3447 * the stream ids are used as track ids.
3449 * This assumes mov->tracks and s->streams are in the same order and
3450 * there are no gaps in either of them (so mov->tracks[n] refers to
3453 * As an exception, there can be more entries in
3454 * s->streams than in mov->tracks, in which case new track ids are
3455 * generated (starting after the largest found stream id).
3457 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3461 if (mov->track_ids_ok)
3464 if (mov->use_stream_ids_as_track_ids) {
3465 int next_generated_track_id = 0;
3466 for (i = 0; i < s->nb_streams; i++) {
3467 if (s->streams[i]->id > next_generated_track_id)
3468 next_generated_track_id = s->streams[i]->id;
3471 for (i = 0; i < mov->nb_streams; i++) {
3472 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3475 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3478 for (i = 0; i < mov->nb_streams; i++) {
3479 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3482 mov->tracks[i].track_id = i + 1;
3486 mov->track_ids_ok = 1;
3491 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3495 int64_t pos = avio_tell(pb);
3496 avio_wb32(pb, 0); /* size placeholder*/
3497 ffio_wfourcc(pb, "moov");
3499 mov_setup_track_ids(mov, s);
3501 for (i = 0; i < mov->nb_streams; i++) {
3502 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3505 mov->tracks[i].time = mov->time;
3507 if (mov->tracks[i].entry)
3508 build_chunks(&mov->tracks[i]);
3511 if (mov->chapter_track)
3512 for (i = 0; i < s->nb_streams; i++) {
3513 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3514 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3516 for (i = 0; i < mov->nb_streams; i++) {
3517 MOVTrack *track = &mov->tracks[i];
3518 if (track->tag == MKTAG('r','t','p',' ')) {
3519 track->tref_tag = MKTAG('h','i','n','t');
3520 track->tref_id = mov->tracks[track->src_track].track_id;
3521 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3522 int * fallback, size;
3523 fallback = (int*)av_stream_get_side_data(track->st,
3524 AV_PKT_DATA_FALLBACK_TRACK,
3526 if (fallback != NULL && size == sizeof(int)) {
3527 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3528 track->tref_tag = MKTAG('f','a','l','l');
3529 track->tref_id = mov->tracks[*fallback].track_id;
3534 for (i = 0; i < mov->nb_streams; i++) {
3535 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3536 int src_trk = mov->tracks[i].src_track;
3537 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3538 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3539 //src_trk may have a different timescale than the tmcd track
3540 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3541 mov->tracks[i].timescale,
3542 mov->tracks[src_trk].timescale);
3546 mov_write_mvhd_tag(pb, mov);
3547 if (mov->mode != MODE_MOV && !mov->iods_skip)
3548 mov_write_iods_tag(pb, mov);
3549 for (i = 0; i < mov->nb_streams; i++) {
3550 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3551 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3556 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3557 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3559 if (mov->mode == MODE_PSP)
3560 mov_write_uuidusmt_tag(pb, s);
3562 mov_write_udta_tag(pb, mov, s);
3564 return update_size(pb, pos);
3567 static void param_write_int(AVIOContext *pb, const char *name, int value)
3569 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3572 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3574 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3577 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3580 len = FFMIN(sizeof(buf) / 2 - 1, len);
3581 ff_data_to_hex(buf, value, len, 0);
3582 buf[2 * len] = '\0';
3583 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3586 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3588 int64_t pos = avio_tell(pb);
3590 int64_t manifest_bit_rate = 0;
3591 AVCPBProperties *props = NULL;
3593 static const uint8_t uuid[] = {
3594 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3595 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3599 ffio_wfourcc(pb, "uuid");
3600 avio_write(pb, uuid, sizeof(uuid));
3603 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3604 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3605 avio_printf(pb, "<head>\n");
3606 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3607 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3609 avio_printf(pb, "</head>\n");
3610 avio_printf(pb, "<body>\n");
3611 avio_printf(pb, "<switch>\n");
3613 mov_setup_track_ids(mov, s);
3615 for (i = 0; i < mov->nb_streams; i++) {
3616 MOVTrack *track = &mov->tracks[i];
3618 int track_id = track->track_id;
3620 AVStream *st = track->st;
3621 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3623 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3625 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3631 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3633 if (track->par->bit_rate) {
3634 manifest_bit_rate = track->par->bit_rate;
3636 manifest_bit_rate = props->max_bitrate;
3639 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3641 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3642 param_write_int(pb, "trackID", track_id);
3643 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3644 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3645 if (track->par->codec_id == AV_CODEC_ID_H264) {
3647 int size = track->par->extradata_size;
3648 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3650 param_write_hex(pb, "CodecPrivateData",
3651 ptr ? ptr : track->par->extradata,
3655 param_write_string(pb, "FourCC", "H264");
3656 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3657 param_write_string(pb, "FourCC", "WVC1");
3658 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3659 track->par->extradata_size);
3661 param_write_int(pb, "MaxWidth", track->par->width);
3662 param_write_int(pb, "MaxHeight", track->par->height);
3663 param_write_int(pb, "DisplayWidth", track->par->width);
3664 param_write_int(pb, "DisplayHeight", track->par->height);
3666 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3667 switch (track->par->profile)
3669 case FF_PROFILE_AAC_HE_V2:
3670 param_write_string(pb, "FourCC", "AACP");
3672 case FF_PROFILE_AAC_HE:
3673 param_write_string(pb, "FourCC", "AACH");
3676 param_write_string(pb, "FourCC", "AACL");
3678 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3679 param_write_string(pb, "FourCC", "WMAP");
3681 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3682 track->par->extradata_size);
3683 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3684 track->par->codec_id));
3685 param_write_int(pb, "Channels", track->par->channels);
3686 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3687 param_write_int(pb, "BitsPerSample", 16);
3688 param_write_int(pb, "PacketSize", track->par->block_align ?
3689 track->par->block_align : 4);
3691 avio_printf(pb, "</%s>\n", type);
3693 avio_printf(pb, "</switch>\n");
3694 avio_printf(pb, "</body>\n");
3695 avio_printf(pb, "</smil>\n");
3697 return update_size(pb, pos);
3700 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3703 ffio_wfourcc(pb, "mfhd");
3705 avio_wb32(pb, mov->fragments);
3709 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3711 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3712 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3715 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3716 MOVTrack *track, int64_t moof_offset)
3718 int64_t pos = avio_tell(pb);
3719 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3720 MOV_TFHD_BASE_DATA_OFFSET;
3721 if (!track->entry) {
3722 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3724 flags |= MOV_TFHD_DEFAULT_FLAGS;
3726 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3727 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3728 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3729 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3730 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3733 /* Don't set a default sample size, the silverlight player refuses
3734 * to play files with that set. Don't set a default sample duration,
3735 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3736 * file format says it MUST NOT be set. */
3737 if (track->mode == MODE_ISM)
3738 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3739 MOV_TFHD_BASE_DATA_OFFSET);
3741 avio_wb32(pb, 0); /* size placeholder */
3742 ffio_wfourcc(pb, "tfhd");
3743 avio_w8(pb, 0); /* version */
3744 avio_wb24(pb, flags);
3746 avio_wb32(pb, track->track_id); /* track-id */
3747 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3748 avio_wb64(pb, moof_offset);
3749 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3750 track->default_duration = get_cluster_duration(track, 0);
3751 avio_wb32(pb, track->default_duration);
3753 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3754 track->default_size = track->entry ? track->cluster[0].size : 1;
3755 avio_wb32(pb, track->default_size);
3757 track->default_size = -1;
3759 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3760 /* Set the default flags based on the second sample, if available.
3761 * If the first sample is different, that can be signaled via a separate field. */
3762 if (track->entry > 1)
3763 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
3765 track->default_sample_flags =
3766 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
3767 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3768 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3769 avio_wb32(pb, track->default_sample_flags);
3772 return update_size(pb, pos);
3775 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3776 MOVTrack *track, int moof_size,
3779 int64_t pos = avio_tell(pb);
3780 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3783 for (i = first; i < end; i++) {
3784 if (get_cluster_duration(track, i) != track->default_duration)
3785 flags |= MOV_TRUN_SAMPLE_DURATION;
3786 if (track->cluster[i].size != track->default_size)
3787 flags |= MOV_TRUN_SAMPLE_SIZE;
3788 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3789 flags |= MOV_TRUN_SAMPLE_FLAGS;
3791 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
3792 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
3793 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3794 if (track->flags & MOV_TRACK_CTTS)
3795 flags |= MOV_TRUN_SAMPLE_CTS;
3797 avio_wb32(pb, 0); /* size placeholder */
3798 ffio_wfourcc(pb, "trun");
3799 avio_w8(pb, 0); /* version */
3800 avio_wb24(pb, flags);
3802 avio_wb32(pb, end - first); /* sample count */
3803 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3804 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3806 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3808 avio_wb32(pb, moof_size + 8 + track->data_offset +
3809 track->cluster[first].pos); /* data offset */
3810 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3811 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
3813 for (i = first; i < end; i++) {
3814 if (flags & MOV_TRUN_SAMPLE_DURATION)
3815 avio_wb32(pb, get_cluster_duration(track, i));
3816 if (flags & MOV_TRUN_SAMPLE_SIZE)
3817 avio_wb32(pb, track->cluster[i].size);
3818 if (flags & MOV_TRUN_SAMPLE_FLAGS)
3819 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3820 if (flags & MOV_TRUN_SAMPLE_CTS)
3821 avio_wb32(pb, track->cluster[i].cts);
3824 mov->first_trun = 0;
3825 return update_size(pb, pos);
3828 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3830 int64_t pos = avio_tell(pb);
3831 static const uint8_t uuid[] = {
3832 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3833 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3836 avio_wb32(pb, 0); /* size placeholder */
3837 ffio_wfourcc(pb, "uuid");
3838 avio_write(pb, uuid, sizeof(uuid));
3841 avio_wb64(pb, track->start_dts + track->frag_start +
3842 track->cluster[0].cts);
3843 avio_wb64(pb, track->end_pts -
3844 (track->cluster[0].dts + track->cluster[0].cts));
3846 return update_size(pb, pos);
3849 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3850 MOVTrack *track, int entry)
3852 int n = track->nb_frag_info - 1 - entry, i;
3853 int size = 8 + 16 + 4 + 1 + 16*n;
3854 static const uint8_t uuid[] = {
3855 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3856 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3862 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3863 avio_wb32(pb, size);
3864 ffio_wfourcc(pb, "uuid");
3865 avio_write(pb, uuid, sizeof(uuid));
3869 for (i = 0; i < n; i++) {
3870 int index = entry + 1 + i;
3871 avio_wb64(pb, track->frag_info[index].time);
3872 avio_wb64(pb, track->frag_info[index].duration);
3874 if (n < mov->ism_lookahead) {
3875 int free_size = 16 * (mov->ism_lookahead - n);
3876 avio_wb32(pb, free_size);
3877 ffio_wfourcc(pb, "free");
3878 ffio_fill(pb, 0, free_size - 8);
3884 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3887 int64_t pos = avio_tell(pb);
3889 for (i = 0; i < mov->ism_lookahead; i++) {
3890 /* Update the tfrf tag for the last ism_lookahead fragments,
3891 * nb_frag_info - 1 is the next fragment to be written. */
3892 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3894 avio_seek(pb, pos, SEEK_SET);
3898 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3902 for (i = 0; i < mov->nb_streams; i++) {
3903 MOVTrack *track = &mov->tracks[i];
3904 MOVFragmentInfo *info;
3905 if ((tracks >= 0 && i != tracks) || !track->entry)
3907 track->nb_frag_info++;
3908 if (track->nb_frag_info >= track->frag_info_capacity) {
3909 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3910 if (av_reallocp_array(&track->frag_info,
3912 sizeof(*track->frag_info)))
3913 return AVERROR(ENOMEM);
3914 track->frag_info_capacity = new_capacity;
3916 info = &track->frag_info[track->nb_frag_info - 1];
3917 info->offset = avio_tell(pb);
3919 // Try to recreate the original pts for the first packet
3920 // from the fields we have stored
3921 info->time = track->start_dts + track->frag_start +
3922 track->cluster[0].cts;
3923 info->duration = track->end_pts -
3924 (track->cluster[0].dts + track->cluster[0].cts);
3925 // If the pts is less than zero, we will have trimmed
3926 // away parts of the media track using an edit list,
3927 // and the corresponding start presentation time is zero.
3928 if (info->time < 0) {
3929 info->duration += info->time;
3932 info->tfrf_offset = 0;
3933 mov_write_tfrf_tags(pb, mov, track);
3938 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
3941 for (i = 0; i < mov->nb_streams; i++) {
3942 MOVTrack *track = &mov->tracks[i];
3943 if ((tracks >= 0 && i != tracks) || !track->entry)
3945 if (track->nb_frag_info > max) {
3946 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
3947 track->nb_frag_info = max;
3952 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3954 int64_t pos = avio_tell(pb);
3956 avio_wb32(pb, 0); /* size */
3957 ffio_wfourcc(pb, "tfdt");
3958 avio_w8(pb, 1); /* version */
3960 avio_wb64(pb, track->frag_start);
3961 return update_size(pb, pos);
3964 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3965 MOVTrack *track, int64_t moof_offset,
3968 int64_t pos = avio_tell(pb);
3970 avio_wb32(pb, 0); /* size placeholder */
3971 ffio_wfourcc(pb, "traf");
3973 mov_write_tfhd_tag(pb, mov, track, moof_offset);
3974 if (mov->mode != MODE_ISM)
3975 mov_write_tfdt_tag(pb, track);
3976 for (i = 1; i < track->entry; i++) {
3977 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
3978 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
3982 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
3983 if (mov->mode == MODE_ISM) {
3984 mov_write_tfxd_tag(pb, track);
3986 if (mov->ism_lookahead) {
3987 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3989 if (track->nb_frag_info > 0) {
3990 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3991 if (!info->tfrf_offset)
3992 info->tfrf_offset = avio_tell(pb);
3994 avio_wb32(pb, 8 + size);
3995 ffio_wfourcc(pb, "free");
3996 for (i = 0; i < size; i++)
4001 return update_size(pb, pos);
4004 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4005 int tracks, int moof_size)
4007 int64_t pos = avio_tell(pb);
4010 avio_wb32(pb, 0); /* size placeholder */
4011 ffio_wfourcc(pb, "moof");
4012 mov->first_trun = 1;
4014 mov_write_mfhd_tag(pb, mov);
4015 for (i = 0; i < mov->nb_streams; i++) {
4016 MOVTrack *track = &mov->tracks[i];
4017 if (tracks >= 0 && i != tracks)
4021 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4024 return update_size(pb, pos);
4027 static int mov_write_sidx_tag(AVIOContext *pb,
4028 MOVTrack *track, int ref_size, int total_sidx_size)
4030 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4031 int64_t presentation_time, duration, offset;
4032 int starts_with_SAP, i, entries;
4036 presentation_time = track->start_dts + track->frag_start +
4037 track->cluster[0].cts;
4038 duration = track->end_pts -
4039 (track->cluster[0].dts + track->cluster[0].cts);
4040 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4042 // pts<0 should be cut away using edts
4043 if (presentation_time < 0) {
4044 duration += presentation_time;
4045 presentation_time = 0;
4048 entries = track->nb_frag_info;
4051 presentation_time = track->frag_info[0].time;
4054 avio_wb32(pb, 0); /* size */
4055 ffio_wfourcc(pb, "sidx");
4056 avio_w8(pb, 1); /* version */
4058 avio_wb32(pb, track->track_id); /* reference_ID */
4059 avio_wb32(pb, track->timescale); /* timescale */
4060 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4061 offset_pos = avio_tell(pb);
4062 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4063 avio_wb16(pb, 0); /* reserved */
4065 avio_wb16(pb, entries); /* reference_count */
4066 for (i = 0; i < entries; i++) {
4067 if (!track->entry) {
4068 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4069 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4071 duration = track->frag_info[i].duration;
4072 ref_size = track->frag_info[i].size;
4073 starts_with_SAP = 1;
4075 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4076 avio_wb32(pb, duration); /* subsegment_duration */
4077 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4080 end_pos = avio_tell(pb);
4081 offset = pos + total_sidx_size - end_pos;
4082 avio_seek(pb, offset_pos, SEEK_SET);
4083 avio_wb64(pb, offset);
4084 avio_seek(pb, end_pos, SEEK_SET);
4085 return update_size(pb, pos);
4088 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4089 int tracks, int ref_size)
4092 AVIOContext *avio_buf;
4094 for (round = 0; round < 2; round++) {
4095 // First run one round to calculate the total size of all
4097 // This would be much simpler if we'd only write one sidx
4098 // atom, for the first track in the moof.
4100 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4105 for (i = 0; i < mov->nb_streams; i++) {
4106 MOVTrack *track = &mov->tracks[i];
4107 if (tracks >= 0 && i != tracks)
4109 // When writing a sidx for the full file, entry is 0, but
4110 // we want to include all tracks. ref_size is 0 in this case,
4111 // since we read it from frag_info instead.
4112 if (!track->entry && ref_size > 0)
4114 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4118 total_size = ffio_close_null_buf(avio_buf);
4123 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4126 AVIOContext *avio_buf;
4129 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4131 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4132 moof_size = ffio_close_null_buf(avio_buf);
4134 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4135 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4137 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4138 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4139 mov->ism_lookahead) {
4140 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4142 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4143 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4144 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4148 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4151 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4153 int64_t pos = avio_tell(pb);
4156 avio_wb32(pb, 0); /* size placeholder */
4157 ffio_wfourcc(pb, "tfra");
4158 avio_w8(pb, 1); /* version */
4161 avio_wb32(pb, track->track_id);
4162 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4163 avio_wb32(pb, track->nb_frag_info);
4164 for (i = 0; i < track->nb_frag_info; i++) {
4165 avio_wb64(pb, track->frag_info[i].time);
4166 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4167 avio_w8(pb, 1); /* traf number */
4168 avio_w8(pb, 1); /* trun number */
4169 avio_w8(pb, 1); /* sample number */
4172 return update_size(pb, pos);
4175 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4177 int64_t pos = avio_tell(pb);
4180 avio_wb32(pb, 0); /* size placeholder */
4181 ffio_wfourcc(pb, "mfra");
4182 /* An empty mfra atom is enough to indicate to the publishing point that
4183 * the stream has ended. */
4184 if (mov->flags & FF_MOV_FLAG_ISML)
4185 return update_size(pb, pos);
4187 for (i = 0; i < mov->nb_streams; i++) {
4188 MOVTrack *track = &mov->tracks[i];
4189 if (track->nb_frag_info)
4190 mov_write_tfra_tag(pb, track);
4194 ffio_wfourcc(pb, "mfro");
4195 avio_wb32(pb, 0); /* version + flags */
4196 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4198 return update_size(pb, pos);
4201 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4203 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4204 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4206 mov->mdat_pos = avio_tell(pb);
4207 avio_wb32(pb, 0); /* size placeholder*/
4208 ffio_wfourcc(pb, "mdat");
4212 /* TODO: This needs to be more general */
4213 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4215 MOVMuxContext *mov = s->priv_data;
4216 int64_t pos = avio_tell(pb);
4217 int has_h264 = 0, has_video = 0;
4221 for (i = 0; i < s->nb_streams; i++) {
4222 AVStream *st = s->streams[i];
4223 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4225 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4229 avio_wb32(pb, 0); /* size */
4230 ffio_wfourcc(pb, "ftyp");
4232 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4233 ffio_wfourcc(pb, mov->major_brand);
4234 else if (mov->mode == MODE_3GP) {
4235 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4236 minor = has_h264 ? 0x100 : 0x200;
4237 } else if (mov->mode & MODE_3G2) {
4238 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4239 minor = has_h264 ? 0x20000 : 0x10000;
4240 } else if (mov->mode == MODE_PSP)
4241 ffio_wfourcc(pb, "MSNV");
4242 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4243 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4244 else if (mov->mode == MODE_MP4)
4245 ffio_wfourcc(pb, "isom");
4246 else if (mov->mode == MODE_IPOD)
4247 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4248 else if (mov->mode == MODE_ISM)
4249 ffio_wfourcc(pb, "isml");
4250 else if (mov->mode == MODE_F4V)
4251 ffio_wfourcc(pb, "f4v ");
4253 ffio_wfourcc(pb, "qt ");
4255 avio_wb32(pb, minor);
4257 if (mov->mode == MODE_MOV)
4258 ffio_wfourcc(pb, "qt ");
4259 else if (mov->mode == MODE_ISM) {
4260 ffio_wfourcc(pb, "piff");
4261 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4262 ffio_wfourcc(pb, "isom");
4263 ffio_wfourcc(pb, "iso2");
4265 ffio_wfourcc(pb, "avc1");
4268 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4269 // brand. This is compatible with users that don't understand tfdt.
4270 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4271 ffio_wfourcc(pb, "iso6");
4273 if (mov->mode == MODE_3GP)
4274 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4275 else if (mov->mode & MODE_3G2)
4276 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4277 else if (mov->mode == MODE_PSP)
4278 ffio_wfourcc(pb, "MSNV");
4279 else if (mov->mode == MODE_MP4)
4280 ffio_wfourcc(pb, "mp41");
4282 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4283 ffio_wfourcc(pb, "dash");
4285 return update_size(pb, pos);
4288 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4290 AVStream *video_st = s->streams[0];
4291 AVCodecParameters *video_par = s->streams[0]->codecpar;
4292 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4293 int audio_rate = audio_par->sample_rate;
4294 int64_t frame_rate = video_st->avg_frame_rate.den ?
4295 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4297 int audio_kbitrate = audio_par->bit_rate / 1000;
4298 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4300 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4301 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4302 return AVERROR(EINVAL);
4305 avio_wb32(pb, 0x94); /* size */
4306 ffio_wfourcc(pb, "uuid");
4307 ffio_wfourcc(pb, "PROF");
4309 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4310 avio_wb32(pb, 0xbb88695c);
4311 avio_wb32(pb, 0xfac9c740);
4313 avio_wb32(pb, 0x0); /* ? */
4314 avio_wb32(pb, 0x3); /* 3 sections ? */
4316 avio_wb32(pb, 0x14); /* size */
4317 ffio_wfourcc(pb, "FPRF");
4318 avio_wb32(pb, 0x0); /* ? */
4319 avio_wb32(pb, 0x0); /* ? */
4320 avio_wb32(pb, 0x0); /* ? */
4322 avio_wb32(pb, 0x2c); /* size */
4323 ffio_wfourcc(pb, "APRF"); /* audio */
4325 avio_wb32(pb, 0x2); /* TrackID */
4326 ffio_wfourcc(pb, "mp4a");
4327 avio_wb32(pb, 0x20f);
4329 avio_wb32(pb, audio_kbitrate);
4330 avio_wb32(pb, audio_kbitrate);
4331 avio_wb32(pb, audio_rate);
4332 avio_wb32(pb, audio_par->channels);
4334 avio_wb32(pb, 0x34); /* size */
4335 ffio_wfourcc(pb, "VPRF"); /* video */
4337 avio_wb32(pb, 0x1); /* TrackID */
4338 if (video_par->codec_id == AV_CODEC_ID_H264) {
4339 ffio_wfourcc(pb, "avc1");
4340 avio_wb16(pb, 0x014D);
4341 avio_wb16(pb, 0x0015);
4343 ffio_wfourcc(pb, "mp4v");
4344 avio_wb16(pb, 0x0000);
4345 avio_wb16(pb, 0x0103);
4348 avio_wb32(pb, video_kbitrate);
4349 avio_wb32(pb, video_kbitrate);
4350 avio_wb32(pb, frame_rate);
4351 avio_wb32(pb, frame_rate);
4352 avio_wb16(pb, video_par->width);
4353 avio_wb16(pb, video_par->height);
4354 avio_wb32(pb, 0x010001); /* ? */
4359 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4361 MOVMuxContext *mov = s->priv_data;
4364 mov_write_ftyp_tag(pb,s);
4365 if (mov->mode == MODE_PSP) {
4366 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4367 for (i = 0; i < s->nb_streams; i++) {
4368 AVStream *st = s->streams[i];
4369 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4371 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4377 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4378 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4379 return AVERROR(EINVAL);
4381 return mov_write_uuidprof_tag(pb, s);
4386 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4389 int i, closed_gop = 0;
4391 for (i = 0; i < pkt->size - 4; i++) {
4392 c = (c << 8) + pkt->data[i];
4393 if (c == 0x1b8) { // gop
4394 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4395 } else if (c == 0x100) { // pic
4396 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4397 if (!temp_ref || closed_gop) // I picture is not reordered
4398 *flags = MOV_SYNC_SAMPLE;
4400 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4407 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4409 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4410 int seq = 0, entry = 0;
4411 int key = pkt->flags & AV_PKT_FLAG_KEY;
4412 start = find_next_marker(pkt->data, end);
4413 for (next = start; next < end; start = next) {
4414 next = find_next_marker(start + 4, end);
4415 switch (AV_RB32(start)) {
4416 case VC1_CODE_SEQHDR:
4419 case VC1_CODE_ENTRYPOINT:
4422 case VC1_CODE_SLICE:
4423 trk->vc1_info.slices = 1;
4427 if (!trk->entry && trk->vc1_info.first_packet_seen)
4428 trk->vc1_info.first_frag_written = 1;
4429 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4430 /* First packet in first fragment */
4431 trk->vc1_info.first_packet_seq = seq;
4432 trk->vc1_info.first_packet_entry = entry;
4433 trk->vc1_info.first_packet_seen = 1;
4434 } else if ((seq && !trk->vc1_info.packet_seq) ||
4435 (entry && !trk->vc1_info.packet_entry)) {
4437 for (i = 0; i < trk->entry; i++)
4438 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4439 trk->has_keyframes = 0;
4441 trk->vc1_info.packet_seq = 1;
4443 trk->vc1_info.packet_entry = 1;
4444 if (!trk->vc1_info.first_frag_written) {
4445 /* First fragment */
4446 if ((!seq || trk->vc1_info.first_packet_seq) &&
4447 (!entry || trk->vc1_info.first_packet_entry)) {
4448 /* First packet had the same headers as this one, readd the
4449 * sync sample flag. */
4450 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4451 trk->has_keyframes = 1;
4455 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4457 else if (trk->vc1_info.packet_seq)
4459 else if (trk->vc1_info.packet_entry)
4462 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4463 trk->has_keyframes++;
4467 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4469 MOVMuxContext *mov = s->priv_data;
4474 if (!track->mdat_buf)
4476 if (!mov->mdat_buf) {
4477 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4480 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4481 track->mdat_buf = NULL;
4483 offset = avio_tell(mov->mdat_buf);
4484 avio_write(mov->mdat_buf, buf, buf_size);
4487 for (i = track->entries_flushed; i < track->entry; i++)
4488 track->cluster[i].pos += offset;
4489 track->entries_flushed = track->entry;
4493 static int mov_flush_fragment(AVFormatContext *s, int force)
4495 MOVMuxContext *mov = s->priv_data;
4496 int i, first_track = -1;
4497 int64_t mdat_size = 0;
4499 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4501 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4504 // Try to fill in the duration of the last packet in each stream
4505 // from queued packets in the interleave queues. If the flushing
4506 // of fragments was triggered automatically by an AVPacket, we
4507 // already have reliable info for the end of that track, but other
4508 // tracks may need to be filled in.
4509 for (i = 0; i < s->nb_streams; i++) {
4510 MOVTrack *track = &mov->tracks[i];
4511 if (!track->end_reliable) {
4513 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4514 track->track_duration = pkt.dts - track->start_dts;
4515 if (pkt.pts != AV_NOPTS_VALUE)
4516 track->end_pts = pkt.pts;
4518 track->end_pts = pkt.dts;
4523 for (i = 0; i < mov->nb_streams; i++) {
4524 MOVTrack *track = &mov->tracks[i];
4525 if (track->entry <= 1)
4527 // Sample durations are calculated as the diff of dts values,
4528 // but for the last sample in a fragment, we don't know the dts
4529 // of the first sample in the next fragment, so we have to rely
4530 // on what was set as duration in the AVPacket. Not all callers
4531 // set this though, so we might want to replace it with an
4532 // estimate if it currently is zero.
4533 if (get_cluster_duration(track, track->entry - 1) != 0)
4535 // Use the duration (i.e. dts diff) of the second last sample for
4536 // the last one. This is a wild guess (and fatal if it turns out
4537 // to be too long), but probably the best we can do - having a zero
4538 // duration is bad as well.
4539 track->track_duration += get_cluster_duration(track, track->entry - 2);
4540 track->end_pts += get_cluster_duration(track, track->entry - 2);
4541 if (!mov->missing_duration_warned) {
4542 av_log(s, AV_LOG_WARNING,
4543 "Estimating the duration of the last packet in a "
4544 "fragment, consider setting the duration field in "
4545 "AVPacket instead.\n");
4546 mov->missing_duration_warned = 1;
4550 if (!mov->moov_written) {
4551 int64_t pos = avio_tell(s->pb);
4553 int buf_size, moov_size;
4555 for (i = 0; i < mov->nb_streams; i++)
4556 if (!mov->tracks[i].entry)
4558 /* Don't write the initial moov unless all tracks have data */
4559 if (i < mov->nb_streams && !force)
4562 moov_size = get_moov_size(s);
4563 for (i = 0; i < mov->nb_streams; i++)
4564 mov->tracks[i].data_offset = pos + moov_size + 8;
4566 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4567 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4568 mov_write_identification(s->pb, s);
4569 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4572 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4573 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4574 mov->reserved_header_pos = avio_tell(s->pb);
4576 mov->moov_written = 1;
4580 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4581 mov->mdat_buf = NULL;
4582 avio_wb32(s->pb, buf_size + 8);
4583 ffio_wfourcc(s->pb, "mdat");
4584 avio_write(s->pb, buf, buf_size);
4587 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4588 mov->reserved_header_pos = avio_tell(s->pb);
4590 mov->moov_written = 1;
4592 for (i = 0; i < mov->nb_streams; i++) {
4593 if (mov->tracks[i].entry)
4594 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4595 mov->tracks[i].track_duration -
4596 mov->tracks[i].cluster[0].dts;
4597 mov->tracks[i].entry = 0;
4598 mov->tracks[i].end_reliable = 0;
4604 if (mov->frag_interleave) {
4605 for (i = 0; i < mov->nb_streams; i++) {
4606 MOVTrack *track = &mov->tracks[i];
4608 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4614 mdat_size = avio_tell(mov->mdat_buf);
4617 for (i = 0; i < mov->nb_streams; i++) {
4618 MOVTrack *track = &mov->tracks[i];
4619 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4620 track->data_offset = 0;
4622 track->data_offset = mdat_size;
4623 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4625 if (first_video_track) {
4627 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4628 first_video_track = 0;
4633 if (track->mdat_buf)
4634 mdat_size += avio_tell(track->mdat_buf);
4635 if (first_track < 0)
4642 avio_write_marker(s->pb,
4643 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4644 (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);
4646 for (i = 0; i < mov->nb_streams; i++) {
4647 MOVTrack *track = &mov->tracks[i];
4648 int buf_size, write_moof = 1, moof_tracks = -1;
4650 int64_t duration = 0;
4653 duration = track->start_dts + track->track_duration -
4654 track->cluster[0].dts;
4655 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4656 if (!track->mdat_buf)
4658 mdat_size = avio_tell(track->mdat_buf);
4661 write_moof = i == first_track;
4667 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4670 avio_wb32(s->pb, mdat_size + 8);
4671 ffio_wfourcc(s->pb, "mdat");
4675 track->frag_start += duration;
4677 track->entries_flushed = 0;
4678 track->end_reliable = 0;
4679 if (!mov->frag_interleave) {
4680 if (!track->mdat_buf)
4682 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4683 track->mdat_buf = NULL;
4687 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4688 mov->mdat_buf = NULL;
4691 avio_write(s->pb, buf, buf_size);
4701 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4703 MOVMuxContext *mov = s->priv_data;
4704 int had_moov = mov->moov_written;
4705 int ret = mov_flush_fragment(s, force);
4708 // If using delay_moov, the first flush only wrote the moov,
4709 // not the actual moof+mdat pair, thus flush once again.
4710 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4711 ret = mov_flush_fragment(s, force);
4715 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4717 MOVMuxContext *mov = s->priv_data;
4718 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4723 ref = trk->cluster[trk->entry - 1].dts;
4724 } else if ( trk->start_dts != AV_NOPTS_VALUE
4725 && !trk->frag_discont) {
4726 ref = trk->start_dts + trk->track_duration;
4728 ref = pkt->dts; // Skip tests for the first packet
4730 duration = pkt->dts - ref;
4731 if (pkt->dts < ref || duration >= INT_MAX) {
4732 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4737 pkt->pts = AV_NOPTS_VALUE;
4740 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
4741 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
4742 return AVERROR(EINVAL);
4747 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4749 MOVMuxContext *mov = s->priv_data;
4750 AVIOContext *pb = s->pb;
4751 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4752 AVCodecParameters *par = trk->par;
4753 unsigned int samples_in_chunk = 0;
4754 int size = pkt->size, ret = 0;
4755 uint8_t *reformatted_data = NULL;
4757 ret = check_pkt(s, pkt);
4761 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4763 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4764 if (mov->frag_interleave && mov->fragments > 0) {
4765 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
4766 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
4771 if (!trk->mdat_buf) {
4772 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4777 if (!mov->mdat_buf) {
4778 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4785 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
4786 /* We must find out how many AMR blocks there are in one packet */
4787 static const uint16_t packed_size[16] =
4788 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4791 while (len < size && samples_in_chunk < 100) {
4792 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4795 if (samples_in_chunk > 1) {
4796 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4799 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
4800 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4801 samples_in_chunk = trk->par->frame_size;
4802 } else if (trk->sample_size)
4803 samples_in_chunk = size / trk->sample_size;
4805 samples_in_chunk = 1;
4807 /* copy extradata if it exists */
4808 if (trk->vos_len == 0 && par->extradata_size > 0 &&
4809 !TAG_IS_AVCI(trk->tag) &&
4810 (par->codec_id != AV_CODEC_ID_DNXHD)) {
4811 trk->vos_len = par->extradata_size;
4812 trk->vos_data = av_malloc(trk->vos_len);
4813 if (!trk->vos_data) {
4814 ret = AVERROR(ENOMEM);
4817 memcpy(trk->vos_data, par->extradata, trk->vos_len);
4820 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4821 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4822 if (!s->streams[pkt->stream_index]->nb_frames) {
4823 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4824 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4825 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4828 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4830 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4831 /* from x264 or from bytestream H.264 */
4832 /* NAL reformatting needed */
4833 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4834 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4836 avio_write(pb, reformatted_data, size);
4838 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4839 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
4845 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4848 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4849 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4850 /* extradata is Annex B, assume the bitstream is too and convert it */
4851 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4852 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4853 avio_write(pb, reformatted_data, size);
4855 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4857 #if CONFIG_AC3_PARSER
4858 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
4859 size = handle_eac3(mov, pkt, trk);
4864 avio_write(pb, pkt->data, size);
4867 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4868 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
4869 int nal_size_length = (par->extradata[4] & 0x3) + 1;
4870 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
4872 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
4879 avio_write(pb, pkt->data, size);
4883 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
4884 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4885 /* copy frame to create needed atoms */
4886 trk->vos_len = size;
4887 trk->vos_data = av_malloc(size);
4888 if (!trk->vos_data) {
4889 ret = AVERROR(ENOMEM);
4892 memcpy(trk->vos_data, pkt->data, size);
4895 if (trk->entry >= trk->cluster_capacity) {
4896 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4897 if (av_reallocp_array(&trk->cluster, new_capacity,
4898 sizeof(*trk->cluster))) {
4899 ret = AVERROR(ENOMEM);
4902 trk->cluster_capacity = new_capacity;
4905 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
4906 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4907 trk->cluster[trk->entry].chunkNum = 0;
4908 trk->cluster[trk->entry].size = size;
4909 trk->cluster[trk->entry].entries = samples_in_chunk;
4910 trk->cluster[trk->entry].dts = pkt->dts;
4911 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4912 if (!trk->frag_discont) {
4913 /* First packet of a new fragment. We already wrote the duration
4914 * of the last packet of the previous fragment based on track_duration,
4915 * which might not exactly match our dts. Therefore adjust the dts
4916 * of this packet to be what the previous packets duration implies. */
4917 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4918 /* We also may have written the pts and the corresponding duration
4919 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
4920 * the next fragment. This means the cts of the first sample must
4921 * be the same in all fragments, unless end_pts was updated by
4922 * the packet causing the fragment to be written. */
4923 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
4924 mov->mode == MODE_ISM)
4925 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
4927 /* New fragment, but discontinuous from previous fragments.
4928 * Pretend the duration sum of the earlier fragments is
4929 * pkt->dts - trk->start_dts. */
4930 trk->frag_start = pkt->dts - trk->start_dts;
4931 trk->end_pts = AV_NOPTS_VALUE;
4932 trk->frag_discont = 0;
4936 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4937 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4938 /* Not using edit lists and shifting the first track to start from zero.
4939 * If the other streams start from a later timestamp, we won't be able
4940 * to signal the difference in starting time without an edit list.
4941 * Thus move the timestamp for this first sample to 0, increasing
4942 * its duration instead. */
4943 trk->cluster[trk->entry].dts = trk->start_dts = 0;
4945 if (trk->start_dts == AV_NOPTS_VALUE) {
4946 trk->start_dts = pkt->dts;
4947 if (trk->frag_discont) {
4948 if (mov->use_editlist) {
4949 /* Pretend the whole stream started at pts=0, with earlier fragments
4950 * already written. If the stream started at pts=0, the duration sum
4951 * of earlier fragments would have been pkt->pts. */
4952 trk->frag_start = pkt->pts;
4953 trk->start_dts = pkt->dts - pkt->pts;
4955 /* Pretend the whole stream started at dts=0, with earlier fragments
4956 * already written, with a duration summing up to pkt->dts. */
4957 trk->frag_start = pkt->dts;
4960 trk->frag_discont = 0;
4961 } else if (pkt->dts && mov->moov_written)
4962 av_log(s, AV_LOG_WARNING,
4963 "Track %d starts with a nonzero dts %"PRId64", while the moov "
4964 "already has been written. Set the delay_moov flag to handle "
4966 pkt->stream_index, pkt->dts);
4968 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4969 trk->last_sample_is_subtitle_end = 0;
4971 if (pkt->pts == AV_NOPTS_VALUE) {
4972 av_log(s, AV_LOG_WARNING, "pts has no value\n");
4973 pkt->pts = pkt->dts;
4975 if (pkt->dts != pkt->pts)
4976 trk->flags |= MOV_TRACK_CTTS;
4977 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
4978 trk->cluster[trk->entry].flags = 0;
4979 if (trk->start_cts == AV_NOPTS_VALUE)
4980 trk->start_cts = pkt->pts - pkt->dts;
4981 if (trk->end_pts == AV_NOPTS_VALUE)
4982 trk->end_pts = trk->cluster[trk->entry].dts +
4983 trk->cluster[trk->entry].cts + pkt->duration;
4985 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
4986 trk->cluster[trk->entry].cts +
4989 if (par->codec_id == AV_CODEC_ID_VC1) {
4990 mov_parse_vc1_frame(pkt, trk);
4991 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4992 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4993 trk->entry > 0) { // force sync sample for the first key frame
4994 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4995 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4996 trk->flags |= MOV_TRACK_STPS;
4998 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5000 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5001 trk->has_keyframes++;
5004 trk->sample_count += samples_in_chunk;
5005 mov->mdat_size += size;
5007 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5008 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5009 reformatted_data, size);
5014 av_free(reformatted_data);
5018 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5020 MOVMuxContext *mov = s->priv_data;
5021 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5022 AVCodecParameters *par = trk->par;
5023 int64_t frag_duration = 0;
5024 int size = pkt->size;
5026 int ret = check_pkt(s, pkt);
5030 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5032 for (i = 0; i < s->nb_streams; i++)
5033 mov->tracks[i].frag_discont = 1;
5034 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5038 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5039 trk->start_dts = pkt->dts;
5040 if (pkt->pts != AV_NOPTS_VALUE)
5041 trk->start_cts = pkt->pts - pkt->dts;
5046 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS) {
5048 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5049 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5050 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5052 return AVERROR(ENOMEM);
5053 av_free(par->extradata);
5054 par->extradata = newextra;
5055 memcpy(par->extradata, side, side_size);
5056 par->extradata_size = side_size;
5057 mov->need_rewrite_extradata = 1;
5061 return 0; /* Discard 0 sized packets */
5064 if (trk->entry && pkt->stream_index < s->nb_streams)
5065 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5066 s->streams[pkt->stream_index]->time_base,
5068 if ((mov->max_fragment_duration &&
5069 frag_duration >= mov->max_fragment_duration) ||
5070 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5071 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5072 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5073 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5074 if (frag_duration >= mov->min_fragment_duration) {
5075 // Set the duration of this track to line up with the next
5076 // sample in this track. This avoids relying on AVPacket
5077 // duration, but only helps for this particular track, not
5078 // for the other ones that are flushed at the same time.
5079 trk->track_duration = pkt->dts - trk->start_dts;
5080 if (pkt->pts != AV_NOPTS_VALUE)
5081 trk->end_pts = pkt->pts;
5083 trk->end_pts = pkt->dts;
5084 trk->end_reliable = 1;
5085 mov_auto_flush_fragment(s, 0);
5089 return ff_mov_write_packet(s, pkt);
5092 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5096 uint8_t data[2] = {0};
5099 av_init_packet(&end);
5100 end.size = sizeof(data);
5105 end.stream_index = stream_index;
5107 ret = mov_write_single_packet(s, &end);
5108 av_packet_unref(&end);
5113 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5116 mov_flush_fragment(s, 1);
5120 MOVMuxContext *mov = s->priv_data;
5121 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5124 return mov_write_single_packet(s, pkt); /* Passthrough. */
5127 * Subtitles require special handling.
5129 * 1) For full complaince, every track must have a sample at
5130 * dts == 0, which is rarely true for subtitles. So, as soon
5131 * as we see any packet with dts > 0, write an empty subtitle
5132 * at dts == 0 for any subtitle track with no samples in it.
5134 * 2) For each subtitle track, check if the current packet's
5135 * dts is past the duration of the last subtitle sample. If
5136 * so, we now need to write an end sample for that subtitle.
5138 * This must be done conditionally to allow for subtitles that
5139 * immediately replace each other, in which case an end sample
5140 * is not needed, and is, in fact, actively harmful.
5142 * 3) See mov_write_trailer for how the final end sample is
5145 for (i = 0; i < mov->nb_streams; i++) {
5146 MOVTrack *trk = &mov->tracks[i];
5149 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5150 trk->track_duration < pkt->dts &&
5151 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5152 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5153 if (ret < 0) return ret;
5154 trk->last_sample_is_subtitle_end = 1;
5158 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5159 AVPacket *opkt = pkt;
5160 int reshuffle_ret, ret;
5161 if (trk->is_unaligned_qt_rgb) {
5162 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5163 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5164 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5165 if (reshuffle_ret < 0)
5166 return reshuffle_ret;
5169 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5170 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5175 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5176 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5177 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5178 for (i = 0; i < pkt->size; i++)
5179 pkt->data[i] = ~pkt->data[i];
5181 if (reshuffle_ret) {
5182 ret = mov_write_single_packet(s, pkt);
5185 av_packet_free(&pkt);
5190 return mov_write_single_packet(s, pkt);
5194 // QuickTime chapters involve an additional text track with the chapter names
5195 // as samples, and a tref pointing from the other tracks to the chapter one.
5196 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5200 MOVMuxContext *mov = s->priv_data;
5201 MOVTrack *track = &mov->tracks[tracknum];
5202 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5205 track->mode = mov->mode;
5206 track->tag = MKTAG('t','e','x','t');
5207 track->timescale = MOV_TIMESCALE;
5208 track->par = avcodec_parameters_alloc();
5210 return AVERROR(ENOMEM);
5211 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5213 // These properties are required to make QT recognize the chapter track
5214 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5215 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5216 return AVERROR(ENOMEM);
5217 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5219 if (avio_open_dyn_buf(&pb) >= 0) {
5223 /* Stub header (usually for Quicktime chapter track) */
5225 avio_wb32(pb, 0x01); // displayFlags
5226 avio_w8(pb, 0x00); // horizontal justification
5227 avio_w8(pb, 0x00); // vertical justification
5228 avio_w8(pb, 0x00); // bgColourRed
5229 avio_w8(pb, 0x00); // bgColourGreen
5230 avio_w8(pb, 0x00); // bgColourBlue
5231 avio_w8(pb, 0x00); // bgColourAlpha
5233 avio_wb16(pb, 0x00); // defTextBoxTop
5234 avio_wb16(pb, 0x00); // defTextBoxLeft
5235 avio_wb16(pb, 0x00); // defTextBoxBottom
5236 avio_wb16(pb, 0x00); // defTextBoxRight
5238 avio_wb16(pb, 0x00); // startChar
5239 avio_wb16(pb, 0x00); // endChar
5240 avio_wb16(pb, 0x01); // fontID
5241 avio_w8(pb, 0x00); // fontStyleFlags
5242 avio_w8(pb, 0x00); // fontSize
5243 avio_w8(pb, 0x00); // fgColourRed
5244 avio_w8(pb, 0x00); // fgColourGreen
5245 avio_w8(pb, 0x00); // fgColourBlue
5246 avio_w8(pb, 0x00); // fgColourAlpha
5248 avio_wb32(pb, 0x0D); // box size
5249 ffio_wfourcc(pb, "ftab"); // box atom name
5250 avio_wb16(pb, 0x01); // entry count
5252 avio_wb16(pb, 0x01); // font ID
5253 avio_w8(pb, 0x00); // font name length
5255 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5256 track->par->extradata = buf;
5257 track->par->extradata_size = size;
5264 for (i = 0; i < s->nb_chapters; i++) {
5265 AVChapter *c = s->chapters[i];
5266 AVDictionaryEntry *t;
5268 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5269 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5270 pkt.duration = end - pkt.dts;
5272 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5273 static const char encd[12] = {
5274 0x00, 0x00, 0x00, 0x0C,
5276 0x00, 0x00, 0x01, 0x00 };
5277 len = strlen(t->value);
5278 pkt.size = len + 2 + 12;
5279 pkt.data = av_malloc(pkt.size);
5281 return AVERROR(ENOMEM);
5282 AV_WB16(pkt.data, len);
5283 memcpy(pkt.data + 2, t->value, len);
5284 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5285 ff_mov_write_packet(s, &pkt);
5286 av_freep(&pkt.data);
5294 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5298 /* compute the frame number */
5299 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5303 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5306 MOVMuxContext *mov = s->priv_data;
5307 MOVTrack *track = &mov->tracks[index];
5308 AVStream *src_st = s->streams[src_index];
5309 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5310 AVRational rate = find_fps(s, src_st);
5312 /* tmcd track based on video stream */
5313 track->mode = mov->mode;
5314 track->tag = MKTAG('t','m','c','d');
5315 track->src_track = src_index;
5316 track->timescale = mov->tracks[src_index].timescale;
5317 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5318 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5320 /* set st to src_st for metadata access*/
5323 /* encode context: tmcd data stream */
5324 track->par = avcodec_parameters_alloc();
5326 return AVERROR(ENOMEM);
5327 track->par->codec_type = AVMEDIA_TYPE_DATA;
5328 track->par->codec_tag = track->tag;
5329 track->st->avg_frame_rate = av_inv_q(rate);
5331 /* the tmcd track just contains one packet with the frame number */
5332 pkt.data = av_malloc(pkt.size);
5334 return AVERROR(ENOMEM);
5335 AV_WB32(pkt.data, tc.start);
5336 ret = ff_mov_write_packet(s, &pkt);
5342 * st->disposition controls the "enabled" flag in the tkhd tag.
5343 * QuickTime will not play a track if it is not enabled. So make sure
5344 * that one track of each type (audio, video, subtitle) is enabled.
5346 * Subtitles are special. For audio and video, setting "enabled" also
5347 * makes the track "default" (i.e. it is rendered when played). For
5348 * subtitles, an "enabled" subtitle is not rendered by default, but
5349 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5352 static void enable_tracks(AVFormatContext *s)
5354 MOVMuxContext *mov = s->priv_data;
5356 int enabled[AVMEDIA_TYPE_NB];
5357 int first[AVMEDIA_TYPE_NB];
5359 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5364 for (i = 0; i < s->nb_streams; i++) {
5365 AVStream *st = s->streams[i];
5367 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5368 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5371 if (first[st->codecpar->codec_type] < 0)
5372 first[st->codecpar->codec_type] = i;
5373 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5374 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5375 enabled[st->codecpar->codec_type]++;
5379 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5381 case AVMEDIA_TYPE_VIDEO:
5382 case AVMEDIA_TYPE_AUDIO:
5383 case AVMEDIA_TYPE_SUBTITLE:
5385 mov->per_stream_grouping = 1;
5386 if (!enabled[i] && first[i] >= 0)
5387 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5393 static void mov_free(AVFormatContext *s)
5395 MOVMuxContext *mov = s->priv_data;
5398 if (mov->chapter_track) {
5399 if (mov->tracks[mov->chapter_track].par)
5400 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5401 av_freep(&mov->tracks[mov->chapter_track].par);
5404 for (i = 0; i < mov->nb_streams; i++) {
5405 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5406 ff_mov_close_hinting(&mov->tracks[i]);
5407 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5408 av_freep(&mov->tracks[i].par);
5409 av_freep(&mov->tracks[i].cluster);
5410 av_freep(&mov->tracks[i].frag_info);
5412 if (mov->tracks[i].vos_len)
5413 av_freep(&mov->tracks[i].vos_data);
5415 ff_mov_cenc_free(&mov->tracks[i].cenc);
5418 av_freep(&mov->tracks);
5421 static uint32_t rgb_to_yuv(uint32_t rgb)
5426 r = (rgb >> 16) & 0xFF;
5427 g = (rgb >> 8) & 0xFF;
5430 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5431 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5432 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5434 return (y << 16) | (cr << 8) | cb;
5437 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5440 int i, width = 720, height = 480;
5441 int have_palette = 0, have_size = 0;
5442 uint32_t palette[16];
5443 char *cur = st->codecpar->extradata;
5445 while (cur && *cur) {
5446 if (strncmp("palette:", cur, 8) == 0) {
5448 count = sscanf(cur + 8,
5449 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5450 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5451 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5452 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5453 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5454 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5455 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5456 &palette[12], &palette[13], &palette[14], &palette[15]);
5458 for (i = 0; i < count; i++) {
5459 palette[i] = rgb_to_yuv(palette[i]);
5462 } else if (!strncmp("size:", cur, 5)) {
5463 sscanf(cur + 5, "%dx%d", &width, &height);
5466 if (have_palette && have_size)
5468 cur += strcspn(cur, "\n\r");
5469 cur += strspn(cur, "\n\r");
5472 track->vos_data = av_malloc(16*4);
5473 if (!track->vos_data)
5474 return AVERROR(ENOMEM);
5475 for (i = 0; i < 16; i++) {
5476 AV_WB32(track->vos_data + i * 4, palette[i]);
5478 track->vos_len = 16 * 4;
5480 st->codecpar->width = width;
5481 st->codecpar->height = track->height = height;
5486 static int mov_init(AVFormatContext *s)
5488 MOVMuxContext *mov = s->priv_data;
5489 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5490 int i, ret, hint_track = 0, tmcd_track = 0;
5494 /* Default mode == MP4 */
5495 mov->mode = MODE_MP4;
5498 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5499 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5500 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5501 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5502 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5503 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5504 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5507 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5508 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5510 /* Set the FRAGMENT flag if any of the fragmentation methods are
5512 if (mov->max_fragment_duration || mov->max_fragment_size ||
5513 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5514 FF_MOV_FLAG_FRAG_KEYFRAME |
5515 FF_MOV_FLAG_FRAG_CUSTOM))
5516 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5518 /* Set other implicit flags immediately */
5519 if (mov->mode == MODE_ISM)
5520 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5521 FF_MOV_FLAG_FRAGMENT;
5522 if (mov->flags & FF_MOV_FLAG_DASH)
5523 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5524 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5526 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5527 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5528 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5531 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5532 mov->reserved_moov_size = -1;
5535 if (mov->use_editlist < 0) {
5536 mov->use_editlist = 1;
5537 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5538 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5539 // If we can avoid needing an edit list by shifting the
5540 // tracks, prefer that over (trying to) write edit lists
5541 // in fragmented output.
5542 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5543 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5544 mov->use_editlist = 0;
5547 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5548 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5549 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5551 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5552 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5554 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5555 * if the latter is set that's enough and omit_tfhd_offset doesn't
5556 * add anything extra on top of that. */
5557 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5558 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5559 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5561 if (mov->frag_interleave &&
5562 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5563 av_log(s, AV_LOG_ERROR,
5564 "Sample interleaving in fragments is mutually exclusive with "
5565 "omit_tfhd_offset and separate_moof\n");
5566 return AVERROR(EINVAL);
5569 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5570 * is enabled, we don't support non-seekable output at all. */
5571 if (!s->pb->seekable &&
5572 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5573 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5574 return AVERROR(EINVAL);
5577 mov->nb_streams = s->nb_streams;
5578 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5579 mov->chapter_track = mov->nb_streams++;
5581 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5582 /* Add hint tracks for each audio and video stream */
5583 hint_track = mov->nb_streams;
5584 for (i = 0; i < s->nb_streams; i++) {
5585 AVStream *st = s->streams[i];
5586 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5587 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5593 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5594 || mov->write_tmcd == 1) {
5595 tmcd_track = mov->nb_streams;
5597 /* +1 tmcd track for each video stream with a timecode */
5598 for (i = 0; i < s->nb_streams; i++) {
5599 AVStream *st = s->streams[i];
5600 AVDictionaryEntry *t = global_tcr;
5601 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5602 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5604 ret = mov_check_timecode_track(s, &tc, i, t->value);
5606 mov->nb_meta_tmcd++;
5610 /* check if there is already a tmcd track to remux */
5611 if (mov->nb_meta_tmcd) {
5612 for (i = 0; i < s->nb_streams; i++) {
5613 AVStream *st = s->streams[i];
5614 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5615 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5616 "so timecode metadata are now ignored\n");
5617 mov->nb_meta_tmcd = 0;
5622 mov->nb_streams += mov->nb_meta_tmcd;
5625 // Reserve an extra stream for chapters for the case where chapters
5626 // are written in the trailer
5627 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5629 return AVERROR(ENOMEM);
5631 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5632 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5633 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5635 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5636 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5637 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5638 return AVERROR(EINVAL);
5641 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5642 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5643 mov->encryption_kid_len, CENC_KID_SIZE);
5644 return AVERROR(EINVAL);
5647 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5648 mov->encryption_scheme_str);
5649 return AVERROR(EINVAL);
5653 for (i = 0; i < s->nb_streams; i++) {
5654 AVStream *st= s->streams[i];
5655 MOVTrack *track= &mov->tracks[i];
5656 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5659 track->par = st->codecpar;
5660 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5661 if (track->language < 0)
5662 track->language = 0;
5663 track->mode = mov->mode;
5664 track->tag = mov_find_codec_tag(s, track);
5666 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5667 "codec not currently supported in container\n",
5668 avcodec_get_name(st->codecpar->codec_id), i);
5669 return AVERROR(EINVAL);
5671 /* If hinting of this track is enabled by a later hint track,
5672 * this is updated. */
5673 track->hint_track = -1;
5674 track->start_dts = AV_NOPTS_VALUE;
5675 track->start_cts = AV_NOPTS_VALUE;
5676 track->end_pts = AV_NOPTS_VALUE;
5677 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5678 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5679 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5680 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5681 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5682 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5683 return AVERROR(EINVAL);
5685 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5687 if (mov->video_track_timescale) {
5688 track->timescale = mov->video_track_timescale;
5690 track->timescale = st->time_base.den;
5691 while(track->timescale < 10000)
5692 track->timescale *= 2;
5694 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5695 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5696 return AVERROR(EINVAL);
5698 if (track->mode == MODE_MOV && track->timescale > 100000)
5699 av_log(s, AV_LOG_WARNING,
5700 "WARNING codec timebase is very high. If duration is too long,\n"
5701 "file may not be playable by quicktime. Specify a shorter timebase\n"
5702 "or choose different container.\n");
5703 if (track->mode == MODE_MOV &&
5704 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5705 track->tag == MKTAG('r','a','w',' ')) {
5706 enum AVPixelFormat pix_fmt = track->par->format;
5707 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5708 pix_fmt = AV_PIX_FMT_MONOWHITE;
5709 track->is_unaligned_qt_rgb =
5710 pix_fmt == AV_PIX_FMT_RGB24 ||
5711 pix_fmt == AV_PIX_FMT_BGR24 ||
5712 pix_fmt == AV_PIX_FMT_PAL8 ||
5713 pix_fmt == AV_PIX_FMT_GRAY8 ||
5714 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5715 pix_fmt == AV_PIX_FMT_MONOBLACK;
5717 if (track->mode == MODE_MP4 &&
5718 track->par->codec_id == AV_CODEC_ID_VP9) {
5719 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
5720 av_log(s, AV_LOG_ERROR,
5721 "VP9 in MP4 support is experimental, add "
5722 "'-strict %d' if you want to use it.\n",
5723 FF_COMPLIANCE_EXPERIMENTAL);
5724 return AVERROR_EXPERIMENTAL;
5727 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5728 track->timescale = st->codecpar->sample_rate;
5729 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
5730 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
5731 track->audio_vbr = 1;
5732 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
5733 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
5734 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
5735 if (!st->codecpar->block_align) {
5736 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
5737 return AVERROR(EINVAL);
5739 track->sample_size = st->codecpar->block_align;
5740 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
5741 track->audio_vbr = 1;
5743 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
5745 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
5746 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
5747 track->audio_vbr = 1;
5749 if (track->mode != MODE_MOV &&
5750 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
5751 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
5752 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
5753 i, track->par->sample_rate);
5754 return AVERROR(EINVAL);
5756 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
5757 i, track->par->sample_rate);
5760 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5761 track->timescale = st->time_base.den;
5762 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
5763 track->timescale = st->time_base.den;
5765 track->timescale = MOV_TIMESCALE;
5768 track->height = st->codecpar->height;
5769 /* The ism specific timescale isn't mandatory, but is assumed by
5770 * some tools, such as mp4split. */
5771 if (mov->mode == MODE_ISM)
5772 track->timescale = 10000000;
5774 avpriv_set_pts_info(st, 64, 1, track->timescale);
5776 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5777 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
5778 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
5788 static int mov_write_header(AVFormatContext *s)
5790 AVIOContext *pb = s->pb;
5791 MOVMuxContext *mov = s->priv_data;
5792 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5793 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
5795 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5798 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5799 /* Add hint tracks for each audio and video stream */
5800 hint_track = nb_tracks;
5801 for (i = 0; i < s->nb_streams; i++) {
5802 AVStream *st = s->streams[i];
5803 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5804 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5810 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5811 tmcd_track = nb_tracks;
5813 for (i = 0; i < s->nb_streams; i++) {
5815 AVStream *st= s->streams[i];
5816 MOVTrack *track= &mov->tracks[i];
5818 /* copy extradata if it exists */
5819 if (st->codecpar->extradata_size) {
5820 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
5821 mov_create_dvd_sub_decoder_specific_info(track, st);
5822 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
5823 track->vos_len = st->codecpar->extradata_size;
5824 track->vos_data = av_malloc(track->vos_len);
5825 if (!track->vos_data) {
5826 return AVERROR(ENOMEM);
5828 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
5832 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5833 track->par->channel_layout != AV_CH_LAYOUT_MONO)
5836 for (j = 0; j < s->nb_streams; j++) {
5837 AVStream *stj= s->streams[j];
5838 MOVTrack *trackj= &mov->tracks[j];
5842 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5843 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
5844 trackj->language != track->language ||
5845 trackj->tag != track->tag
5848 track->multichannel_as_mono++;
5852 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5853 if ((ret = mov_write_identification(pb, s)) < 0)
5857 if (mov->reserved_moov_size){
5858 mov->reserved_header_pos = avio_tell(pb);
5859 if (mov->reserved_moov_size > 0)
5860 avio_skip(pb, mov->reserved_moov_size);
5863 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5864 /* If no fragmentation options have been set, set a default. */
5865 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
5866 FF_MOV_FLAG_FRAG_CUSTOM)) &&
5867 !mov->max_fragment_duration && !mov->max_fragment_size)
5868 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
5870 if (mov->flags & FF_MOV_FLAG_FASTSTART)
5871 mov->reserved_header_pos = avio_tell(pb);
5872 mov_write_mdat_tag(pb, mov);
5875 ff_parse_creation_time_metadata(s, &mov->time, 1);
5877 mov->time += 0x7C25B080; // 1970 based -> 1904 based
5879 if (mov->chapter_track)
5880 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5883 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5884 /* Initialize the hint tracks for each audio and video stream */
5885 for (i = 0; i < s->nb_streams; i++) {
5886 AVStream *st = s->streams[i];
5887 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5888 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5889 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
5896 if (mov->nb_meta_tmcd) {
5897 /* Initialize the tmcd tracks */
5898 for (i = 0; i < s->nb_streams; i++) {
5899 AVStream *st = s->streams[i];
5902 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5905 t = av_dict_get(st->metadata, "timecode", NULL, 0);
5908 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
5910 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
5919 if (mov->flags & FF_MOV_FLAG_ISML)
5920 mov_write_isml_manifest(pb, mov, s);
5922 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5923 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5924 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
5927 mov->moov_written = 1;
5928 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5929 mov->reserved_header_pos = avio_tell(pb);
5935 static int get_moov_size(AVFormatContext *s)
5938 AVIOContext *moov_buf;
5939 MOVMuxContext *mov = s->priv_data;
5941 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
5943 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
5945 return ffio_close_null_buf(moov_buf);
5948 static int get_sidx_size(AVFormatContext *s)
5952 MOVMuxContext *mov = s->priv_data;
5954 if ((ret = ffio_open_null_buf(&buf)) < 0)
5956 mov_write_sidx_tags(buf, mov, -1, 0);
5957 return ffio_close_null_buf(buf);
5961 * This function gets the moov size if moved to the top of the file: the chunk
5962 * offset table can switch between stco (32-bit entries) to co64 (64-bit
5963 * entries) when the moov is moved to the beginning, so the size of the moov
5964 * would change. It also updates the chunk offset tables.
5966 static int compute_moov_size(AVFormatContext *s)
5968 int i, moov_size, moov_size2;
5969 MOVMuxContext *mov = s->priv_data;
5971 moov_size = get_moov_size(s);
5975 for (i = 0; i < mov->nb_streams; i++)
5976 mov->tracks[i].data_offset += moov_size;
5978 moov_size2 = get_moov_size(s);
5982 /* if the size changed, we just switched from stco to co64 and need to
5983 * update the offsets */
5984 if (moov_size2 != moov_size)
5985 for (i = 0; i < mov->nb_streams; i++)
5986 mov->tracks[i].data_offset += moov_size2 - moov_size;
5991 static int compute_sidx_size(AVFormatContext *s)
5994 MOVMuxContext *mov = s->priv_data;
5996 sidx_size = get_sidx_size(s);
6000 for (i = 0; i < mov->nb_streams; i++)
6001 mov->tracks[i].data_offset += sidx_size;
6006 static int shift_data(AVFormatContext *s)
6008 int ret = 0, moov_size;
6009 MOVMuxContext *mov = s->priv_data;
6010 int64_t pos, pos_end = avio_tell(s->pb);
6011 uint8_t *buf, *read_buf[2];
6012 int read_buf_id = 0;
6014 AVIOContext *read_pb;
6016 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6017 moov_size = compute_sidx_size(s);
6019 moov_size = compute_moov_size(s);
6023 buf = av_malloc(moov_size * 2);
6025 return AVERROR(ENOMEM);
6027 read_buf[1] = buf + moov_size;
6029 /* Shift the data: the AVIO context of the output can only be used for
6030 * writing, so we re-open the same output, but for reading. It also avoids
6031 * a read/seek/write/seek back and forth. */
6033 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6035 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6036 "the second pass (faststart)\n", s->filename);
6040 /* mark the end of the shift to up to the last data we wrote, and get ready
6042 pos_end = avio_tell(s->pb);
6043 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6045 /* start reading at where the new moov will be placed */
6046 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6047 pos = avio_tell(read_pb);
6049 #define READ_BLOCK do { \
6050 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6054 /* shift data by chunk of at most moov_size */
6059 n = read_size[read_buf_id];
6062 avio_write(s->pb, read_buf[read_buf_id], n);
6064 } while (pos < pos_end);
6065 ff_format_io_close(s, &read_pb);
6072 static int mov_write_trailer(AVFormatContext *s)
6074 MOVMuxContext *mov = s->priv_data;
6075 AVIOContext *pb = s->pb;
6080 if (mov->need_rewrite_extradata) {
6081 for (i = 0; i < s->nb_streams; i++) {
6082 MOVTrack *track = &mov->tracks[i];
6083 AVCodecParameters *par = track->par;
6085 track->vos_len = par->extradata_size;
6086 track->vos_data = av_malloc(track->vos_len);
6087 if (!track->vos_data)
6088 return AVERROR(ENOMEM);
6089 memcpy(track->vos_data, par->extradata, track->vos_len);
6091 mov->need_rewrite_extradata = 0;
6095 * Before actually writing the trailer, make sure that there are no
6096 * dangling subtitles, that need a terminating sample.
6098 for (i = 0; i < mov->nb_streams; i++) {
6099 MOVTrack *trk = &mov->tracks[i];
6100 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6101 !trk->last_sample_is_subtitle_end) {
6102 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6103 trk->last_sample_is_subtitle_end = 1;
6107 // If there were no chapters when the header was written, but there
6108 // are chapters now, write them in the trailer. This only works
6109 // when we are not doing fragments.
6110 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6111 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6112 mov->chapter_track = mov->nb_streams++;
6113 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6118 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6119 moov_pos = avio_tell(pb);
6121 /* Write size of mdat tag */
6122 if (mov->mdat_size + 8 <= UINT32_MAX) {
6123 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6124 avio_wb32(pb, mov->mdat_size + 8);
6126 /* overwrite 'wide' placeholder atom */
6127 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6128 /* special value: real atom size will be 64 bit value after
6131 ffio_wfourcc(pb, "mdat");
6132 avio_wb64(pb, mov->mdat_size + 16);
6134 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6136 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6137 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6138 res = shift_data(s);
6141 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6142 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6144 } else if (mov->reserved_moov_size > 0) {
6146 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6148 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6150 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6151 return AVERROR(EINVAL);
6153 avio_wb32(pb, size);
6154 ffio_wfourcc(pb, "free");
6155 ffio_fill(pb, 0, size - 8);
6156 avio_seek(pb, moov_pos, SEEK_SET);
6158 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6163 mov_auto_flush_fragment(s, 1);
6164 for (i = 0; i < mov->nb_streams; i++)
6165 mov->tracks[i].data_offset = 0;
6166 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6168 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6169 res = shift_data(s);
6172 end = avio_tell(pb);
6173 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6174 mov_write_sidx_tags(pb, mov, -1, 0);
6175 avio_seek(pb, end, SEEK_SET);
6176 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6177 mov_write_mfra_tag(pb, mov);
6178 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6179 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6180 mov_write_mfra_tag(pb, mov);
6187 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6190 AVStream *st = s->streams[pkt->stream_index];
6192 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6193 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6194 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6200 #if CONFIG_MOV_MUXER
6202 AVOutputFormat ff_mov_muxer = {
6204 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6205 .extensions = "mov",
6206 .priv_data_size = sizeof(MOVMuxContext),
6207 .audio_codec = AV_CODEC_ID_AAC,
6208 .video_codec = CONFIG_LIBX264_ENCODER ?
6209 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6211 .write_header = mov_write_header,
6212 .write_packet = mov_write_packet,
6213 .write_trailer = mov_write_trailer,
6215 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6216 .codec_tag = (const AVCodecTag* const []){
6217 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6219 .check_bitstream = mov_check_bitstream,
6220 .priv_class = &mov_muxer_class,
6223 #if CONFIG_TGP_MUXER
6225 AVOutputFormat ff_tgp_muxer = {
6227 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6228 .extensions = "3gp",
6229 .priv_data_size = sizeof(MOVMuxContext),
6230 .audio_codec = AV_CODEC_ID_AMR_NB,
6231 .video_codec = AV_CODEC_ID_H263,
6233 .write_header = mov_write_header,
6234 .write_packet = mov_write_packet,
6235 .write_trailer = mov_write_trailer,
6237 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6238 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6239 .check_bitstream = mov_check_bitstream,
6240 .priv_class = &tgp_muxer_class,
6243 #if CONFIG_MP4_MUXER
6245 AVOutputFormat ff_mp4_muxer = {
6247 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6248 .mime_type = "video/mp4",
6249 .extensions = "mp4",
6250 .priv_data_size = sizeof(MOVMuxContext),
6251 .audio_codec = AV_CODEC_ID_AAC,
6252 .video_codec = CONFIG_LIBX264_ENCODER ?
6253 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6255 .write_header = mov_write_header,
6256 .write_packet = mov_write_packet,
6257 .write_trailer = mov_write_trailer,
6259 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6260 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6261 .check_bitstream = mov_check_bitstream,
6262 .priv_class = &mp4_muxer_class,
6265 #if CONFIG_PSP_MUXER
6267 AVOutputFormat ff_psp_muxer = {
6269 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6270 .extensions = "mp4,psp",
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 []){ ff_mp4_obj_type, 0 },
6282 .check_bitstream = mov_check_bitstream,
6283 .priv_class = &psp_muxer_class,
6286 #if CONFIG_TG2_MUXER
6288 AVOutputFormat ff_tg2_muxer = {
6290 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6291 .extensions = "3g2",
6292 .priv_data_size = sizeof(MOVMuxContext),
6293 .audio_codec = AV_CODEC_ID_AMR_NB,
6294 .video_codec = AV_CODEC_ID_H263,
6296 .write_header = mov_write_header,
6297 .write_packet = mov_write_packet,
6298 .write_trailer = mov_write_trailer,
6300 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6301 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6302 .check_bitstream = mov_check_bitstream,
6303 .priv_class = &tg2_muxer_class,
6306 #if CONFIG_IPOD_MUXER
6308 AVOutputFormat ff_ipod_muxer = {
6310 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6311 .mime_type = "video/mp4",
6312 .extensions = "m4v,m4a",
6313 .priv_data_size = sizeof(MOVMuxContext),
6314 .audio_codec = AV_CODEC_ID_AAC,
6315 .video_codec = AV_CODEC_ID_H264,
6317 .write_header = mov_write_header,
6318 .write_packet = mov_write_packet,
6319 .write_trailer = mov_write_trailer,
6321 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6322 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6323 .check_bitstream = mov_check_bitstream,
6324 .priv_class = &ipod_muxer_class,
6327 #if CONFIG_ISMV_MUXER
6329 AVOutputFormat ff_ismv_muxer = {
6331 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6332 .mime_type = "video/mp4",
6333 .extensions = "ismv,isma",
6334 .priv_data_size = sizeof(MOVMuxContext),
6335 .audio_codec = AV_CODEC_ID_AAC,
6336 .video_codec = AV_CODEC_ID_H264,
6338 .write_header = mov_write_header,
6339 .write_packet = mov_write_packet,
6340 .write_trailer = mov_write_trailer,
6342 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6343 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6344 .check_bitstream = mov_check_bitstream,
6345 .priv_class = &ismv_muxer_class,
6348 #if CONFIG_F4V_MUXER
6350 AVOutputFormat ff_f4v_muxer = {
6352 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6353 .mime_type = "application/f4v",
6354 .extensions = "f4v",
6355 .priv_data_size = sizeof(MOVMuxContext),
6356 .audio_codec = AV_CODEC_ID_AAC,
6357 .video_codec = AV_CODEC_ID_H264,
6359 .write_header = mov_write_header,
6360 .write_packet = mov_write_packet,
6361 .write_trailer = mov_write_trailer,
6363 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6364 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6365 .check_bitstream = mov_check_bitstream,
6366 .priv_class = &f4v_muxer_class,