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/get_bits.h"
36 #include "libavcodec/put_bits.h"
37 #include "libavcodec/vc1_common.h"
38 #include "libavcodec/raw.h"
40 #include "libavutil/avstring.h"
41 #include "libavutil/intfloat.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/libm.h"
44 #include "libavutil/opt.h"
45 #include "libavutil/dict.h"
46 #include "libavutil/pixdesc.h"
47 #include "libavutil/timecode.h"
48 #include "libavutil/color_utils.h"
54 static const AVOption options[] = {
55 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
56 { "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" },
57 { "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 },
58 { "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" },
59 { "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" },
60 { "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" },
61 { "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" },
62 { "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" },
63 { "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" },
64 { "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" },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 { "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" },
73 { "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" },
74 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
75 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
76 { "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},
77 { "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},
78 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
79 { "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},
80 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
81 { "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},
82 { "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},
83 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
84 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
85 { "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},
86 { "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},
87 { "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 },
88 { "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 },
89 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
90 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
94 #define MOV_CLASS(flavor)\
95 static const AVClass flavor ## _muxer_class = {\
96 .class_name = #flavor " muxer",\
97 .item_name = av_default_item_name,\
99 .version = LIBAVUTIL_VERSION_INT,\
102 static int get_moov_size(AVFormatContext *s);
104 static int utf8len(const uint8_t *b)
109 GET_UTF8(val, *b++, return -1;)
115 //FIXME support 64 bit variant with wide placeholders
116 static int64_t update_size(AVIOContext *pb, int64_t pos)
118 int64_t curpos = avio_tell(pb);
119 avio_seek(pb, pos, SEEK_SET);
120 avio_wb32(pb, curpos - pos); /* rewrite size */
121 avio_seek(pb, curpos, SEEK_SET);
126 static int co64_required(const MOVTrack *track)
128 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
133 /* Chunk offset atom */
134 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
137 int mode64 = co64_required(track); // use 32 bit size variant if possible
138 int64_t pos = avio_tell(pb);
139 avio_wb32(pb, 0); /* size */
141 ffio_wfourcc(pb, "co64");
143 ffio_wfourcc(pb, "stco");
144 avio_wb32(pb, 0); /* version & flags */
145 avio_wb32(pb, track->chunkCount); /* entry count */
146 for (i = 0; i < track->entry; i++) {
147 if (!track->cluster[i].chunkNum)
150 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
152 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
154 return update_size(pb, pos);
157 /* Sample size atom */
158 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
161 int i, j, entries = 0, tst = -1, oldtst = -1;
163 int64_t pos = avio_tell(pb);
164 avio_wb32(pb, 0); /* size */
165 ffio_wfourcc(pb, "stsz");
166 avio_wb32(pb, 0); /* version & flags */
168 for (i = 0; i < track->entry; i++) {
169 tst = track->cluster[i].size / track->cluster[i].entries;
170 if (oldtst != -1 && tst != oldtst)
173 entries += track->cluster[i].entries;
175 if (equalChunks && track->entry) {
176 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
177 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
178 avio_wb32(pb, sSize); // sample size
179 avio_wb32(pb, entries); // sample count
181 avio_wb32(pb, 0); // sample size
182 avio_wb32(pb, entries); // sample count
183 for (i = 0; i < track->entry; i++) {
184 for (j = 0; j < track->cluster[i].entries; j++) {
185 avio_wb32(pb, track->cluster[i].size /
186 track->cluster[i].entries);
190 return update_size(pb, pos);
193 /* Sample to chunk atom */
194 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
196 int index = 0, oldval = -1, i;
197 int64_t entryPos, curpos;
199 int64_t pos = avio_tell(pb);
200 avio_wb32(pb, 0); /* size */
201 ffio_wfourcc(pb, "stsc");
202 avio_wb32(pb, 0); // version & flags
203 entryPos = avio_tell(pb);
204 avio_wb32(pb, track->chunkCount); // entry count
205 for (i = 0; i < track->entry; i++) {
206 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
207 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
208 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
209 avio_wb32(pb, 0x1); // sample description index
210 oldval = track->cluster[i].samples_in_chunk;
214 curpos = avio_tell(pb);
215 avio_seek(pb, entryPos, SEEK_SET);
216 avio_wb32(pb, index); // rewrite size
217 avio_seek(pb, curpos, SEEK_SET);
219 return update_size(pb, pos);
222 /* Sync sample atom */
223 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
225 int64_t curpos, entryPos;
227 int64_t pos = avio_tell(pb);
228 avio_wb32(pb, 0); // size
229 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
230 avio_wb32(pb, 0); // version & flags
231 entryPos = avio_tell(pb);
232 avio_wb32(pb, track->entry); // entry count
233 for (i = 0; i < track->entry; i++) {
234 if (track->cluster[i].flags & flag) {
235 avio_wb32(pb, i + 1);
239 curpos = avio_tell(pb);
240 avio_seek(pb, entryPos, SEEK_SET);
241 avio_wb32(pb, index); // rewrite size
242 avio_seek(pb, curpos, SEEK_SET);
243 return update_size(pb, pos);
246 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
248 avio_wb32(pb, 0x11); /* size */
249 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
250 else ffio_wfourcc(pb, "damr");
251 ffio_wfourcc(pb, "FFMP");
252 avio_w8(pb, 0); /* decoder version */
254 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
255 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
256 avio_w8(pb, 0x01); /* Frames per sample */
260 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
265 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
267 if (track->vos_len < 7)
271 ffio_wfourcc(pb, "dac3");
273 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
274 fscod = get_bits(&gbc, 2);
275 frmsizecod = get_bits(&gbc, 6);
276 bsid = get_bits(&gbc, 5);
277 bsmod = get_bits(&gbc, 3);
278 acmod = get_bits(&gbc, 3);
280 skip_bits(&gbc, 2); // dsurmod
282 if ((acmod & 1) && acmod != 1)
283 skip_bits(&gbc, 2); // cmixlev
285 skip_bits(&gbc, 2); // surmixlev
287 lfeon = get_bits1(&gbc);
289 init_put_bits(&pbc, buf, sizeof(buf));
290 put_bits(&pbc, 2, fscod);
291 put_bits(&pbc, 5, bsid);
292 put_bits(&pbc, 3, bsmod);
293 put_bits(&pbc, 3, acmod);
294 put_bits(&pbc, 1, lfeon);
295 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
296 put_bits(&pbc, 5, 0); // reserved
298 flush_put_bits(&pbc);
299 avio_write(pb, buf, sizeof(buf));
309 /* Layout of the EC3SpecificBox */
310 /* maximum bitrate */
312 /* number of independent substreams */
315 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
317 /* bit stream identification 5 bits */
319 /* one bit reserved */
320 /* audio service mixing (not supported yet) 1 bit */
321 /* bit stream mode 3 bits */
323 /* audio coding mode 3 bits */
325 /* sub woofer on 1 bit */
327 /* 3 bits reserved */
328 /* number of dependent substreams associated with this substream 4 bits */
330 /* channel locations of the dependent substream(s), if any, 9 bits */
332 /* if there is no dependent substream, then one bit reserved instead */
333 } substream[1]; /* TODO: support 8 independent substreams */
336 #if CONFIG_AC3_PARSER
337 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
340 AC3HeaderInfo tmp, *hdr = &tmp;
341 struct eac3_info *info;
344 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
345 return AVERROR(ENOMEM);
346 info = track->eac3_priv;
348 init_get_bits(&gbc, pkt->data, pkt->size * 8);
349 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
350 /* drop the packets until we see a good one */
352 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
355 return AVERROR_INVALIDDATA;
358 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
359 num_blocks = hdr->num_blocks;
361 if (!info->ec3_done) {
362 /* AC-3 substream must be the first one */
363 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
364 return AVERROR(EINVAL);
366 /* this should always be the case, given that our AC-3 parser
367 * concatenates dependent frames to their independent parent */
368 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
369 /* substream ids must be incremental */
370 if (hdr->substreamid > info->num_ind_sub + 1)
371 return AVERROR(EINVAL);
373 if (hdr->substreamid == info->num_ind_sub + 1) {
374 //info->num_ind_sub++;
375 avpriv_request_sample(track->par, "Multiple independent substreams");
376 return AVERROR_PATCHWELCOME;
377 } else if (hdr->substreamid < info->num_ind_sub ||
378 hdr->substreamid == 0 && info->substream[0].bsid) {
384 /* fill the info needed for the "dec3" atom */
385 info->substream[hdr->substreamid].fscod = hdr->sr_code;
386 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
387 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
388 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
389 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
391 /* Parse dependent substream(s), if any */
392 if (pkt->size != hdr->frame_size) {
393 int cumul_size = hdr->frame_size;
394 int parent = hdr->substreamid;
396 while (cumul_size != pkt->size) {
398 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
399 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
400 return AVERROR_INVALIDDATA;
401 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
402 return AVERROR(EINVAL);
403 cumul_size += hdr->frame_size;
404 info->substream[parent].num_dep_sub++;
406 /* header is parsed up to lfeon, but custom channel map may be needed */
409 /* skip volume control params */
410 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
411 skip_bits(&gbc, 5); // skip dialog normalization
412 if (get_bits1(&gbc)) {
413 skip_bits(&gbc, 8); // skip compression gain word
416 /* get the dependent stream channel map, if exists */
418 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
420 info->substream[parent].chan_loc |= hdr->channel_mode;
426 if (!info->num_blocks && num_blocks == 6)
428 else if (info->num_blocks + num_blocks > 6)
429 return AVERROR_INVALIDDATA;
431 if (!info->num_blocks) {
433 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
435 info->num_blocks = num_blocks;
439 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
441 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
442 info->num_blocks += num_blocks;
443 info->pkt.duration += pkt->duration;
444 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
446 if (info->num_blocks != 6)
448 av_packet_unref(pkt);
449 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
451 av_packet_unref(&info->pkt);
452 info->num_blocks = 0;
459 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
463 struct eac3_info *info;
466 if (!track->eac3_priv)
467 return AVERROR(EINVAL);
469 info = track->eac3_priv;
470 size = 2 + 4 * (info->num_ind_sub + 1);
471 buf = av_malloc(size);
473 size = AVERROR(ENOMEM);
477 init_put_bits(&pbc, buf, size);
478 put_bits(&pbc, 13, info->data_rate);
479 put_bits(&pbc, 3, info->num_ind_sub);
480 for (i = 0; i <= info->num_ind_sub; i++) {
481 put_bits(&pbc, 2, info->substream[i].fscod);
482 put_bits(&pbc, 5, info->substream[i].bsid);
483 put_bits(&pbc, 1, 0); /* reserved */
484 put_bits(&pbc, 1, 0); /* asvc */
485 put_bits(&pbc, 3, info->substream[i].bsmod);
486 put_bits(&pbc, 3, info->substream[i].acmod);
487 put_bits(&pbc, 1, info->substream[i].lfeon);
488 put_bits(&pbc, 5, 0); /* reserved */
489 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
490 if (!info->substream[i].num_dep_sub) {
491 put_bits(&pbc, 1, 0); /* reserved */
494 put_bits(&pbc, 9, info->substream[i].chan_loc);
497 flush_put_bits(&pbc);
499 avio_wb32(pb, size + 8);
500 ffio_wfourcc(pb, "dec3");
501 avio_write(pb, buf, size);
506 av_packet_unref(&info->pkt);
507 av_freep(&track->eac3_priv);
513 * This function writes extradata "as is".
514 * Extradata must be formatted like a valid atom (with size and tag).
516 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
518 avio_write(pb, track->par->extradata, track->par->extradata_size);
519 return track->par->extradata_size;
522 static int mov_write_enda_tag(AVIOContext *pb)
525 ffio_wfourcc(pb, "enda");
526 avio_wb16(pb, 1); /* little endian */
530 static int mov_write_enda_tag_be(AVIOContext *pb)
533 ffio_wfourcc(pb, "enda");
534 avio_wb16(pb, 0); /* big endian */
538 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
543 avio_w8(pb, (size >> (7 * i)) | 0x80);
544 avio_w8(pb, size & 0x7F);
547 static unsigned compute_avg_bitrate(MOVTrack *track)
551 if (!track->track_duration)
553 for (i = 0; i < track->entry; i++)
554 size += track->cluster[i].size;
555 return size * 8 * track->timescale / track->track_duration;
558 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
560 AVCPBProperties *props;
561 int64_t pos = avio_tell(pb);
562 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
563 unsigned avg_bitrate;
565 avio_wb32(pb, 0); // size
566 ffio_wfourcc(pb, "esds");
567 avio_wb32(pb, 0); // Version
570 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
571 avio_wb16(pb, track->track_id);
572 avio_w8(pb, 0x00); // flags (= no flags)
574 // DecoderConfig descriptor
575 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
577 // Object type indication
578 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
579 track->par->codec_id == AV_CODEC_ID_MP3) &&
580 track->par->sample_rate > 24000)
581 avio_w8(pb, 0x6B); // 11172-3
583 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
585 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
586 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
587 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
588 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
589 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
590 avio_w8(pb, 0x15); // flags (= Audiostream)
592 avio_w8(pb, 0x11); // flags (= Visualstream)
594 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
597 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
599 avg_bitrate = compute_avg_bitrate(track);
600 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)
601 avio_wb32(pb, avg_bitrate);
603 if (track->vos_len) {
604 // DecoderSpecific info descriptor
605 put_descr(pb, 0x05, track->vos_len);
606 avio_write(pb, track->vos_data, track->vos_len);
610 put_descr(pb, 0x06, 1);
612 return update_size(pb, pos);
615 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
617 return codec_id == AV_CODEC_ID_PCM_S24LE ||
618 codec_id == AV_CODEC_ID_PCM_S32LE ||
619 codec_id == AV_CODEC_ID_PCM_F32LE ||
620 codec_id == AV_CODEC_ID_PCM_F64LE;
623 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
625 return codec_id == AV_CODEC_ID_PCM_S24BE ||
626 codec_id == AV_CODEC_ID_PCM_S32BE ||
627 codec_id == AV_CODEC_ID_PCM_F32BE ||
628 codec_id == AV_CODEC_ID_PCM_F64BE;
631 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
634 int64_t pos = avio_tell(pb);
636 avio_wl32(pb, track->tag); // store it byteswapped
637 track->par->codec_tag = av_bswap16(track->tag >> 16);
638 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
640 return update_size(pb, pos);
643 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
646 int64_t pos = avio_tell(pb);
648 ffio_wfourcc(pb, "wfex");
649 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
651 return update_size(pb, pos);
654 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
656 uint32_t layout_tag, bitmap;
657 int64_t pos = avio_tell(pb);
659 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
660 track->par->channel_layout,
663 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
664 "lack of channel information\n");
668 if (track->multichannel_as_mono)
671 avio_wb32(pb, 0); // Size
672 ffio_wfourcc(pb, "chan"); // Type
673 avio_w8(pb, 0); // Version
674 avio_wb24(pb, 0); // Flags
675 avio_wb32(pb, layout_tag); // mChannelLayoutTag
676 avio_wb32(pb, bitmap); // mChannelBitmap
677 avio_wb32(pb, 0); // mNumberChannelDescriptions
679 return update_size(pb, pos);
682 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
684 int64_t pos = avio_tell(pb);
686 avio_wb32(pb, 0); /* size */
687 ffio_wfourcc(pb, "wave");
689 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
690 avio_wb32(pb, 12); /* size */
691 ffio_wfourcc(pb, "frma");
692 avio_wl32(pb, track->tag);
695 if (track->par->codec_id == AV_CODEC_ID_AAC) {
696 /* useless atom needed by mplayer, ipod, not needed by quicktime */
697 avio_wb32(pb, 12); /* size */
698 ffio_wfourcc(pb, "mp4a");
700 mov_write_esds_tag(pb, track);
701 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
702 mov_write_enda_tag(pb);
703 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
704 mov_write_enda_tag_be(pb);
705 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
706 mov_write_amr_tag(pb, track);
707 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
708 mov_write_ac3_tag(pb, track);
709 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
710 mov_write_eac3_tag(pb, track);
711 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
712 track->par->codec_id == AV_CODEC_ID_QDM2) {
713 mov_write_extradata_tag(pb, track);
714 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
715 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
716 mov_write_ms_tag(s, pb, track);
719 avio_wb32(pb, 8); /* size */
720 avio_wb32(pb, 0); /* null tag */
722 return update_size(pb, pos);
725 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
728 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
729 int unescaped_size, seq_found = 0;
730 int level = 0, interlace = 0;
731 int packet_seq = track->vc1_info.packet_seq;
732 int packet_entry = track->vc1_info.packet_entry;
733 int slices = track->vc1_info.slices;
736 if (track->start_dts == AV_NOPTS_VALUE) {
737 /* No packets written yet, vc1_info isn't authoritative yet. */
738 /* Assume inline sequence and entry headers. */
739 packet_seq = packet_entry = 1;
740 av_log(NULL, AV_LOG_WARNING,
741 "moov atom written before any packets, unable to write correct "
742 "dvc1 atom. Set the delay_moov flag to fix this.\n");
745 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
747 return AVERROR(ENOMEM);
748 start = find_next_marker(track->vos_data, end);
749 for (next = start; next < end; start = next) {
752 next = find_next_marker(start + 4, end);
753 size = next - start - 4;
756 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
757 init_get_bits(&gb, unescaped, 8 * unescaped_size);
758 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
759 int profile = get_bits(&gb, 2);
760 if (profile != PROFILE_ADVANCED) {
762 return AVERROR(ENOSYS);
765 level = get_bits(&gb, 3);
766 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
768 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
769 skip_bits(&gb, 1); /* broadcast */
770 interlace = get_bits1(&gb);
771 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
776 return AVERROR(ENOSYS);
779 init_put_bits(&pbc, buf, 7);
780 /* VC1DecSpecStruc */
781 put_bits(&pbc, 4, 12); /* profile - advanced */
782 put_bits(&pbc, 3, level);
783 put_bits(&pbc, 1, 0); /* reserved */
784 /* VC1AdvDecSpecStruc */
785 put_bits(&pbc, 3, level);
786 put_bits(&pbc, 1, 0); /* cbr */
787 put_bits(&pbc, 6, 0); /* reserved */
788 put_bits(&pbc, 1, !interlace); /* no interlace */
789 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
790 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
791 put_bits(&pbc, 1, !slices); /* no slice code */
792 put_bits(&pbc, 1, 0); /* no bframe */
793 put_bits(&pbc, 1, 0); /* reserved */
796 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
797 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
799 put_bits32(&pbc, 0xffffffff);
801 flush_put_bits(&pbc);
808 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
810 uint8_t buf[7] = { 0 };
813 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
816 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
817 ffio_wfourcc(pb, "dvc1");
818 avio_write(pb, buf, sizeof(buf));
819 avio_write(pb, track->vos_data, track->vos_len);
824 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
826 avio_wb32(pb, track->vos_len + 8);
827 ffio_wfourcc(pb, "glbl");
828 avio_write(pb, track->vos_data, track->vos_len);
829 return 8 + track->vos_len;
833 * Compute flags for 'lpcm' tag.
834 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
836 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
839 case AV_CODEC_ID_PCM_F32BE:
840 case AV_CODEC_ID_PCM_F64BE:
842 case AV_CODEC_ID_PCM_F32LE:
843 case AV_CODEC_ID_PCM_F64LE:
845 case AV_CODEC_ID_PCM_U8:
847 case AV_CODEC_ID_PCM_S16BE:
848 case AV_CODEC_ID_PCM_S24BE:
849 case AV_CODEC_ID_PCM_S32BE:
851 case AV_CODEC_ID_PCM_S8:
852 case AV_CODEC_ID_PCM_S16LE:
853 case AV_CODEC_ID_PCM_S24LE:
854 case AV_CODEC_ID_PCM_S32LE:
861 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
865 if (cluster_idx >= track->entry)
868 if (cluster_idx + 1 == track->entry)
869 next_dts = track->track_duration + track->start_dts;
871 next_dts = track->cluster[cluster_idx + 1].dts;
873 next_dts -= track->cluster[cluster_idx].dts;
875 av_assert0(next_dts >= 0);
876 av_assert0(next_dts <= INT_MAX);
881 static int get_samples_per_packet(MOVTrack *track)
883 int i, first_duration;
885 // return track->par->frame_size;
887 /* use 1 for raw PCM */
888 if (!track->audio_vbr)
891 /* check to see if duration is constant for all clusters */
894 first_duration = get_cluster_duration(track, 0);
895 for (i = 1; i < track->entry; i++) {
896 if (get_cluster_duration(track, i) != first_duration)
899 return first_duration;
902 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
904 int64_t pos = avio_tell(pb);
906 uint32_t tag = track->tag;
908 if (track->mode == MODE_MOV) {
909 if (track->timescale > UINT16_MAX) {
910 if (mov_get_lpcm_flags(track->par->codec_id))
911 tag = AV_RL32("lpcm");
913 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
914 mov_pcm_be_gt16(track->par->codec_id) ||
915 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
916 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
917 track->par->codec_id == AV_CODEC_ID_QDM2) {
922 avio_wb32(pb, 0); /* size */
923 if (mov->encryption_scheme != MOV_ENC_NONE) {
924 ffio_wfourcc(pb, "enca");
926 avio_wl32(pb, tag); // store it byteswapped
928 avio_wb32(pb, 0); /* Reserved */
929 avio_wb16(pb, 0); /* Reserved */
930 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
932 /* SoundDescription */
933 avio_wb16(pb, version); /* Version */
934 avio_wb16(pb, 0); /* Revision level */
935 avio_wb32(pb, 0); /* Reserved */
940 avio_wb16(pb, 0xfffe);
942 avio_wb32(pb, 0x00010000);
944 avio_wb64(pb, av_double2int(track->par->sample_rate));
945 avio_wb32(pb, track->par->channels);
946 avio_wb32(pb, 0x7F000000);
947 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
948 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
949 avio_wb32(pb, track->sample_size);
950 avio_wb32(pb, get_samples_per_packet(track));
952 if (track->mode == MODE_MOV) {
953 avio_wb16(pb, track->par->channels);
954 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
955 track->par->codec_id == AV_CODEC_ID_PCM_S8)
956 avio_wb16(pb, 8); /* bits per sample */
957 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
958 avio_wb16(pb, track->par->bits_per_coded_sample);
961 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
962 } else { /* reserved for mp4/3gp */
968 avio_wb16(pb, 0); /* packet size (= 0) */
969 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
970 track->par->sample_rate : 0);
971 avio_wb16(pb, 0); /* Reserved */
974 if (version == 1) { /* SoundDescription V1 extended info */
975 if (mov_pcm_le_gt16(track->par->codec_id) ||
976 mov_pcm_be_gt16(track->par->codec_id))
977 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
979 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
980 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
981 avio_wb32(pb, track->sample_size); /* Bytes per frame */
982 avio_wb32(pb, 2); /* Bytes per sample */
985 if (track->mode == MODE_MOV &&
986 (track->par->codec_id == AV_CODEC_ID_AAC ||
987 track->par->codec_id == AV_CODEC_ID_AC3 ||
988 track->par->codec_id == AV_CODEC_ID_EAC3 ||
989 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
990 track->par->codec_id == AV_CODEC_ID_ALAC ||
991 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
992 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
993 track->par->codec_id == AV_CODEC_ID_QDM2 ||
994 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
995 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
996 mov_write_wave_tag(s, pb, track);
997 else if (track->tag == MKTAG('m','p','4','a'))
998 mov_write_esds_tag(pb, track);
999 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1000 mov_write_amr_tag(pb, track);
1001 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1002 mov_write_ac3_tag(pb, track);
1003 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1004 mov_write_eac3_tag(pb, track);
1005 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1006 mov_write_extradata_tag(pb, track);
1007 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1008 mov_write_wfex_tag(s, pb, track);
1009 else if (track->vos_len > 0)
1010 mov_write_glbl_tag(pb, track);
1012 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1013 mov_write_chan_tag(s, pb, track);
1015 if (mov->encryption_scheme != MOV_ENC_NONE) {
1016 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1019 return update_size(pb, pos);
1022 static int mov_write_d263_tag(AVIOContext *pb)
1024 avio_wb32(pb, 0xf); /* size */
1025 ffio_wfourcc(pb, "d263");
1026 ffio_wfourcc(pb, "FFMP");
1027 avio_w8(pb, 0); /* decoder version */
1028 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1029 avio_w8(pb, 0xa); /* level */
1030 avio_w8(pb, 0); /* profile */
1034 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1036 int64_t pos = avio_tell(pb);
1039 ffio_wfourcc(pb, "avcC");
1040 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1041 return update_size(pb, pos);
1044 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1046 int64_t pos = avio_tell(pb);
1049 ffio_wfourcc(pb, "vpcC");
1050 avio_wb32(pb, 0); /* version & flags */
1051 ff_isom_write_vpcc(s, pb, track->par);
1052 return update_size(pb, pos);
1055 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1057 int64_t pos = avio_tell(pb);
1060 ffio_wfourcc(pb, "hvcC");
1061 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1062 return update_size(pb, pos);
1065 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1066 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1072 if (track->vos_data && track->vos_len > 0x29) {
1073 if (track->vos_data[0] == 0x00 &&
1074 track->vos_data[1] == 0x00 &&
1075 track->vos_data[2] == 0x02 &&
1076 track->vos_data[3] == 0x80 &&
1077 (track->vos_data[4] == 0x01 || track->vos_data[4] == 0x02)) {
1078 /* looks like a DNxHD bit stream */
1079 interlaced = (track->vos_data[5] & 2);
1080 cid = AV_RB32(track->vos_data + 0x28);
1082 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1086 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1090 avio_wb32(pb, 24); /* size */
1091 ffio_wfourcc(pb, "ACLR");
1092 ffio_wfourcc(pb, "ACLR");
1093 ffio_wfourcc(pb, "0001");
1094 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1095 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1096 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1097 } else { /* Full range (0-255) */
1098 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1100 avio_wb32(pb, 0); /* unknown */
1102 avio_wb32(pb, 24); /* size */
1103 ffio_wfourcc(pb, "APRG");
1104 ffio_wfourcc(pb, "APRG");
1105 ffio_wfourcc(pb, "0001");
1106 avio_wb32(pb, 1); /* unknown */
1107 avio_wb32(pb, 0); /* unknown */
1109 avio_wb32(pb, 120); /* size */
1110 ffio_wfourcc(pb, "ARES");
1111 ffio_wfourcc(pb, "ARES");
1112 ffio_wfourcc(pb, "0001");
1113 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1114 avio_wb32(pb, track->par->width);
1115 /* values below are based on samples created with quicktime and avid codecs */
1117 avio_wb32(pb, track->par->height / 2);
1118 avio_wb32(pb, 2); /* unknown */
1119 avio_wb32(pb, 0); /* unknown */
1120 avio_wb32(pb, 4); /* unknown */
1122 avio_wb32(pb, track->par->height);
1123 avio_wb32(pb, 1); /* unknown */
1124 avio_wb32(pb, 0); /* unknown */
1125 if (track->par->height == 1080)
1126 avio_wb32(pb, 5); /* unknown */
1128 avio_wb32(pb, 6); /* unknown */
1131 for (i = 0; i < 10; i++)
1137 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1140 ffio_wfourcc(pb, "DpxE");
1141 if (track->par->extradata_size >= 12 &&
1142 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1143 avio_wb32(pb, track->par->extradata[11]);
1150 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1152 int tag = track->par->codec_tag;
1154 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
1157 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1158 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1159 else if (track->par->codec_id == AV_CODEC_ID_VP9) tag = MKTAG('v','p','0','9');
1160 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1161 else if (track->par->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1162 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1163 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1164 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1165 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1166 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1167 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1172 static const AVCodecTag codec_ipod_tags[] = {
1173 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1174 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1175 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1176 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1177 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1178 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1179 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1180 { AV_CODEC_ID_NONE, 0 },
1183 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1185 int tag = track->par->codec_tag;
1187 // keep original tag for subs, ipod supports both formats
1188 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1189 (tag == MKTAG('t', 'x', '3', 'g') ||
1190 tag == MKTAG('t', 'e', 'x', 't'))))
1191 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
1193 if (!av_match_ext(s->filename, "m4a") &&
1194 !av_match_ext(s->filename, "m4b") &&
1195 !av_match_ext(s->filename, "m4v"))
1196 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1197 "Quicktime/Ipod might not play the file\n");
1202 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1206 if (track->par->width == 720) { /* SD */
1207 if (track->par->height == 480) { /* NTSC */
1208 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1209 else tag = MKTAG('d','v','c',' ');
1210 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1211 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1212 else tag = MKTAG('d','v','p','p');
1213 } else if (track->par->height == 720) { /* HD 720 line */
1214 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1215 else tag = MKTAG('d','v','h','p');
1216 } else if (track->par->height == 1080) { /* HD 1080 line */
1217 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1218 else tag = MKTAG('d','v','h','6');
1220 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1227 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1229 AVRational rate = st->avg_frame_rate;
1231 #if FF_API_LAVF_AVCTX
1232 FF_DISABLE_DEPRECATION_WARNINGS
1233 rate = av_inv_q(st->codec->time_base);
1234 if (av_timecode_check_frame_rate(rate) < 0) {
1235 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1236 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1237 rate = st->avg_frame_rate;
1239 FF_ENABLE_DEPRECATION_WARNINGS
1245 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1247 int tag = track->par->codec_tag;
1248 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1249 AVStream *st = track->st;
1250 int rate = av_q2d(find_fps(s, st));
1253 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1255 if (track->par->format == AV_PIX_FMT_YUV420P) {
1256 if (track->par->width == 1280 && track->par->height == 720) {
1258 if (rate == 24) tag = MKTAG('x','d','v','4');
1259 else if (rate == 25) tag = MKTAG('x','d','v','5');
1260 else if (rate == 30) tag = MKTAG('x','d','v','1');
1261 else if (rate == 50) tag = MKTAG('x','d','v','a');
1262 else if (rate == 60) tag = MKTAG('x','d','v','9');
1264 } else if (track->par->width == 1440 && track->par->height == 1080) {
1266 if (rate == 24) tag = MKTAG('x','d','v','6');
1267 else if (rate == 25) tag = MKTAG('x','d','v','7');
1268 else if (rate == 30) tag = MKTAG('x','d','v','8');
1270 if (rate == 25) tag = MKTAG('x','d','v','3');
1271 else if (rate == 30) tag = MKTAG('x','d','v','2');
1273 } else if (track->par->width == 1920 && track->par->height == 1080) {
1275 if (rate == 24) tag = MKTAG('x','d','v','d');
1276 else if (rate == 25) tag = MKTAG('x','d','v','e');
1277 else if (rate == 30) tag = MKTAG('x','d','v','f');
1279 if (rate == 25) tag = MKTAG('x','d','v','c');
1280 else if (rate == 30) tag = MKTAG('x','d','v','b');
1283 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1284 if (track->par->width == 1280 && track->par->height == 720) {
1286 if (rate == 24) tag = MKTAG('x','d','5','4');
1287 else if (rate == 25) tag = MKTAG('x','d','5','5');
1288 else if (rate == 30) tag = MKTAG('x','d','5','1');
1289 else if (rate == 50) tag = MKTAG('x','d','5','a');
1290 else if (rate == 60) tag = MKTAG('x','d','5','9');
1292 } else if (track->par->width == 1920 && track->par->height == 1080) {
1294 if (rate == 24) tag = MKTAG('x','d','5','d');
1295 else if (rate == 25) tag = MKTAG('x','d','5','e');
1296 else if (rate == 30) tag = MKTAG('x','d','5','f');
1298 if (rate == 25) tag = MKTAG('x','d','5','c');
1299 else if (rate == 30) tag = MKTAG('x','d','5','b');
1307 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1309 int tag = track->par->codec_tag;
1310 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1311 AVStream *st = track->st;
1312 int rate = av_q2d(find_fps(s, st));
1315 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1317 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1318 if (track->par->width == 960 && track->par->height == 720) {
1320 if (rate == 24) tag = MKTAG('a','i','5','p');
1321 else if (rate == 25) tag = MKTAG('a','i','5','q');
1322 else if (rate == 30) tag = MKTAG('a','i','5','p');
1323 else if (rate == 50) tag = MKTAG('a','i','5','q');
1324 else if (rate == 60) tag = MKTAG('a','i','5','p');
1326 } else if (track->par->width == 1440 && track->par->height == 1080) {
1328 if (rate == 24) tag = MKTAG('a','i','5','3');
1329 else if (rate == 25) tag = MKTAG('a','i','5','2');
1330 else if (rate == 30) tag = MKTAG('a','i','5','3');
1332 if (rate == 50) tag = MKTAG('a','i','5','5');
1333 else if (rate == 60) tag = MKTAG('a','i','5','6');
1336 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1337 if (track->par->width == 1280 && track->par->height == 720) {
1339 if (rate == 24) tag = MKTAG('a','i','1','p');
1340 else if (rate == 25) tag = MKTAG('a','i','1','q');
1341 else if (rate == 30) tag = MKTAG('a','i','1','p');
1342 else if (rate == 50) tag = MKTAG('a','i','1','q');
1343 else if (rate == 60) tag = MKTAG('a','i','1','p');
1345 } else if (track->par->width == 1920 && track->par->height == 1080) {
1347 if (rate == 24) tag = MKTAG('a','i','1','3');
1348 else if (rate == 25) tag = MKTAG('a','i','1','2');
1349 else if (rate == 30) tag = MKTAG('a','i','1','3');
1351 if (rate == 25) tag = MKTAG('a','i','1','5');
1352 else if (rate == 50) tag = MKTAG('a','i','1','5');
1353 else if (rate == 60) tag = MKTAG('a','i','1','6');
1355 } else if ( track->par->width == 4096 && track->par->height == 2160
1356 || track->par->width == 3840 && track->par->height == 2160
1357 || track->par->width == 2048 && track->par->height == 1080) {
1358 tag = MKTAG('a','i','v','x');
1365 static const struct {
1366 enum AVPixelFormat pix_fmt;
1369 } mov_pix_fmt_tags[] = {
1370 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1371 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1372 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1373 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1374 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1375 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1376 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1377 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1378 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1379 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1380 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1381 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1382 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1383 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1384 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1387 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1389 int tag = track->par->codec_tag;
1391 enum AVPixelFormat pix_fmt;
1393 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1394 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1395 tag = mov_pix_fmt_tags[i].tag;
1396 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1397 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1402 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1403 track->par->bits_per_coded_sample);
1404 if (tag == MKTAG('r','a','w',' ') &&
1405 track->par->format != pix_fmt &&
1406 track->par->format != AV_PIX_FMT_NONE)
1407 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1408 av_get_pix_fmt_name(track->par->format));
1412 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1414 int tag = track->par->codec_tag;
1416 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1417 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1418 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1419 track->par->codec_id == AV_CODEC_ID_H263 ||
1420 track->par->codec_id == AV_CODEC_ID_H264 ||
1421 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1422 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1423 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1424 tag = mov_get_dv_codec_tag(s, track);
1425 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1426 tag = mov_get_rawvideo_codec_tag(s, track);
1427 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1428 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1429 else if (track->par->codec_id == AV_CODEC_ID_H264)
1430 tag = mov_get_h264_codec_tag(s, track);
1431 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1432 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1433 if (!tag) { // if no mac fcc found, try with Microsoft tags
1434 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1436 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1437 "the file may be unplayable!\n");
1439 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1440 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1441 if (!tag) { // if no mac fcc found, try with Microsoft tags
1442 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1444 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1445 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1446 "the file may be unplayable!\n");
1449 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1450 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1456 static const AVCodecTag codec_3gp_tags[] = {
1457 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1458 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1459 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1460 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1461 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1462 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1463 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1464 { AV_CODEC_ID_NONE, 0 },
1467 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1468 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1469 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1470 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1471 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1472 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1473 { AV_CODEC_ID_NONE, 0 },
1476 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1480 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1481 tag = mp4_get_codec_tag(s, track);
1482 else if (track->mode == MODE_ISM) {
1483 tag = mp4_get_codec_tag(s, track);
1484 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
1485 tag = MKTAG('w', 'm', 'a', ' ');
1486 } else if (track->mode == MODE_IPOD)
1487 tag = ipod_get_codec_tag(s, track);
1488 else if (track->mode & MODE_3GP)
1489 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
1490 else if (track->mode == MODE_F4V)
1491 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
1493 tag = mov_get_codec_tag(s, track);
1498 /** Write uuid atom.
1499 * Needed to make file play in iPods running newest firmware
1500 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1502 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1505 ffio_wfourcc(pb, "uuid");
1506 avio_wb32(pb, 0x6b6840f2);
1507 avio_wb32(pb, 0x5f244fc5);
1508 avio_wb32(pb, 0xba39a51b);
1509 avio_wb32(pb, 0xcf0323f3);
1514 static const uint16_t fiel_data[] = {
1515 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1518 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1520 unsigned mov_field_order = 0;
1521 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1522 mov_field_order = fiel_data[field_order];
1526 ffio_wfourcc(pb, "fiel");
1527 avio_wb16(pb, mov_field_order);
1531 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1533 int64_t pos = avio_tell(pb);
1534 avio_wb32(pb, 0); /* size */
1535 avio_wl32(pb, track->tag); // store it byteswapped
1536 avio_wb32(pb, 0); /* Reserved */
1537 avio_wb16(pb, 0); /* Reserved */
1538 avio_wb16(pb, 1); /* Data-reference index */
1540 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1541 mov_write_esds_tag(pb, track);
1542 else if (track->par->extradata_size)
1543 avio_write(pb, track->par->extradata, track->par->extradata_size);
1545 return update_size(pb, pos);
1548 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1551 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1552 track->par->sample_aspect_ratio.den, INT_MAX);
1555 ffio_wfourcc(pb, "pasp");
1556 avio_wb32(pb, sar.num);
1557 avio_wb32(pb, sar.den);
1561 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1566 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1568 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1571 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1572 av_log(pb, AV_LOG_DEBUG, "writing gama value %d\n", gama);
1574 av_assert0(track->mode == MODE_MOV);
1576 ffio_wfourcc(pb, "gama");
1577 avio_wb32(pb, gama);
1581 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1586 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1588 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1589 // Ref (MP4): ISO/IEC 14496-12:2012
1591 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1592 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1593 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1594 if ((track->par->width >= 1920 && track->par->height >= 1080)
1595 || (track->par->width == 1280 && track->par->height == 720)) {
1596 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1597 track->par->color_primaries = AVCOL_PRI_BT709;
1598 } else if (track->par->width == 720 && track->height == 576) {
1599 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1600 track->par->color_primaries = AVCOL_PRI_BT470BG;
1601 } else if (track->par->width == 720 &&
1602 (track->height == 486 || track->height == 480)) {
1603 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1604 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1606 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1608 switch (track->par->color_primaries) {
1609 case AVCOL_PRI_BT709:
1610 track->par->color_trc = AVCOL_TRC_BT709;
1611 track->par->color_space = AVCOL_SPC_BT709;
1613 case AVCOL_PRI_SMPTE170M:
1614 case AVCOL_PRI_BT470BG:
1615 track->par->color_trc = AVCOL_TRC_BT709;
1616 track->par->color_space = AVCOL_SPC_SMPTE170M;
1621 /* We should only ever be called by MOV or MP4. */
1622 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1624 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1625 ffio_wfourcc(pb, "colr");
1626 if (track->mode == MODE_MP4)
1627 ffio_wfourcc(pb, "nclx");
1629 ffio_wfourcc(pb, "nclc");
1630 switch (track->par->color_primaries) {
1631 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1632 case AVCOL_PRI_SMPTE170M:
1633 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1634 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1635 default: avio_wb16(pb, 2);
1637 switch (track->par->color_trc) {
1638 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1639 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1640 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1641 default: avio_wb16(pb, 2);
1643 switch (track->par->color_space) {
1644 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1645 case AVCOL_SPC_BT470BG:
1646 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1647 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1648 default: avio_wb16(pb, 2);
1651 if (track->mode == MODE_MP4) {
1652 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1653 avio_w8(pb, full_range << 7);
1660 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1662 AVDictionaryEntry *encoder;
1663 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1664 || (track->par->width == 1440 && track->par->height == 1080)
1665 || (track->par->width == 1920 && track->par->height == 1080);
1667 if (track->mode == MODE_MOV &&
1668 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1669 av_strlcpy(compressor_name, encoder->value, 32);
1670 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1671 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1672 AVStream *st = track->st;
1673 int rate = av_q2d(find_fps(NULL, st));
1674 av_strlcatf(compressor_name, len, "XDCAM");
1675 if (track->par->format == AV_PIX_FMT_YUV422P) {
1676 av_strlcatf(compressor_name, len, " HD422");
1677 } else if(track->par->width == 1440) {
1678 av_strlcatf(compressor_name, len, " HD");
1680 av_strlcatf(compressor_name, len, " EX");
1682 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1684 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1688 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1690 int64_t pos = avio_tell(pb);
1691 char compressor_name[32] = { 0 };
1694 avio_wb32(pb, 0); /* size */
1695 if (mov->encryption_scheme != MOV_ENC_NONE) {
1696 ffio_wfourcc(pb, "encv");
1698 avio_wl32(pb, track->tag); // store it byteswapped
1700 avio_wb32(pb, 0); /* Reserved */
1701 avio_wb16(pb, 0); /* Reserved */
1702 avio_wb16(pb, 1); /* Data-reference index */
1704 avio_wb16(pb, 0); /* Codec stream version */
1705 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1706 if (track->mode == MODE_MOV) {
1707 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1708 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1709 avio_wb32(pb, 0); /* Temporal Quality */
1710 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1712 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1713 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1716 avio_wb32(pb, 0); /* Reserved */
1717 avio_wb32(pb, 0); /* Reserved */
1718 avio_wb32(pb, 0); /* Reserved */
1720 avio_wb16(pb, track->par->width); /* Video width */
1721 avio_wb16(pb, track->height); /* Video height */
1722 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1723 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1724 avio_wb32(pb, 0); /* Data size (= 0) */
1725 avio_wb16(pb, 1); /* Frame count (= 1) */
1727 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1728 find_compressor(compressor_name, 32, track);
1729 avio_w8(pb, strlen(compressor_name));
1730 avio_write(pb, compressor_name, 31);
1732 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1733 avio_wb16(pb, track->par->bits_per_coded_sample |
1734 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1736 avio_wb16(pb, 0x18); /* Reserved */
1738 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1739 int pal_size = 1 << track->par->bits_per_coded_sample;
1741 avio_wb16(pb, 0); /* Color table ID */
1742 avio_wb32(pb, 0); /* Color table seed */
1743 avio_wb16(pb, 0x8000); /* Color table flags */
1744 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1745 for (i = 0; i < pal_size; i++) {
1746 uint32_t rgb = track->palette[i];
1747 uint16_t r = (rgb >> 16) & 0xff;
1748 uint16_t g = (rgb >> 8) & 0xff;
1749 uint16_t b = rgb & 0xff;
1751 avio_wb16(pb, (r << 8) | r);
1752 avio_wb16(pb, (g << 8) | g);
1753 avio_wb16(pb, (b << 8) | b);
1756 avio_wb16(pb, 0xffff); /* Reserved */
1758 if (track->tag == MKTAG('m','p','4','v'))
1759 mov_write_esds_tag(pb, track);
1760 else if (track->par->codec_id == AV_CODEC_ID_H263)
1761 mov_write_d263_tag(pb);
1762 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1763 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1764 mov_write_extradata_tag(pb, track);
1766 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1767 mov_write_avid_tag(pb, track);
1769 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1770 mov_write_hvcc_tag(pb, track);
1771 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1772 mov_write_avcc_tag(pb, track);
1773 if (track->mode == MODE_IPOD)
1774 mov_write_uuid_tag_ipod(pb);
1775 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1776 mov_write_vpcc_tag(mov->fc, pb, track);
1777 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1778 mov_write_dvc1_tag(pb, track);
1779 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1780 track->par->codec_id == AV_CODEC_ID_VP6A) {
1781 /* Don't write any potential extradata here - the cropping
1782 * is signalled via the normal width/height fields. */
1783 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1784 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1785 mov_write_dpxe_tag(pb, track);
1786 } else if (track->vos_len > 0)
1787 mov_write_glbl_tag(pb, track);
1789 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1790 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1791 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1792 int field_order = track->par->field_order;
1794 #if FF_API_LAVF_AVCTX
1795 FF_DISABLE_DEPRECATION_WARNINGS
1796 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1797 field_order = track->st->codec->field_order;
1798 FF_ENABLE_DEPRECATION_WARNINGS
1801 if (field_order != AV_FIELD_UNKNOWN)
1802 mov_write_fiel_tag(pb, track, field_order);
1805 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1806 if (track->mode == MODE_MOV)
1807 mov_write_gama_tag(pb, track, mov->gamma);
1809 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1811 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1812 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1813 mov_write_colr_tag(pb, track);
1815 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1818 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num &&
1819 track->par->sample_aspect_ratio.den != track->par->sample_aspect_ratio.num) {
1820 mov_write_pasp_tag(pb, track);
1823 if (mov->encryption_scheme != MOV_ENC_NONE) {
1824 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1827 /* extra padding for avid stsd */
1828 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1832 return update_size(pb, pos);
1835 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1837 int64_t pos = avio_tell(pb);
1838 avio_wb32(pb, 0); /* size */
1839 ffio_wfourcc(pb, "rtp ");
1840 avio_wb32(pb, 0); /* Reserved */
1841 avio_wb16(pb, 0); /* Reserved */
1842 avio_wb16(pb, 1); /* Data-reference index */
1844 avio_wb16(pb, 1); /* Hint track version */
1845 avio_wb16(pb, 1); /* Highest compatible version */
1846 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1848 avio_wb32(pb, 12); /* size */
1849 ffio_wfourcc(pb, "tims");
1850 avio_wb32(pb, track->timescale);
1852 return update_size(pb, pos);
1855 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1857 uint64_t str_size =strlen(reel_name);
1858 int64_t pos = avio_tell(pb);
1860 if (str_size >= UINT16_MAX){
1861 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1863 return AVERROR(EINVAL);
1866 avio_wb32(pb, 0); /* size */
1867 ffio_wfourcc(pb, "name"); /* Data format */
1868 avio_wb16(pb, str_size); /* string size */
1869 avio_wb16(pb, track->language); /* langcode */
1870 avio_write(pb, reel_name, str_size); /* reel name */
1871 return update_size(pb,pos);
1874 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1876 int64_t pos = avio_tell(pb);
1880 AVDictionaryEntry *t = NULL;
1882 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
1883 #if FF_API_LAVF_AVCTX
1884 FF_DISABLE_DEPRECATION_WARNINGS
1885 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
1886 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
1887 FF_ENABLE_DEPRECATION_WARNINGS
1889 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
1890 return AVERROR(EINVAL);
1893 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
1894 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
1897 if (nb_frames > 255) {
1898 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1899 return AVERROR(EINVAL);
1902 avio_wb32(pb, 0); /* size */
1903 ffio_wfourcc(pb, "tmcd"); /* Data format */
1904 avio_wb32(pb, 0); /* Reserved */
1905 avio_wb32(pb, 1); /* Data reference index */
1906 avio_wb32(pb, 0); /* Flags */
1907 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1908 avio_wb32(pb, track->timescale); /* Timescale */
1909 avio_wb32(pb, frame_duration); /* Frame duration */
1910 avio_w8(pb, nb_frames); /* Number of frames */
1911 avio_w8(pb, 0); /* Reserved */
1913 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1914 if (t && utf8len(t->value) && track->mode != MODE_MP4)
1915 mov_write_source_reference_tag(pb, track, t->value);
1917 avio_wb16(pb, 0); /* zero size */
1920 avio_wb32(pb, 0); /* size */
1921 ffio_wfourcc(pb, "tmcd"); /* Data format */
1922 avio_wb32(pb, 0); /* Reserved */
1923 avio_wb32(pb, 1); /* Data reference index */
1924 if (track->par->extradata_size)
1925 avio_write(pb, track->par->extradata, track->par->extradata_size);
1927 return update_size(pb, pos);
1930 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1932 int64_t pos = avio_tell(pb);
1933 avio_wb32(pb, 0); /* size */
1934 ffio_wfourcc(pb, "stsd");
1935 avio_wb32(pb, 0); /* version & flags */
1936 avio_wb32(pb, 1); /* entry count */
1937 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
1938 mov_write_video_tag(pb, mov, track);
1939 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1940 mov_write_audio_tag(s, pb, mov, track);
1941 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1942 mov_write_subtitle_tag(pb, track);
1943 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
1944 mov_write_rtp_tag(pb, track);
1945 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
1946 mov_write_tmcd_tag(pb, track);
1947 return update_size(pb, pos);
1950 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1952 MOVStts *ctts_entries;
1953 uint32_t entries = 0;
1957 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1959 return AVERROR(ENOMEM);
1960 ctts_entries[0].count = 1;
1961 ctts_entries[0].duration = track->cluster[0].cts;
1962 for (i = 1; i < track->entry; i++) {
1963 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1964 ctts_entries[entries].count++; /* compress */
1967 ctts_entries[entries].duration = track->cluster[i].cts;
1968 ctts_entries[entries].count = 1;
1971 entries++; /* last one */
1972 atom_size = 16 + (entries * 8);
1973 avio_wb32(pb, atom_size); /* size */
1974 ffio_wfourcc(pb, "ctts");
1975 avio_wb32(pb, 0); /* version & flags */
1976 avio_wb32(pb, entries); /* entry count */
1977 for (i = 0; i < entries; i++) {
1978 avio_wb32(pb, ctts_entries[i].count);
1979 avio_wb32(pb, ctts_entries[i].duration);
1981 av_free(ctts_entries);
1985 /* Time to sample atom */
1986 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1988 MOVStts *stts_entries = NULL;
1989 uint32_t entries = -1;
1993 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1994 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1996 return AVERROR(ENOMEM);
1997 stts_entries[0].count = track->sample_count;
1998 stts_entries[0].duration = 1;
2002 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2004 return AVERROR(ENOMEM);
2006 for (i = 0; i < track->entry; i++) {
2007 int duration = get_cluster_duration(track, i);
2008 if (i && duration == stts_entries[entries].duration) {
2009 stts_entries[entries].count++; /* compress */
2012 stts_entries[entries].duration = duration;
2013 stts_entries[entries].count = 1;
2016 entries++; /* last one */
2018 atom_size = 16 + (entries * 8);
2019 avio_wb32(pb, atom_size); /* size */
2020 ffio_wfourcc(pb, "stts");
2021 avio_wb32(pb, 0); /* version & flags */
2022 avio_wb32(pb, entries); /* entry count */
2023 for (i = 0; i < entries; i++) {
2024 avio_wb32(pb, stts_entries[i].count);
2025 avio_wb32(pb, stts_entries[i].duration);
2027 av_free(stts_entries);
2031 static int mov_write_dref_tag(AVIOContext *pb)
2033 avio_wb32(pb, 28); /* size */
2034 ffio_wfourcc(pb, "dref");
2035 avio_wb32(pb, 0); /* version & flags */
2036 avio_wb32(pb, 1); /* entry count */
2038 avio_wb32(pb, 0xc); /* size */
2039 //FIXME add the alis and rsrc atom
2040 ffio_wfourcc(pb, "url ");
2041 avio_wb32(pb, 1); /* version & flags */
2046 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2048 int64_t pos = avio_tell(pb);
2051 avio_wb32(pb, 0); /* size */
2052 ffio_wfourcc(pb, "stbl");
2053 mov_write_stsd_tag(s, pb, mov, track);
2054 mov_write_stts_tag(pb, track);
2055 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2056 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2057 track->has_keyframes && track->has_keyframes < track->entry)
2058 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2059 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2060 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2061 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2062 track->flags & MOV_TRACK_CTTS && track->entry) {
2064 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2067 mov_write_stsc_tag(pb, track);
2068 mov_write_stsz_tag(pb, track);
2069 mov_write_stco_tag(pb, track);
2070 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
2071 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2073 return update_size(pb, pos);
2076 static int mov_write_dinf_tag(AVIOContext *pb)
2078 int64_t pos = avio_tell(pb);
2079 avio_wb32(pb, 0); /* size */
2080 ffio_wfourcc(pb, "dinf");
2081 mov_write_dref_tag(pb);
2082 return update_size(pb, pos);
2085 static int mov_write_nmhd_tag(AVIOContext *pb)
2088 ffio_wfourcc(pb, "nmhd");
2093 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2095 int64_t pos = avio_tell(pb);
2096 const char *font = "Lucida Grande";
2097 avio_wb32(pb, 0); /* size */
2098 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2099 avio_wb32(pb, 0); /* version & flags */
2100 avio_wb16(pb, 0); /* text font */
2101 avio_wb16(pb, 0); /* text face */
2102 avio_wb16(pb, 12); /* text size */
2103 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2104 avio_wb16(pb, 0x0000); /* text color (red) */
2105 avio_wb16(pb, 0x0000); /* text color (green) */
2106 avio_wb16(pb, 0x0000); /* text color (blue) */
2107 avio_wb16(pb, 0xffff); /* background color (red) */
2108 avio_wb16(pb, 0xffff); /* background color (green) */
2109 avio_wb16(pb, 0xffff); /* background color (blue) */
2110 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2111 avio_write(pb, font, strlen(font)); /* font name */
2112 return update_size(pb, pos);
2115 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2117 int64_t pos = avio_tell(pb);
2118 avio_wb32(pb, 0); /* size */
2119 ffio_wfourcc(pb, "gmhd");
2120 avio_wb32(pb, 0x18); /* gmin size */
2121 ffio_wfourcc(pb, "gmin");/* generic media info */
2122 avio_wb32(pb, 0); /* version & flags */
2123 avio_wb16(pb, 0x40); /* graphics mode = */
2124 avio_wb16(pb, 0x8000); /* opColor (r?) */
2125 avio_wb16(pb, 0x8000); /* opColor (g?) */
2126 avio_wb16(pb, 0x8000); /* opColor (b?) */
2127 avio_wb16(pb, 0); /* balance */
2128 avio_wb16(pb, 0); /* reserved */
2131 * This special text atom is required for
2132 * Apple Quicktime chapters. The contents
2133 * don't appear to be documented, so the
2134 * bytes are copied verbatim.
2136 if (track->tag != MKTAG('c','6','0','8')) {
2137 avio_wb32(pb, 0x2C); /* size */
2138 ffio_wfourcc(pb, "text");
2139 avio_wb16(pb, 0x01);
2140 avio_wb32(pb, 0x00);
2141 avio_wb32(pb, 0x00);
2142 avio_wb32(pb, 0x00);
2143 avio_wb32(pb, 0x01);
2144 avio_wb32(pb, 0x00);
2145 avio_wb32(pb, 0x00);
2146 avio_wb32(pb, 0x00);
2147 avio_wb32(pb, 0x00004000);
2148 avio_wb16(pb, 0x0000);
2151 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2152 int64_t tmcd_pos = avio_tell(pb);
2153 avio_wb32(pb, 0); /* size */
2154 ffio_wfourcc(pb, "tmcd");
2155 mov_write_tcmi_tag(pb, track);
2156 update_size(pb, tmcd_pos);
2158 return update_size(pb, pos);
2161 static int mov_write_smhd_tag(AVIOContext *pb)
2163 avio_wb32(pb, 16); /* size */
2164 ffio_wfourcc(pb, "smhd");
2165 avio_wb32(pb, 0); /* version & flags */
2166 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2167 avio_wb16(pb, 0); /* reserved */
2171 static int mov_write_vmhd_tag(AVIOContext *pb)
2173 avio_wb32(pb, 0x14); /* size (always 0x14) */
2174 ffio_wfourcc(pb, "vmhd");
2175 avio_wb32(pb, 0x01); /* version & flags */
2176 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2180 static int is_clcp_track(MOVTrack *track)
2182 return track->tag == MKTAG('c','7','0','8') ||
2183 track->tag == MKTAG('c','6','0','8');
2186 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2188 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2189 int64_t pos = avio_tell(pb);
2193 descr = "DataHandler";
2196 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2197 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2199 descr = "VideoHandler";
2200 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2202 descr = "SoundHandler";
2203 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2204 if (is_clcp_track(track)) {
2206 descr = "ClosedCaptionHandler";
2208 if (track->tag == MKTAG('t','x','3','g')) {
2210 } else if (track->tag == MKTAG('m','p','4','s')) {
2215 descr = "SubtitleHandler";
2217 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2219 descr = "HintHandler";
2220 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2222 descr = "TimeCodeHandler";
2225 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
2226 track->par->codec_tag);
2228 av_log(s, AV_LOG_WARNING,
2229 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
2230 tag_buf, track->par->codec_tag);
2233 // hdlr.name is used by some players to identify the content title
2234 // of the track. So if an alternate handler description is
2235 // specified, use it.
2236 AVDictionaryEntry *t;
2237 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2238 if (t && utf8len(t->value))
2243 avio_wb32(pb, 0); /* size */
2244 ffio_wfourcc(pb, "hdlr");
2245 avio_wb32(pb, 0); /* Version & flags */
2246 avio_write(pb, hdlr, 4); /* handler */
2247 ffio_wfourcc(pb, hdlr_type); /* handler type */
2248 avio_wb32(pb, 0); /* reserved */
2249 avio_wb32(pb, 0); /* reserved */
2250 avio_wb32(pb, 0); /* reserved */
2251 if (!track || track->mode == MODE_MOV)
2252 avio_w8(pb, strlen(descr)); /* pascal string */
2253 avio_write(pb, descr, strlen(descr)); /* handler description */
2254 if (track && track->mode != MODE_MOV)
2255 avio_w8(pb, 0); /* c string */
2256 return update_size(pb, pos);
2259 static int mov_write_hmhd_tag(AVIOContext *pb)
2261 /* This atom must be present, but leaving the values at zero
2262 * seems harmless. */
2263 avio_wb32(pb, 28); /* size */
2264 ffio_wfourcc(pb, "hmhd");
2265 avio_wb32(pb, 0); /* version, flags */
2266 avio_wb16(pb, 0); /* maxPDUsize */
2267 avio_wb16(pb, 0); /* avgPDUsize */
2268 avio_wb32(pb, 0); /* maxbitrate */
2269 avio_wb32(pb, 0); /* avgbitrate */
2270 avio_wb32(pb, 0); /* reserved */
2274 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2276 int64_t pos = avio_tell(pb);
2279 avio_wb32(pb, 0); /* size */
2280 ffio_wfourcc(pb, "minf");
2281 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2282 mov_write_vmhd_tag(pb);
2283 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2284 mov_write_smhd_tag(pb);
2285 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2286 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2287 mov_write_gmhd_tag(pb, track);
2289 mov_write_nmhd_tag(pb);
2291 } else if (track->tag == MKTAG('r','t','p',' ')) {
2292 mov_write_hmhd_tag(pb);
2293 } else if (track->tag == MKTAG('t','m','c','d')) {
2294 if (track->mode == MODE_MP4)
2295 mov_write_nmhd_tag(pb);
2297 mov_write_gmhd_tag(pb, track);
2299 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2300 mov_write_hdlr_tag(s, pb, NULL);
2301 mov_write_dinf_tag(pb);
2302 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2304 return update_size(pb, pos);
2307 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2310 int version = track->track_duration < INT32_MAX ? 0 : 1;
2312 if (track->mode == MODE_ISM)
2315 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2316 ffio_wfourcc(pb, "mdhd");
2317 avio_w8(pb, version);
2318 avio_wb24(pb, 0); /* flags */
2320 avio_wb64(pb, track->time);
2321 avio_wb64(pb, track->time);
2323 avio_wb32(pb, track->time); /* creation time */
2324 avio_wb32(pb, track->time); /* modification time */
2326 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2327 if (!track->entry && mov->mode == MODE_ISM)
2328 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2329 else if (!track->entry)
2330 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2332 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2333 avio_wb16(pb, track->language); /* language */
2334 avio_wb16(pb, 0); /* reserved (quality) */
2336 if (version != 0 && track->mode == MODE_MOV) {
2337 av_log(NULL, AV_LOG_ERROR,
2338 "FATAL error, file duration too long for timebase, this file will not be\n"
2339 "playable with quicktime. Choose a different timebase or a different\n"
2340 "container format\n");
2346 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2347 MOVMuxContext *mov, MOVTrack *track)
2349 int64_t pos = avio_tell(pb);
2352 avio_wb32(pb, 0); /* size */
2353 ffio_wfourcc(pb, "mdia");
2354 mov_write_mdhd_tag(pb, mov, track);
2355 mov_write_hdlr_tag(s, pb, track);
2356 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2358 return update_size(pb, pos);
2361 /* transformation matrix
2365 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2366 int16_t d, int16_t tx, int16_t ty)
2368 avio_wb32(pb, a << 16); /* 16.16 format */
2369 avio_wb32(pb, b << 16); /* 16.16 format */
2370 avio_wb32(pb, 0); /* u in 2.30 format */
2371 avio_wb32(pb, c << 16); /* 16.16 format */
2372 avio_wb32(pb, d << 16); /* 16.16 format */
2373 avio_wb32(pb, 0); /* v in 2.30 format */
2374 avio_wb32(pb, tx << 16); /* 16.16 format */
2375 avio_wb32(pb, ty << 16); /* 16.16 format */
2376 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2379 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2380 MOVTrack *track, AVStream *st)
2382 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2383 track->timescale, AV_ROUND_UP);
2384 int version = duration < INT32_MAX ? 0 : 1;
2385 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2389 uint32_t *display_matrix = NULL;
2390 int display_matrix_size, i;
2393 if (mov->per_stream_grouping)
2396 group = st->codecpar->codec_type;
2398 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2399 &display_matrix_size);
2400 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2401 display_matrix = NULL;
2404 if (track->flags & MOV_TRACK_ENABLED)
2405 flags |= MOV_TKHD_FLAG_ENABLED;
2407 if (track->mode == MODE_ISM)
2410 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2411 ffio_wfourcc(pb, "tkhd");
2412 avio_w8(pb, version);
2413 avio_wb24(pb, flags);
2415 avio_wb64(pb, track->time);
2416 avio_wb64(pb, track->time);
2418 avio_wb32(pb, track->time); /* creation time */
2419 avio_wb32(pb, track->time); /* modification time */
2421 avio_wb32(pb, track->track_id); /* track-id */
2422 avio_wb32(pb, 0); /* reserved */
2423 if (!track->entry && mov->mode == MODE_ISM)
2424 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2425 else if (!track->entry)
2426 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2428 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2430 avio_wb32(pb, 0); /* reserved */
2431 avio_wb32(pb, 0); /* reserved */
2432 avio_wb16(pb, 0); /* layer */
2433 avio_wb16(pb, group); /* alternate group) */
2434 /* Volume, only for audio */
2435 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2436 avio_wb16(pb, 0x0100);
2439 avio_wb16(pb, 0); /* reserved */
2441 /* Matrix structure */
2442 if (st && st->metadata) {
2443 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2444 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2446 if (display_matrix) {
2447 for (i = 0; i < 9; i++)
2448 avio_wb32(pb, display_matrix[i]);
2449 } else if (rotation == 90) {
2450 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2451 } else if (rotation == 180) {
2452 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2453 } else if (rotation == 270) {
2454 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2456 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2458 /* Track width and height, for visual only */
2459 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2460 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2461 int64_t track_width_1616;
2462 if (track->mode == MODE_MOV) {
2463 track_width_1616 = track->par->width * 0x10000ULL;
2465 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2466 track->par->width * 0x10000LL,
2467 st->sample_aspect_ratio.den);
2468 if (!track_width_1616 ||
2469 track->height != track->par->height ||
2470 track_width_1616 > UINT32_MAX)
2471 track_width_1616 = track->par->width * 0x10000ULL;
2473 if (track_width_1616 > UINT32_MAX) {
2474 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2475 track_width_1616 = 0;
2477 avio_wb32(pb, track_width_1616);
2478 if (track->height > 0xFFFF) {
2479 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2482 avio_wb32(pb, track->height * 0x10000U);
2490 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2492 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2493 track->par->sample_aspect_ratio.den);
2495 int64_t pos = avio_tell(pb);
2497 avio_wb32(pb, 0); /* size */
2498 ffio_wfourcc(pb, "tapt");
2501 ffio_wfourcc(pb, "clef");
2503 avio_wb32(pb, width << 16);
2504 avio_wb32(pb, track->par->height << 16);
2507 ffio_wfourcc(pb, "prof");
2509 avio_wb32(pb, width << 16);
2510 avio_wb32(pb, track->par->height << 16);
2513 ffio_wfourcc(pb, "enof");
2515 avio_wb32(pb, track->par->width << 16);
2516 avio_wb32(pb, track->par->height << 16);
2518 return update_size(pb, pos);
2521 // This box seems important for the psp playback ... without it the movie seems to hang
2522 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2525 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2526 track->timescale, AV_ROUND_UP);
2527 int version = duration < INT32_MAX ? 0 : 1;
2528 int entry_size, entry_count, size;
2529 int64_t delay, start_ct = track->start_cts;
2530 int64_t start_dts = track->start_dts;
2533 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2535 av_log(mov->fc, AV_LOG_DEBUG,
2536 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2537 track->cluster[0].dts, track->cluster[0].cts,
2538 start_dts, start_ct, track->track_id);
2539 start_dts = track->cluster[0].dts;
2540 start_ct = track->cluster[0].cts;
2544 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2545 track->timescale, AV_ROUND_DOWN);
2546 version |= delay < INT32_MAX ? 0 : 1;
2548 entry_size = (version == 1) ? 20 : 12;
2549 entry_count = 1 + (delay > 0);
2550 size = 24 + entry_count * entry_size;
2552 /* write the atom data */
2553 avio_wb32(pb, size);
2554 ffio_wfourcc(pb, "edts");
2555 avio_wb32(pb, size - 8);
2556 ffio_wfourcc(pb, "elst");
2557 avio_w8(pb, version);
2558 avio_wb24(pb, 0); /* flags */
2560 avio_wb32(pb, entry_count);
2561 if (delay > 0) { /* add an empty edit to delay presentation */
2562 /* In the positive delay case, the delay includes the cts
2563 * offset, and the second edit list entry below trims out
2564 * the same amount from the actual content. This makes sure
2565 * that the offset last sample is included in the edit
2566 * list duration as well. */
2568 avio_wb64(pb, delay);
2571 avio_wb32(pb, delay);
2574 avio_wb32(pb, 0x00010000);
2576 /* Avoid accidentally ending up with start_ct = -1 which has got a
2577 * special meaning. Normally start_ct should end up positive or zero
2578 * here, but use FFMIN in case dts is a small positive integer
2579 * rounded to 0 when represented in MOV_TIMESCALE units. */
2580 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2581 start_ct = -FFMIN(start_dts, 0);
2582 /* Note, this delay is calculated from the pts of the first sample,
2583 * ensuring that we don't reduce the duration for cases with
2588 /* For fragmented files, we don't know the full length yet. Setting
2589 * duration to 0 allows us to only specify the offset, including
2590 * the rest of the content (from all future fragments) without specifying
2591 * an explicit duration. */
2592 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2597 avio_wb64(pb, duration);
2598 avio_wb64(pb, start_ct);
2600 avio_wb32(pb, duration);
2601 avio_wb32(pb, start_ct);
2603 avio_wb32(pb, 0x00010000);
2607 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2609 avio_wb32(pb, 20); // size
2610 ffio_wfourcc(pb, "tref");
2611 avio_wb32(pb, 12); // size (subatom)
2612 avio_wl32(pb, track->tref_tag);
2613 avio_wb32(pb, track->tref_id);
2617 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2618 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2620 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2621 ffio_wfourcc(pb, "uuid");
2622 ffio_wfourcc(pb, "USMT");
2623 avio_wb32(pb, 0x21d24fce);
2624 avio_wb32(pb, 0xbb88695c);
2625 avio_wb32(pb, 0xfac9c740);
2626 avio_wb32(pb, 0x1c); // another size here!
2627 ffio_wfourcc(pb, "MTDT");
2628 avio_wb32(pb, 0x00010012);
2629 avio_wb32(pb, 0x0a);
2630 avio_wb32(pb, 0x55c40000);
2636 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2638 AVFormatContext *ctx = track->rtp_ctx;
2639 char buf[1000] = "";
2642 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2643 NULL, NULL, 0, 0, ctx);
2644 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2647 avio_wb32(pb, len + 24);
2648 ffio_wfourcc(pb, "udta");
2649 avio_wb32(pb, len + 16);
2650 ffio_wfourcc(pb, "hnti");
2651 avio_wb32(pb, len + 8);
2652 ffio_wfourcc(pb, "sdp ");
2653 avio_write(pb, buf, len);
2657 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2658 const char *tag, const char *str)
2660 int64_t pos = avio_tell(pb);
2661 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2662 if (!t || !utf8len(t->value))
2665 avio_wb32(pb, 0); /* size */
2666 ffio_wfourcc(pb, tag); /* type */
2667 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2668 return update_size(pb, pos);
2671 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2674 AVIOContext *pb_buf;
2681 ret = avio_open_dyn_buf(&pb_buf);
2685 if (mov->mode & MODE_MP4)
2686 mov_write_track_metadata(pb_buf, st, "name", "title");
2688 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2689 avio_wb32(pb, size + 8);
2690 ffio_wfourcc(pb, "udta");
2691 avio_write(pb, buf, size);
2698 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2699 MOVTrack *track, AVStream *st)
2701 int64_t pos = avio_tell(pb);
2702 int entry_backup = track->entry;
2703 int chunk_backup = track->chunkCount;
2706 /* If we want to have an empty moov, but some samples already have been
2707 * buffered (delay_moov), pretend that no samples have been written yet. */
2708 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2709 track->chunkCount = track->entry = 0;
2711 avio_wb32(pb, 0); /* size */
2712 ffio_wfourcc(pb, "trak");
2713 mov_write_tkhd_tag(pb, mov, track, st);
2715 av_assert2(mov->use_editlist >= 0);
2717 if (track->start_dts != AV_NOPTS_VALUE) {
2718 if (mov->use_editlist)
2719 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2720 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2721 av_log(mov->fc, AV_LOG_WARNING,
2722 "Not writing any edit list even though one would have been required\n");
2725 if (track->tref_tag)
2726 mov_write_tref_tag(pb, track);
2728 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
2730 if (track->mode == MODE_PSP)
2731 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2732 if (track->tag == MKTAG('r','t','p',' '))
2733 mov_write_udta_sdp(pb, track);
2734 if (track->mode == MODE_MOV) {
2735 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2736 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2737 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2738 mov_write_tapt_tag(pb, track);
2741 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2742 mov_write_tapt_tag(pb, track);
2745 mov_write_track_udta_tag(pb, mov, st);
2746 track->entry = entry_backup;
2747 track->chunkCount = chunk_backup;
2748 return update_size(pb, pos);
2751 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2753 int i, has_audio = 0, has_video = 0;
2754 int64_t pos = avio_tell(pb);
2755 int audio_profile = mov->iods_audio_profile;
2756 int video_profile = mov->iods_video_profile;
2757 for (i = 0; i < mov->nb_streams; i++) {
2758 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2759 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
2760 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
2763 if (audio_profile < 0)
2764 audio_profile = 0xFF - has_audio;
2765 if (video_profile < 0)
2766 video_profile = 0xFF - has_video;
2767 avio_wb32(pb, 0x0); /* size */
2768 ffio_wfourcc(pb, "iods");
2769 avio_wb32(pb, 0); /* version & flags */
2770 put_descr(pb, 0x10, 7);
2771 avio_wb16(pb, 0x004f);
2774 avio_w8(pb, audio_profile);
2775 avio_w8(pb, video_profile);
2777 return update_size(pb, pos);
2780 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2782 avio_wb32(pb, 0x20); /* size */
2783 ffio_wfourcc(pb, "trex");
2784 avio_wb32(pb, 0); /* version & flags */
2785 avio_wb32(pb, track->track_id); /* track ID */
2786 avio_wb32(pb, 1); /* default sample description index */
2787 avio_wb32(pb, 0); /* default sample duration */
2788 avio_wb32(pb, 0); /* default sample size */
2789 avio_wb32(pb, 0); /* default sample flags */
2793 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2795 int64_t pos = avio_tell(pb);
2797 avio_wb32(pb, 0x0); /* size */
2798 ffio_wfourcc(pb, "mvex");
2799 for (i = 0; i < mov->nb_streams; i++)
2800 mov_write_trex_tag(pb, &mov->tracks[i]);
2801 return update_size(pb, pos);
2804 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2806 int max_track_id = 1, i;
2807 int64_t max_track_len = 0;
2810 for (i = 0; i < mov->nb_streams; i++) {
2811 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2812 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2814 mov->tracks[i].timescale,
2816 if (max_track_len < max_track_len_temp)
2817 max_track_len = max_track_len_temp;
2818 if (max_track_id < mov->tracks[i].track_id)
2819 max_track_id = mov->tracks[i].track_id;
2822 /* If using delay_moov, make sure the output is the same as if no
2823 * samples had been written yet. */
2824 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2829 version = max_track_len < UINT32_MAX ? 0 : 1;
2830 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
2832 ffio_wfourcc(pb, "mvhd");
2833 avio_w8(pb, version);
2834 avio_wb24(pb, 0); /* flags */
2836 avio_wb64(pb, mov->time);
2837 avio_wb64(pb, mov->time);
2839 avio_wb32(pb, mov->time); /* creation time */
2840 avio_wb32(pb, mov->time); /* modification time */
2842 avio_wb32(pb, MOV_TIMESCALE);
2843 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2845 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2846 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2847 avio_wb16(pb, 0); /* reserved */
2848 avio_wb32(pb, 0); /* reserved */
2849 avio_wb32(pb, 0); /* reserved */
2851 /* Matrix structure */
2852 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2854 avio_wb32(pb, 0); /* reserved (preview time) */
2855 avio_wb32(pb, 0); /* reserved (preview duration) */
2856 avio_wb32(pb, 0); /* reserved (poster time) */
2857 avio_wb32(pb, 0); /* reserved (selection time) */
2858 avio_wb32(pb, 0); /* reserved (selection duration) */
2859 avio_wb32(pb, 0); /* reserved (current time) */
2860 avio_wb32(pb, max_track_id + 1); /* Next track id */
2864 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2867 avio_wb32(pb, 33); /* size */
2868 ffio_wfourcc(pb, "hdlr");
2871 ffio_wfourcc(pb, "mdir");
2872 ffio_wfourcc(pb, "appl");
2879 /* helper function to write a data tag with the specified string as data */
2880 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2883 int size = 16 + strlen(data);
2884 avio_wb32(pb, size); /* size */
2885 ffio_wfourcc(pb, "data");
2888 avio_write(pb, data, strlen(data));
2892 lang = ff_mov_iso639_to_lang("und", 1);
2893 avio_wb16(pb, strlen(data)); /* string length */
2894 avio_wb16(pb, lang);
2895 avio_write(pb, data, strlen(data));
2896 return strlen(data) + 4;
2900 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2901 const char *value, int lang, int long_style)
2904 if (value && value[0]) {
2905 int64_t pos = avio_tell(pb);
2906 avio_wb32(pb, 0); /* size */
2907 ffio_wfourcc(pb, name);
2908 mov_write_string_data_tag(pb, value, lang, long_style);
2909 size = update_size(pb, pos);
2914 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
2915 const char *tag, int *lang)
2918 AVDictionaryEntry *t, *t2 = NULL;
2923 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2926 len = strlen(t->key);
2927 snprintf(tag2, sizeof(tag2), "%s-", tag);
2928 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2929 len2 = strlen(t2->key);
2930 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2931 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2939 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2940 const char *name, const char *tag,
2944 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
2947 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2950 /* iTunes bpm number */
2951 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2953 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2954 int size = 0, tmpo = t ? atoi(t->value) : 0;
2957 avio_wb32(pb, size);
2958 ffio_wfourcc(pb, "tmpo");
2959 avio_wb32(pb, size-8); /* size */
2960 ffio_wfourcc(pb, "data");
2961 avio_wb32(pb, 0x15); //type specifier
2963 avio_wb16(pb, tmpo); // data
2968 /* 3GPP TS 26.244 */
2969 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
2972 int64_t pos = avio_tell(pb);
2973 double latitude, longitude, altitude;
2974 int32_t latitude_fix, longitude_fix, altitude_fix;
2975 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
2976 const char *ptr, *place = "";
2978 static const char *astronomical_body = "earth";
2983 longitude = strtod(ptr, &end);
2985 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
2989 latitude = strtod(ptr, &end);
2991 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
2995 altitude = strtod(ptr, &end);
2996 /* If no altitude was present, the default 0 should be fine */
3000 latitude_fix = (int32_t) ((1 << 16) * latitude);
3001 longitude_fix = (int32_t) ((1 << 16) * longitude);
3002 altitude_fix = (int32_t) ((1 << 16) * altitude);
3004 avio_wb32(pb, 0); /* size */
3005 ffio_wfourcc(pb, "loci"); /* type */
3006 avio_wb32(pb, 0); /* version + flags */
3007 avio_wb16(pb, lang);
3008 avio_write(pb, place, strlen(place) + 1);
3009 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3010 avio_wb32(pb, latitude_fix);
3011 avio_wb32(pb, longitude_fix);
3012 avio_wb32(pb, altitude_fix);
3013 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3014 avio_w8(pb, 0); /* additional notes, null terminated string */
3016 return update_size(pb, pos);
3019 /* iTunes track or disc number */
3020 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3021 AVFormatContext *s, int disc)
3023 AVDictionaryEntry *t = av_dict_get(s->metadata,
3024 disc ? "disc" : "track",
3026 int size = 0, track = t ? atoi(t->value) : 0;
3029 char *slash = strchr(t->value, '/');
3031 tracks = atoi(slash + 1);
3032 avio_wb32(pb, 32); /* size */
3033 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3034 avio_wb32(pb, 24); /* size */
3035 ffio_wfourcc(pb, "data");
3036 avio_wb32(pb, 0); // 8 bytes empty
3038 avio_wb16(pb, 0); // empty
3039 avio_wb16(pb, track); // track / disc number
3040 avio_wb16(pb, tracks); // total track / disc number
3041 avio_wb16(pb, 0); // empty
3047 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3048 const char *name, const char *tag,
3051 AVDictionaryEntry *t = NULL;
3053 int size = 24 + len;
3055 if (len != 1 && len != 4)
3058 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3060 num = atoi(t->value);
3062 avio_wb32(pb, size);
3063 ffio_wfourcc(pb, name);
3064 avio_wb32(pb, size - 8);
3065 ffio_wfourcc(pb, "data");
3066 avio_wb32(pb, 0x15);
3068 if (len==4) avio_wb32(pb, num);
3069 else avio_w8 (pb, num);
3074 /* iTunes meta data list */
3075 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3078 int64_t pos = avio_tell(pb);
3079 avio_wb32(pb, 0); /* size */
3080 ffio_wfourcc(pb, "ilst");
3081 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3082 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3083 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3084 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3085 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3086 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3087 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3088 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3089 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3091 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3092 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3093 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3094 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3095 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3096 mov_write_string_metadata(s, pb, "desc", "description",1);
3097 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3098 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3099 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3100 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3101 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3102 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3103 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3104 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3105 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3106 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3107 mov_write_trkn_tag(pb, mov, s, 0); // track number
3108 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3109 mov_write_tmpo_tag(pb, s);
3110 return update_size(pb, pos);
3113 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3116 avio_wb32(pb, 33); /* size */
3117 ffio_wfourcc(pb, "hdlr");
3120 ffio_wfourcc(pb, "mdta");
3128 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3131 AVDictionaryEntry *t = NULL;
3132 int64_t pos = avio_tell(pb);
3133 int64_t curpos, entry_pos;
3136 avio_wb32(pb, 0); /* size */
3137 ffio_wfourcc(pb, "keys");
3139 entry_pos = avio_tell(pb);
3140 avio_wb32(pb, 0); /* entry count */
3142 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3143 avio_wb32(pb, strlen(t->key) + 8);
3144 ffio_wfourcc(pb, "mdta");
3145 avio_write(pb, t->key, strlen(t->key));
3148 curpos = avio_tell(pb);
3149 avio_seek(pb, entry_pos, SEEK_SET);
3150 avio_wb32(pb, count); // rewrite entry count
3151 avio_seek(pb, curpos, SEEK_SET);
3153 return update_size(pb, pos);
3156 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3159 AVDictionaryEntry *t = NULL;
3160 int64_t pos = avio_tell(pb);
3161 int count = 1; /* keys are 1-index based */
3163 avio_wb32(pb, 0); /* size */
3164 ffio_wfourcc(pb, "ilst");
3166 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3167 int64_t entry_pos = avio_tell(pb);
3168 avio_wb32(pb, 0); /* size */
3169 avio_wb32(pb, count); /* key */
3170 mov_write_string_data_tag(pb, t->value, 0, 1);
3171 update_size(pb, entry_pos);
3174 return update_size(pb, pos);
3177 /* meta data tags */
3178 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3182 int64_t pos = avio_tell(pb);
3183 avio_wb32(pb, 0); /* size */
3184 ffio_wfourcc(pb, "meta");
3186 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3187 mov_write_mdta_hdlr_tag(pb, mov, s);
3188 mov_write_mdta_keys_tag(pb, mov, s);
3189 mov_write_mdta_ilst_tag(pb, mov, s);
3192 /* iTunes metadata tag */
3193 mov_write_itunes_hdlr_tag(pb, mov, s);
3194 mov_write_ilst_tag(pb, mov, s);
3196 size = update_size(pb, pos);
3200 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3201 const char *name, const char *key)
3204 AVDictionaryEntry *t;
3206 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3209 len = strlen(t->value);
3212 avio_wb32(pb, size);
3213 ffio_wfourcc(pb, name);
3214 avio_write(pb, t->value, len);
3220 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3224 GET_UTF8(val, *b++, return -1;)
3227 avio_wb16(pb, 0x00);
3231 static uint16_t language_code(const char *str)
3233 return (((str[0] - 0x60) & 0x1F) << 10) +
3234 (((str[1] - 0x60) & 0x1F) << 5) +
3235 (( str[2] - 0x60) & 0x1F);
3238 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3239 const char *tag, const char *str)
3241 int64_t pos = avio_tell(pb);
3242 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3243 if (!t || !utf8len(t->value))
3245 avio_wb32(pb, 0); /* size */
3246 ffio_wfourcc(pb, tag); /* type */
3247 avio_wb32(pb, 0); /* version + flags */
3248 if (!strcmp(tag, "yrrc"))
3249 avio_wb16(pb, atoi(t->value));
3251 avio_wb16(pb, language_code("eng")); /* language */
3252 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3253 if (!strcmp(tag, "albm") &&
3254 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3255 avio_w8(pb, atoi(t->value));
3257 return update_size(pb, pos);
3260 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3262 int64_t pos = avio_tell(pb);
3263 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3265 avio_wb32(pb, 0); // size
3266 ffio_wfourcc(pb, "chpl");
3267 avio_wb32(pb, 0x01000000); // version + flags
3268 avio_wb32(pb, 0); // unknown
3269 avio_w8(pb, nb_chapters);
3271 for (i = 0; i < nb_chapters; i++) {
3272 AVChapter *c = s->chapters[i];
3273 AVDictionaryEntry *t;
3274 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3276 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3277 int len = FFMIN(strlen(t->value), 255);
3279 avio_write(pb, t->value, len);
3283 return update_size(pb, pos);
3286 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3289 AVIOContext *pb_buf;
3293 ret = avio_open_dyn_buf(&pb_buf);
3297 if (mov->mode & MODE_3GP) {
3298 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3299 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3300 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3301 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3302 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3303 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3304 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3305 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3306 mov_write_loci_tag(s, pb_buf);
3307 } 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
3308 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3309 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3310 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3311 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3312 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3313 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3314 // currently ignored by mov.c
3315 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3316 // add support for libquicktime, this atom is also actually read by mov.c
3317 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3318 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3319 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3320 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3321 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3322 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3323 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3325 /* iTunes meta data */
3326 mov_write_meta_tag(pb_buf, mov, s);
3327 mov_write_loci_tag(s, pb_buf);
3330 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3331 mov_write_chpl_tag(pb_buf, s);
3333 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3334 avio_wb32(pb, size + 8);
3335 ffio_wfourcc(pb, "udta");
3336 avio_write(pb, buf, size);
3343 static void mov_write_psp_udta_tag(AVIOContext *pb,
3344 const char *str, const char *lang, int type)
3346 int len = utf8len(str) + 1;
3349 avio_wb16(pb, len * 2 + 10); /* size */
3350 avio_wb32(pb, type); /* type */
3351 avio_wb16(pb, language_code(lang)); /* language */
3352 avio_wb16(pb, 0x01); /* ? */
3353 ascii_to_wc(pb, str);
3356 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3358 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3362 pos = avio_tell(pb);
3363 avio_wb32(pb, 0); /* size placeholder*/
3364 ffio_wfourcc(pb, "uuid");
3365 ffio_wfourcc(pb, "USMT");
3366 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3367 avio_wb32(pb, 0xbb88695c);
3368 avio_wb32(pb, 0xfac9c740);
3370 pos2 = avio_tell(pb);
3371 avio_wb32(pb, 0); /* size placeholder*/
3372 ffio_wfourcc(pb, "MTDT");
3376 avio_wb16(pb, 0x0C); /* size */
3377 avio_wb32(pb, 0x0B); /* type */
3378 avio_wb16(pb, language_code("und")); /* language */
3379 avio_wb16(pb, 0x0); /* ? */
3380 avio_wb16(pb, 0x021C); /* data */
3382 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3383 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3384 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3385 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3387 update_size(pb, pos2);
3388 return update_size(pb, pos);
3394 static void build_chunks(MOVTrack *trk)
3397 MOVIentry *chunk = &trk->cluster[0];
3398 uint64_t chunkSize = chunk->size;
3399 chunk->chunkNum = 1;
3400 if (trk->chunkCount)
3402 trk->chunkCount = 1;
3403 for (i = 1; i<trk->entry; i++){
3404 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3405 chunkSize + trk->cluster[i].size < (1<<20)){
3406 chunkSize += trk->cluster[i].size;
3407 chunk->samples_in_chunk += trk->cluster[i].entries;
3409 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3410 chunk=&trk->cluster[i];
3411 chunkSize = chunk->size;
3417 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3421 int64_t pos = avio_tell(pb);
3422 avio_wb32(pb, 0); /* size placeholder*/
3423 ffio_wfourcc(pb, "moov");
3425 for (i = 0; i < mov->nb_streams; i++) {
3426 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3429 mov->tracks[i].time = mov->time;
3430 mov->tracks[i].track_id = i + 1;
3432 if (mov->tracks[i].entry)
3433 build_chunks(&mov->tracks[i]);
3436 if (mov->chapter_track)
3437 for (i = 0; i < s->nb_streams; i++) {
3438 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3439 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3441 for (i = 0; i < mov->nb_streams; i++) {
3442 MOVTrack *track = &mov->tracks[i];
3443 if (track->tag == MKTAG('r','t','p',' ')) {
3444 track->tref_tag = MKTAG('h','i','n','t');
3445 track->tref_id = mov->tracks[track->src_track].track_id;
3446 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3447 int * fallback, size;
3448 fallback = (int*)av_stream_get_side_data(track->st,
3449 AV_PKT_DATA_FALLBACK_TRACK,
3451 if (fallback != NULL && size == sizeof(int)) {
3452 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3453 track->tref_tag = MKTAG('f','a','l','l');
3454 track->tref_id = mov->tracks[*fallback].track_id;
3459 for (i = 0; i < mov->nb_streams; i++) {
3460 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3461 int src_trk = mov->tracks[i].src_track;
3462 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3463 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3464 //src_trk may have a different timescale than the tmcd track
3465 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3466 mov->tracks[i].timescale,
3467 mov->tracks[src_trk].timescale);
3471 mov_write_mvhd_tag(pb, mov);
3472 if (mov->mode != MODE_MOV && !mov->iods_skip)
3473 mov_write_iods_tag(pb, mov);
3474 for (i = 0; i < mov->nb_streams; i++) {
3475 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3476 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3481 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3482 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3484 if (mov->mode == MODE_PSP)
3485 mov_write_uuidusmt_tag(pb, s);
3487 mov_write_udta_tag(pb, mov, s);
3489 return update_size(pb, pos);
3492 static void param_write_int(AVIOContext *pb, const char *name, int value)
3494 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3497 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3499 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3502 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3505 len = FFMIN(sizeof(buf) / 2 - 1, len);
3506 ff_data_to_hex(buf, value, len, 0);
3507 buf[2 * len] = '\0';
3508 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3511 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
3513 int64_t pos = avio_tell(pb);
3515 static const uint8_t uuid[] = {
3516 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3517 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3521 ffio_wfourcc(pb, "uuid");
3522 avio_write(pb, uuid, sizeof(uuid));
3525 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3526 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3527 avio_printf(pb, "<head>\n");
3528 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3529 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3531 avio_printf(pb, "</head>\n");
3532 avio_printf(pb, "<body>\n");
3533 avio_printf(pb, "<switch>\n");
3534 for (i = 0; i < mov->nb_streams; i++) {
3535 MOVTrack *track = &mov->tracks[i];
3537 /* track->track_id is initialized in write_moov, and thus isn't known
3539 int track_id = i + 1;
3541 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3543 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3548 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3549 (int64_t)track->par->bit_rate);
3550 param_write_int(pb, "systemBitrate", track->par->bit_rate);
3551 param_write_int(pb, "trackID", track_id);
3552 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3553 if (track->par->codec_id == AV_CODEC_ID_H264) {
3555 int size = track->par->extradata_size;
3556 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3558 param_write_hex(pb, "CodecPrivateData",
3559 ptr ? ptr : track->par->extradata,
3563 param_write_string(pb, "FourCC", "H264");
3564 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3565 param_write_string(pb, "FourCC", "WVC1");
3566 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3567 track->par->extradata_size);
3569 param_write_int(pb, "MaxWidth", track->par->width);
3570 param_write_int(pb, "MaxHeight", track->par->height);
3571 param_write_int(pb, "DisplayWidth", track->par->width);
3572 param_write_int(pb, "DisplayHeight", track->par->height);
3574 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3575 switch (track->par->profile)
3577 case FF_PROFILE_AAC_HE_V2:
3578 param_write_string(pb, "FourCC", "AACP");
3580 case FF_PROFILE_AAC_HE:
3581 param_write_string(pb, "FourCC", "AACH");
3584 param_write_string(pb, "FourCC", "AACL");
3586 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3587 param_write_string(pb, "FourCC", "WMAP");
3589 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3590 track->par->extradata_size);
3591 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3592 track->par->codec_id));
3593 param_write_int(pb, "Channels", track->par->channels);
3594 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3595 param_write_int(pb, "BitsPerSample", 16);
3596 param_write_int(pb, "PacketSize", track->par->block_align ?
3597 track->par->block_align : 4);
3599 avio_printf(pb, "</%s>\n", type);
3601 avio_printf(pb, "</switch>\n");
3602 avio_printf(pb, "</body>\n");
3603 avio_printf(pb, "</smil>\n");
3605 return update_size(pb, pos);
3608 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3611 ffio_wfourcc(pb, "mfhd");
3613 avio_wb32(pb, mov->fragments);
3617 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3619 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3620 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3623 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3624 MOVTrack *track, int64_t moof_offset)
3626 int64_t pos = avio_tell(pb);
3627 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3628 MOV_TFHD_BASE_DATA_OFFSET;
3629 if (!track->entry) {
3630 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3632 flags |= MOV_TFHD_DEFAULT_FLAGS;
3634 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3635 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3636 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3637 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3638 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3641 /* Don't set a default sample size, the silverlight player refuses
3642 * to play files with that set. Don't set a default sample duration,
3643 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3644 * file format says it MUST NOT be set. */
3645 if (track->mode == MODE_ISM)
3646 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3647 MOV_TFHD_BASE_DATA_OFFSET);
3649 avio_wb32(pb, 0); /* size placeholder */
3650 ffio_wfourcc(pb, "tfhd");
3651 avio_w8(pb, 0); /* version */
3652 avio_wb24(pb, flags);
3654 avio_wb32(pb, track->track_id); /* track-id */
3655 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3656 avio_wb64(pb, moof_offset);
3657 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3658 track->default_duration = get_cluster_duration(track, 0);
3659 avio_wb32(pb, track->default_duration);
3661 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3662 track->default_size = track->entry ? track->cluster[0].size : 1;
3663 avio_wb32(pb, track->default_size);
3665 track->default_size = -1;
3667 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3668 /* Set the default flags based on the second sample, if available.
3669 * If the first sample is different, that can be signaled via a separate field. */
3670 if (track->entry > 1)
3671 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
3673 track->default_sample_flags =
3674 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
3675 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3676 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3677 avio_wb32(pb, track->default_sample_flags);
3680 return update_size(pb, pos);
3683 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3684 MOVTrack *track, int moof_size,
3687 int64_t pos = avio_tell(pb);
3688 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3691 for (i = first; i < end; i++) {
3692 if (get_cluster_duration(track, i) != track->default_duration)
3693 flags |= MOV_TRUN_SAMPLE_DURATION;
3694 if (track->cluster[i].size != track->default_size)
3695 flags |= MOV_TRUN_SAMPLE_SIZE;
3696 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3697 flags |= MOV_TRUN_SAMPLE_FLAGS;
3699 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
3700 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
3701 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3702 if (track->flags & MOV_TRACK_CTTS)
3703 flags |= MOV_TRUN_SAMPLE_CTS;
3705 avio_wb32(pb, 0); /* size placeholder */
3706 ffio_wfourcc(pb, "trun");
3707 avio_w8(pb, 0); /* version */
3708 avio_wb24(pb, flags);
3710 avio_wb32(pb, end - first); /* sample count */
3711 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3712 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3714 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3716 avio_wb32(pb, moof_size + 8 + track->data_offset +
3717 track->cluster[first].pos); /* data offset */
3718 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3719 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
3721 for (i = first; i < end; i++) {
3722 if (flags & MOV_TRUN_SAMPLE_DURATION)
3723 avio_wb32(pb, get_cluster_duration(track, i));
3724 if (flags & MOV_TRUN_SAMPLE_SIZE)
3725 avio_wb32(pb, track->cluster[i].size);
3726 if (flags & MOV_TRUN_SAMPLE_FLAGS)
3727 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3728 if (flags & MOV_TRUN_SAMPLE_CTS)
3729 avio_wb32(pb, track->cluster[i].cts);
3732 mov->first_trun = 0;
3733 return update_size(pb, pos);
3736 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3738 int64_t pos = avio_tell(pb);
3739 static const uint8_t uuid[] = {
3740 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3741 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3744 avio_wb32(pb, 0); /* size placeholder */
3745 ffio_wfourcc(pb, "uuid");
3746 avio_write(pb, uuid, sizeof(uuid));
3749 avio_wb64(pb, track->start_dts + track->frag_start +
3750 track->cluster[0].cts);
3751 avio_wb64(pb, track->end_pts -
3752 (track->cluster[0].dts + track->cluster[0].cts));
3754 return update_size(pb, pos);
3757 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3758 MOVTrack *track, int entry)
3760 int n = track->nb_frag_info - 1 - entry, i;
3761 int size = 8 + 16 + 4 + 1 + 16*n;
3762 static const uint8_t uuid[] = {
3763 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3764 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3770 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3771 avio_wb32(pb, size);
3772 ffio_wfourcc(pb, "uuid");
3773 avio_write(pb, uuid, sizeof(uuid));
3777 for (i = 0; i < n; i++) {
3778 int index = entry + 1 + i;
3779 avio_wb64(pb, track->frag_info[index].time);
3780 avio_wb64(pb, track->frag_info[index].duration);
3782 if (n < mov->ism_lookahead) {
3783 int free_size = 16 * (mov->ism_lookahead - n);
3784 avio_wb32(pb, free_size);
3785 ffio_wfourcc(pb, "free");
3786 ffio_fill(pb, 0, free_size - 8);
3792 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3795 int64_t pos = avio_tell(pb);
3797 for (i = 0; i < mov->ism_lookahead; i++) {
3798 /* Update the tfrf tag for the last ism_lookahead fragments,
3799 * nb_frag_info - 1 is the next fragment to be written. */
3800 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3802 avio_seek(pb, pos, SEEK_SET);
3806 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3810 for (i = 0; i < mov->nb_streams; i++) {
3811 MOVTrack *track = &mov->tracks[i];
3812 MOVFragmentInfo *info;
3813 if ((tracks >= 0 && i != tracks) || !track->entry)
3815 track->nb_frag_info++;
3816 if (track->nb_frag_info >= track->frag_info_capacity) {
3817 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3818 if (av_reallocp_array(&track->frag_info,
3820 sizeof(*track->frag_info)))
3821 return AVERROR(ENOMEM);
3822 track->frag_info_capacity = new_capacity;
3824 info = &track->frag_info[track->nb_frag_info - 1];
3825 info->offset = avio_tell(pb);
3827 // Try to recreate the original pts for the first packet
3828 // from the fields we have stored
3829 info->time = track->start_dts + track->frag_start +
3830 track->cluster[0].cts;
3831 info->duration = track->end_pts -
3832 (track->cluster[0].dts + track->cluster[0].cts);
3833 // If the pts is less than zero, we will have trimmed
3834 // away parts of the media track using an edit list,
3835 // and the corresponding start presentation time is zero.
3836 if (info->time < 0) {
3837 info->duration += info->time;
3840 info->tfrf_offset = 0;
3841 mov_write_tfrf_tags(pb, mov, track);
3846 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3848 int64_t pos = avio_tell(pb);
3850 avio_wb32(pb, 0); /* size */
3851 ffio_wfourcc(pb, "tfdt");
3852 avio_w8(pb, 1); /* version */
3854 avio_wb64(pb, track->frag_start);
3855 return update_size(pb, pos);
3858 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3859 MOVTrack *track, int64_t moof_offset,
3862 int64_t pos = avio_tell(pb);
3864 avio_wb32(pb, 0); /* size placeholder */
3865 ffio_wfourcc(pb, "traf");
3867 mov_write_tfhd_tag(pb, mov, track, moof_offset);
3868 if (mov->mode != MODE_ISM)
3869 mov_write_tfdt_tag(pb, track);
3870 for (i = 1; i < track->entry; i++) {
3871 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
3872 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
3876 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
3877 if (mov->mode == MODE_ISM) {
3878 mov_write_tfxd_tag(pb, track);
3880 if (mov->ism_lookahead) {
3881 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3883 if (track->nb_frag_info > 0) {
3884 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3885 if (!info->tfrf_offset)
3886 info->tfrf_offset = avio_tell(pb);
3888 avio_wb32(pb, 8 + size);
3889 ffio_wfourcc(pb, "free");
3890 for (i = 0; i < size; i++)
3895 return update_size(pb, pos);
3898 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3899 int tracks, int moof_size)
3901 int64_t pos = avio_tell(pb);
3904 avio_wb32(pb, 0); /* size placeholder */
3905 ffio_wfourcc(pb, "moof");
3906 mov->first_trun = 1;
3908 mov_write_mfhd_tag(pb, mov);
3909 for (i = 0; i < mov->nb_streams; i++) {
3910 MOVTrack *track = &mov->tracks[i];
3911 if (tracks >= 0 && i != tracks)
3915 mov_write_traf_tag(pb, mov, track, pos, moof_size);
3918 return update_size(pb, pos);
3921 static int mov_write_sidx_tag(AVIOContext *pb,
3922 MOVTrack *track, int ref_size, int total_sidx_size)
3924 int64_t pos = avio_tell(pb), offset_pos, end_pos;
3925 int64_t presentation_time, duration, offset;
3926 int starts_with_SAP, i, entries;
3930 presentation_time = track->start_dts + track->frag_start +
3931 track->cluster[0].cts;
3932 duration = track->end_pts -
3933 (track->cluster[0].dts + track->cluster[0].cts);
3934 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
3936 // pts<0 should be cut away using edts
3937 if (presentation_time < 0) {
3938 duration += presentation_time;
3939 presentation_time = 0;
3942 entries = track->nb_frag_info;
3945 presentation_time = track->frag_info[0].time;
3948 avio_wb32(pb, 0); /* size */
3949 ffio_wfourcc(pb, "sidx");
3950 avio_w8(pb, 1); /* version */
3952 avio_wb32(pb, track->track_id); /* reference_ID */
3953 avio_wb32(pb, track->timescale); /* timescale */
3954 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
3955 offset_pos = avio_tell(pb);
3956 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
3957 avio_wb16(pb, 0); /* reserved */
3959 avio_wb16(pb, entries); /* reference_count */
3960 for (i = 0; i < entries; i++) {
3961 if (!track->entry) {
3962 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
3963 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
3965 duration = track->frag_info[i].duration;
3966 ref_size = track->frag_info[i].size;
3967 starts_with_SAP = 1;
3969 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
3970 avio_wb32(pb, duration); /* subsegment_duration */
3971 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
3974 end_pos = avio_tell(pb);
3975 offset = pos + total_sidx_size - end_pos;
3976 avio_seek(pb, offset_pos, SEEK_SET);
3977 avio_wb64(pb, offset);
3978 avio_seek(pb, end_pos, SEEK_SET);
3979 return update_size(pb, pos);
3982 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
3983 int tracks, int ref_size)
3986 AVIOContext *avio_buf;
3988 for (round = 0; round < 2; round++) {
3989 // First run one round to calculate the total size of all
3991 // This would be much simpler if we'd only write one sidx
3992 // atom, for the first track in the moof.
3994 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3999 for (i = 0; i < mov->nb_streams; i++) {
4000 MOVTrack *track = &mov->tracks[i];
4001 if (tracks >= 0 && i != tracks)
4003 // When writing a sidx for the full file, entry is 0, but
4004 // we want to include all tracks. ref_size is 0 in this case,
4005 // since we read it from frag_info instead.
4006 if (!track->entry && ref_size > 0)
4008 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4012 total_size = ffio_close_null_buf(avio_buf);
4017 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4020 AVIOContext *avio_buf;
4023 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4025 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4026 moof_size = ffio_close_null_buf(avio_buf);
4028 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4029 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4031 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4034 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4037 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4039 int64_t pos = avio_tell(pb);
4042 avio_wb32(pb, 0); /* size placeholder */
4043 ffio_wfourcc(pb, "tfra");
4044 avio_w8(pb, 1); /* version */
4047 avio_wb32(pb, track->track_id);
4048 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4049 avio_wb32(pb, track->nb_frag_info);
4050 for (i = 0; i < track->nb_frag_info; i++) {
4051 avio_wb64(pb, track->frag_info[i].time);
4052 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4053 avio_w8(pb, 1); /* traf number */
4054 avio_w8(pb, 1); /* trun number */
4055 avio_w8(pb, 1); /* sample number */
4058 return update_size(pb, pos);
4061 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4063 int64_t pos = avio_tell(pb);
4066 avio_wb32(pb, 0); /* size placeholder */
4067 ffio_wfourcc(pb, "mfra");
4068 /* An empty mfra atom is enough to indicate to the publishing point that
4069 * the stream has ended. */
4070 if (mov->flags & FF_MOV_FLAG_ISML)
4071 return update_size(pb, pos);
4073 for (i = 0; i < mov->nb_streams; i++) {
4074 MOVTrack *track = &mov->tracks[i];
4075 if (track->nb_frag_info)
4076 mov_write_tfra_tag(pb, track);
4080 ffio_wfourcc(pb, "mfro");
4081 avio_wb32(pb, 0); /* version + flags */
4082 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4084 return update_size(pb, pos);
4087 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4089 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4090 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4092 mov->mdat_pos = avio_tell(pb);
4093 avio_wb32(pb, 0); /* size placeholder*/
4094 ffio_wfourcc(pb, "mdat");
4098 /* TODO: This needs to be more general */
4099 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4101 MOVMuxContext *mov = s->priv_data;
4102 int64_t pos = avio_tell(pb);
4103 int has_h264 = 0, has_video = 0;
4107 for (i = 0; i < s->nb_streams; i++) {
4108 AVStream *st = s->streams[i];
4109 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4111 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4115 avio_wb32(pb, 0); /* size */
4116 ffio_wfourcc(pb, "ftyp");
4118 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4119 ffio_wfourcc(pb, mov->major_brand);
4120 else if (mov->mode == MODE_3GP) {
4121 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4122 minor = has_h264 ? 0x100 : 0x200;
4123 } else if (mov->mode & MODE_3G2) {
4124 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4125 minor = has_h264 ? 0x20000 : 0x10000;
4126 } else if (mov->mode == MODE_PSP)
4127 ffio_wfourcc(pb, "MSNV");
4128 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4129 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4130 else if (mov->mode == MODE_MP4)
4131 ffio_wfourcc(pb, "isom");
4132 else if (mov->mode == MODE_IPOD)
4133 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4134 else if (mov->mode == MODE_ISM)
4135 ffio_wfourcc(pb, "isml");
4136 else if (mov->mode == MODE_F4V)
4137 ffio_wfourcc(pb, "f4v ");
4139 ffio_wfourcc(pb, "qt ");
4141 avio_wb32(pb, minor);
4143 if (mov->mode == MODE_MOV)
4144 ffio_wfourcc(pb, "qt ");
4145 else if (mov->mode == MODE_ISM) {
4146 ffio_wfourcc(pb, "piff");
4147 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4148 ffio_wfourcc(pb, "isom");
4149 ffio_wfourcc(pb, "iso2");
4151 ffio_wfourcc(pb, "avc1");
4154 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4155 // brand. This is compatible with users that don't understand tfdt.
4156 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4157 ffio_wfourcc(pb, "iso6");
4159 if (mov->mode == MODE_3GP)
4160 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4161 else if (mov->mode & MODE_3G2)
4162 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4163 else if (mov->mode == MODE_PSP)
4164 ffio_wfourcc(pb, "MSNV");
4165 else if (mov->mode == MODE_MP4)
4166 ffio_wfourcc(pb, "mp41");
4168 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4169 ffio_wfourcc(pb, "dash");
4171 return update_size(pb, pos);
4174 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4176 AVStream *video_st = s->streams[0];
4177 AVCodecParameters *video_par = s->streams[0]->codecpar;
4178 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4179 int audio_rate = audio_par->sample_rate;
4180 // TODO: should be avg_frame_rate
4181 int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
4182 int audio_kbitrate = audio_par->bit_rate / 1000;
4183 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4185 avio_wb32(pb, 0x94); /* size */
4186 ffio_wfourcc(pb, "uuid");
4187 ffio_wfourcc(pb, "PROF");
4189 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4190 avio_wb32(pb, 0xbb88695c);
4191 avio_wb32(pb, 0xfac9c740);
4193 avio_wb32(pb, 0x0); /* ? */
4194 avio_wb32(pb, 0x3); /* 3 sections ? */
4196 avio_wb32(pb, 0x14); /* size */
4197 ffio_wfourcc(pb, "FPRF");
4198 avio_wb32(pb, 0x0); /* ? */
4199 avio_wb32(pb, 0x0); /* ? */
4200 avio_wb32(pb, 0x0); /* ? */
4202 avio_wb32(pb, 0x2c); /* size */
4203 ffio_wfourcc(pb, "APRF"); /* audio */
4205 avio_wb32(pb, 0x2); /* TrackID */
4206 ffio_wfourcc(pb, "mp4a");
4207 avio_wb32(pb, 0x20f);
4209 avio_wb32(pb, audio_kbitrate);
4210 avio_wb32(pb, audio_kbitrate);
4211 avio_wb32(pb, audio_rate);
4212 avio_wb32(pb, audio_par->channels);
4214 avio_wb32(pb, 0x34); /* size */
4215 ffio_wfourcc(pb, "VPRF"); /* video */
4217 avio_wb32(pb, 0x1); /* TrackID */
4218 if (video_par->codec_id == AV_CODEC_ID_H264) {
4219 ffio_wfourcc(pb, "avc1");
4220 avio_wb16(pb, 0x014D);
4221 avio_wb16(pb, 0x0015);
4223 ffio_wfourcc(pb, "mp4v");
4224 avio_wb16(pb, 0x0000);
4225 avio_wb16(pb, 0x0103);
4228 avio_wb32(pb, video_kbitrate);
4229 avio_wb32(pb, video_kbitrate);
4230 avio_wb32(pb, frame_rate);
4231 avio_wb32(pb, frame_rate);
4232 avio_wb16(pb, video_par->width);
4233 avio_wb16(pb, video_par->height);
4234 avio_wb32(pb, 0x010001); /* ? */
4237 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4239 MOVMuxContext *mov = s->priv_data;
4242 mov_write_ftyp_tag(pb,s);
4243 if (mov->mode == MODE_PSP) {
4244 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4245 for (i = 0; i < s->nb_streams; i++) {
4246 AVStream *st = s->streams[i];
4247 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4249 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4255 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4256 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4257 return AVERROR(EINVAL);
4259 mov_write_uuidprof_tag(pb, s);
4264 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4267 int i, closed_gop = 0;
4269 for (i = 0; i < pkt->size - 4; i++) {
4270 c = (c << 8) + pkt->data[i];
4271 if (c == 0x1b8) { // gop
4272 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4273 } else if (c == 0x100) { // pic
4274 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4275 if (!temp_ref || closed_gop) // I picture is not reordered
4276 *flags = MOV_SYNC_SAMPLE;
4278 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4285 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4287 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4288 int seq = 0, entry = 0;
4289 int key = pkt->flags & AV_PKT_FLAG_KEY;
4290 start = find_next_marker(pkt->data, end);
4291 for (next = start; next < end; start = next) {
4292 next = find_next_marker(start + 4, end);
4293 switch (AV_RB32(start)) {
4294 case VC1_CODE_SEQHDR:
4297 case VC1_CODE_ENTRYPOINT:
4300 case VC1_CODE_SLICE:
4301 trk->vc1_info.slices = 1;
4305 if (!trk->entry && trk->vc1_info.first_packet_seen)
4306 trk->vc1_info.first_frag_written = 1;
4307 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4308 /* First packet in first fragment */
4309 trk->vc1_info.first_packet_seq = seq;
4310 trk->vc1_info.first_packet_entry = entry;
4311 trk->vc1_info.first_packet_seen = 1;
4312 } else if ((seq && !trk->vc1_info.packet_seq) ||
4313 (entry && !trk->vc1_info.packet_entry)) {
4315 for (i = 0; i < trk->entry; i++)
4316 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4317 trk->has_keyframes = 0;
4319 trk->vc1_info.packet_seq = 1;
4321 trk->vc1_info.packet_entry = 1;
4322 if (!trk->vc1_info.first_frag_written) {
4323 /* First fragment */
4324 if ((!seq || trk->vc1_info.first_packet_seq) &&
4325 (!entry || trk->vc1_info.first_packet_entry)) {
4326 /* First packet had the same headers as this one, readd the
4327 * sync sample flag. */
4328 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4329 trk->has_keyframes = 1;
4333 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4335 else if (trk->vc1_info.packet_seq)
4337 else if (trk->vc1_info.packet_entry)
4340 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4341 trk->has_keyframes++;
4345 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4347 MOVMuxContext *mov = s->priv_data;
4352 if (!track->mdat_buf)
4354 if (!mov->mdat_buf) {
4355 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4358 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4359 track->mdat_buf = NULL;
4361 offset = avio_tell(mov->mdat_buf);
4362 avio_write(mov->mdat_buf, buf, buf_size);
4365 for (i = track->entries_flushed; i < track->entry; i++)
4366 track->cluster[i].pos += offset;
4367 track->entries_flushed = track->entry;
4371 static int mov_flush_fragment(AVFormatContext *s, int force)
4373 MOVMuxContext *mov = s->priv_data;
4374 int i, first_track = -1;
4375 int64_t mdat_size = 0;
4377 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4379 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4382 // Try to fill in the duration of the last packet in each stream
4383 // from queued packets in the interleave queues. If the flushing
4384 // of fragments was triggered automatically by an AVPacket, we
4385 // already have reliable info for the end of that track, but other
4386 // tracks may need to be filled in.
4387 for (i = 0; i < s->nb_streams; i++) {
4388 MOVTrack *track = &mov->tracks[i];
4389 if (!track->end_reliable) {
4391 const AVPacket *next = ff_interleaved_peek(s, i, &ts_offset);
4393 track->track_duration = next->dts - track->start_dts + ts_offset;
4394 if (next->pts != AV_NOPTS_VALUE)
4395 track->end_pts = next->pts;
4397 track->end_pts = next->dts;
4398 track->end_pts += ts_offset;
4403 for (i = 0; i < mov->nb_streams; i++) {
4404 MOVTrack *track = &mov->tracks[i];
4405 if (track->entry <= 1)
4407 // Sample durations are calculated as the diff of dts values,
4408 // but for the last sample in a fragment, we don't know the dts
4409 // of the first sample in the next fragment, so we have to rely
4410 // on what was set as duration in the AVPacket. Not all callers
4411 // set this though, so we might want to replace it with an
4412 // estimate if it currently is zero.
4413 if (get_cluster_duration(track, track->entry - 1) != 0)
4415 // Use the duration (i.e. dts diff) of the second last sample for
4416 // the last one. This is a wild guess (and fatal if it turns out
4417 // to be too long), but probably the best we can do - having a zero
4418 // duration is bad as well.
4419 track->track_duration += get_cluster_duration(track, track->entry - 2);
4420 track->end_pts += get_cluster_duration(track, track->entry - 2);
4421 if (!mov->missing_duration_warned) {
4422 av_log(s, AV_LOG_WARNING,
4423 "Estimating the duration of the last packet in a "
4424 "fragment, consider setting the duration field in "
4425 "AVPacket instead.\n");
4426 mov->missing_duration_warned = 1;
4430 if (!mov->moov_written) {
4431 int64_t pos = avio_tell(s->pb);
4433 int buf_size, moov_size;
4435 for (i = 0; i < mov->nb_streams; i++)
4436 if (!mov->tracks[i].entry)
4438 /* Don't write the initial moov unless all tracks have data */
4439 if (i < mov->nb_streams && !force)
4442 moov_size = get_moov_size(s);
4443 for (i = 0; i < mov->nb_streams; i++)
4444 mov->tracks[i].data_offset = pos + moov_size + 8;
4446 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4447 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4448 mov_write_identification(s->pb, s);
4449 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4452 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4453 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4454 mov->reserved_header_pos = avio_tell(s->pb);
4456 mov->moov_written = 1;
4460 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4461 mov->mdat_buf = NULL;
4462 avio_wb32(s->pb, buf_size + 8);
4463 ffio_wfourcc(s->pb, "mdat");
4464 avio_write(s->pb, buf, buf_size);
4467 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4468 mov->reserved_header_pos = avio_tell(s->pb);
4470 mov->moov_written = 1;
4472 for (i = 0; i < mov->nb_streams; i++) {
4473 if (mov->tracks[i].entry)
4474 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4475 mov->tracks[i].track_duration -
4476 mov->tracks[i].cluster[0].dts;
4477 mov->tracks[i].entry = 0;
4478 mov->tracks[i].end_reliable = 0;
4484 if (mov->frag_interleave) {
4485 for (i = 0; i < mov->nb_streams; i++) {
4486 MOVTrack *track = &mov->tracks[i];
4488 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4494 mdat_size = avio_tell(mov->mdat_buf);
4497 for (i = 0; i < mov->nb_streams; i++) {
4498 MOVTrack *track = &mov->tracks[i];
4499 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4500 track->data_offset = 0;
4502 track->data_offset = mdat_size;
4503 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4505 if (first_video_track) {
4507 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4508 first_video_track = 0;
4513 if (track->mdat_buf)
4514 mdat_size += avio_tell(track->mdat_buf);
4515 if (first_track < 0)
4522 avio_write_marker(s->pb,
4523 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4524 (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);
4526 for (i = 0; i < mov->nb_streams; i++) {
4527 MOVTrack *track = &mov->tracks[i];
4528 int buf_size, write_moof = 1, moof_tracks = -1;
4530 int64_t duration = 0;
4533 duration = track->start_dts + track->track_duration -
4534 track->cluster[0].dts;
4535 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4536 if (!track->mdat_buf)
4538 mdat_size = avio_tell(track->mdat_buf);
4541 write_moof = i == first_track;
4547 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4550 avio_wb32(s->pb, mdat_size + 8);
4551 ffio_wfourcc(s->pb, "mdat");
4555 track->frag_start += duration;
4557 track->entries_flushed = 0;
4558 track->end_reliable = 0;
4559 if (!mov->frag_interleave) {
4560 if (!track->mdat_buf)
4562 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4563 track->mdat_buf = NULL;
4567 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4568 mov->mdat_buf = NULL;
4571 avio_write(s->pb, buf, buf_size);
4581 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4583 MOVMuxContext *mov = s->priv_data;
4584 int had_moov = mov->moov_written;
4585 int ret = mov_flush_fragment(s, force);
4588 // If using delay_moov, the first flush only wrote the moov,
4589 // not the actual moof+mdat pair, thus flush once again.
4590 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4591 ret = mov_flush_fragment(s, force);
4595 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4597 MOVMuxContext *mov = s->priv_data;
4598 AVIOContext *pb = s->pb;
4599 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4600 AVCodecParameters *par = trk->par;
4601 unsigned int samples_in_chunk = 0;
4602 int size = pkt->size, ret = 0;
4603 uint8_t *reformatted_data = NULL;
4606 int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
4607 if (duration < 0 || duration > INT_MAX) {
4608 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4612 pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
4613 pkt->pts = AV_NOPTS_VALUE;
4616 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
4617 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
4618 return AVERROR(EINVAL);
4620 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4622 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4623 if (mov->frag_interleave && mov->fragments > 0) {
4624 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
4625 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
4630 if (!trk->mdat_buf) {
4631 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4636 if (!mov->mdat_buf) {
4637 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4644 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
4645 /* We must find out how many AMR blocks there are in one packet */
4646 static const uint16_t packed_size[16] =
4647 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4650 while (len < size && samples_in_chunk < 100) {
4651 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4654 if (samples_in_chunk > 1) {
4655 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4658 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
4659 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4660 samples_in_chunk = trk->par->frame_size;
4661 } else if (trk->sample_size)
4662 samples_in_chunk = size / trk->sample_size;
4664 samples_in_chunk = 1;
4666 /* copy extradata if it exists */
4667 if (trk->vos_len == 0 && par->extradata_size > 0 &&
4668 !TAG_IS_AVCI(trk->tag) &&
4669 (par->codec_id != AV_CODEC_ID_DNXHD)) {
4670 trk->vos_len = par->extradata_size;
4671 trk->vos_data = av_malloc(trk->vos_len);
4672 if (!trk->vos_data) {
4673 ret = AVERROR(ENOMEM);
4676 memcpy(trk->vos_data, par->extradata, trk->vos_len);
4679 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4680 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4681 if (!s->streams[pkt->stream_index]->nb_frames) {
4682 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4683 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4684 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4687 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4689 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4690 /* from x264 or from bytestream H.264 */
4691 /* NAL reformatting needed */
4692 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4693 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4695 avio_write(pb, reformatted_data, size);
4697 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4698 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
4704 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4707 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4708 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4709 /* extradata is Annex B, assume the bitstream is too and convert it */
4710 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4711 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4712 avio_write(pb, reformatted_data, size);
4714 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4716 #if CONFIG_AC3_PARSER
4717 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
4718 size = handle_eac3(mov, pkt, trk);
4723 avio_write(pb, pkt->data, size);
4726 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4727 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
4728 int nal_size_length = (par->extradata[4] & 0x3) + 1;
4729 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
4731 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
4738 avio_write(pb, pkt->data, size);
4742 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
4743 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4744 /* copy frame to create needed atoms */
4745 trk->vos_len = size;
4746 trk->vos_data = av_malloc(size);
4747 if (!trk->vos_data) {
4748 ret = AVERROR(ENOMEM);
4751 memcpy(trk->vos_data, pkt->data, size);
4754 if (trk->entry >= trk->cluster_capacity) {
4755 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4756 if (av_reallocp_array(&trk->cluster, new_capacity,
4757 sizeof(*trk->cluster))) {
4758 ret = AVERROR(ENOMEM);
4761 trk->cluster_capacity = new_capacity;
4764 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
4765 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4766 trk->cluster[trk->entry].chunkNum = 0;
4767 trk->cluster[trk->entry].size = size;
4768 trk->cluster[trk->entry].entries = samples_in_chunk;
4769 trk->cluster[trk->entry].dts = pkt->dts;
4770 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4771 if (!trk->frag_discont) {
4772 /* First packet of a new fragment. We already wrote the duration
4773 * of the last packet of the previous fragment based on track_duration,
4774 * which might not exactly match our dts. Therefore adjust the dts
4775 * of this packet to be what the previous packets duration implies. */
4776 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4777 /* We also may have written the pts and the corresponding duration
4778 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
4779 * the next fragment. This means the cts of the first sample must
4780 * be the same in all fragments, unless end_pts was updated by
4781 * the packet causing the fragment to be written. */
4782 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
4783 mov->mode == MODE_ISM)
4784 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
4786 /* New fragment, but discontinuous from previous fragments.
4787 * Pretend the duration sum of the earlier fragments is
4788 * pkt->dts - trk->start_dts. */
4789 trk->frag_start = pkt->dts - trk->start_dts;
4790 trk->end_pts = AV_NOPTS_VALUE;
4791 trk->frag_discont = 0;
4795 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4796 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4797 /* Not using edit lists and shifting the first track to start from zero.
4798 * If the other streams start from a later timestamp, we won't be able
4799 * to signal the difference in starting time without an edit list.
4800 * Thus move the timestamp for this first sample to 0, increasing
4801 * its duration instead. */
4802 trk->cluster[trk->entry].dts = trk->start_dts = 0;
4804 if (trk->start_dts == AV_NOPTS_VALUE) {
4805 trk->start_dts = pkt->dts;
4806 if (trk->frag_discont) {
4807 if (mov->use_editlist) {
4808 /* Pretend the whole stream started at pts=0, with earlier fragments
4809 * already written. If the stream started at pts=0, the duration sum
4810 * of earlier fragments would have been pkt->pts. */
4811 trk->frag_start = pkt->pts;
4812 trk->start_dts = pkt->dts - pkt->pts;
4814 /* Pretend the whole stream started at dts=0, with earlier fragments
4815 * already written, with a duration summing up to pkt->dts. */
4816 trk->frag_start = pkt->dts;
4819 trk->frag_discont = 0;
4820 } else if (pkt->dts && mov->moov_written)
4821 av_log(s, AV_LOG_WARNING,
4822 "Track %d starts with a nonzero dts %"PRId64", while the moov "
4823 "already has been written. Set the delay_moov flag to handle "
4825 pkt->stream_index, pkt->dts);
4827 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4828 trk->last_sample_is_subtitle_end = 0;
4830 if (pkt->pts == AV_NOPTS_VALUE) {
4831 av_log(s, AV_LOG_WARNING, "pts has no value\n");
4832 pkt->pts = pkt->dts;
4834 if (pkt->dts != pkt->pts)
4835 trk->flags |= MOV_TRACK_CTTS;
4836 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
4837 trk->cluster[trk->entry].flags = 0;
4838 if (trk->start_cts == AV_NOPTS_VALUE)
4839 trk->start_cts = pkt->pts - pkt->dts;
4840 if (trk->end_pts == AV_NOPTS_VALUE)
4841 trk->end_pts = trk->cluster[trk->entry].dts +
4842 trk->cluster[trk->entry].cts + pkt->duration;
4844 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
4845 trk->cluster[trk->entry].cts +
4848 if (par->codec_id == AV_CODEC_ID_VC1) {
4849 mov_parse_vc1_frame(pkt, trk);
4850 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4851 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4852 trk->entry > 0) { // force sync sample for the first key frame
4853 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4854 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4855 trk->flags |= MOV_TRACK_STPS;
4857 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
4859 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
4860 trk->has_keyframes++;
4863 trk->sample_count += samples_in_chunk;
4864 mov->mdat_size += size;
4866 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
4867 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
4868 reformatted_data, size);
4873 av_free(reformatted_data);
4877 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
4879 MOVMuxContext *mov = s->priv_data;
4880 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4881 AVCodecParameters *par = trk->par;
4882 int64_t frag_duration = 0;
4883 int size = pkt->size;
4885 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
4887 for (i = 0; i < s->nb_streams; i++)
4888 mov->tracks[i].frag_discont = 1;
4889 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
4893 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
4894 trk->start_dts = pkt->dts;
4895 if (pkt->pts != AV_NOPTS_VALUE)
4896 trk->start_cts = pkt->pts - pkt->dts;
4901 return 0; /* Discard 0 sized packets */
4904 if (trk->entry && pkt->stream_index < s->nb_streams)
4905 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
4906 s->streams[pkt->stream_index]->time_base,
4908 if ((mov->max_fragment_duration &&
4909 frag_duration >= mov->max_fragment_duration) ||
4910 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
4911 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
4912 par->codec_type == AVMEDIA_TYPE_VIDEO &&
4913 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
4914 if (frag_duration >= mov->min_fragment_duration) {
4915 // Set the duration of this track to line up with the next
4916 // sample in this track. This avoids relying on AVPacket
4917 // duration, but only helps for this particular track, not
4918 // for the other ones that are flushed at the same time.
4919 trk->track_duration = pkt->dts - trk->start_dts;
4920 if (pkt->pts != AV_NOPTS_VALUE)
4921 trk->end_pts = pkt->pts;
4923 trk->end_pts = pkt->dts;
4924 trk->end_reliable = 1;
4925 mov_auto_flush_fragment(s, 0);
4929 return ff_mov_write_packet(s, pkt);
4932 static int mov_write_subtitle_end_packet(AVFormatContext *s,
4936 uint8_t data[2] = {0};
4939 av_init_packet(&end);
4940 end.size = sizeof(data);
4945 end.stream_index = stream_index;
4947 ret = mov_write_single_packet(s, &end);
4948 av_packet_unref(&end);
4953 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4956 mov_flush_fragment(s, 1);
4960 MOVMuxContext *mov = s->priv_data;
4961 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4964 return mov_write_single_packet(s, pkt); /* Passthrough. */
4967 * Subtitles require special handling.
4969 * 1) For full complaince, every track must have a sample at
4970 * dts == 0, which is rarely true for subtitles. So, as soon
4971 * as we see any packet with dts > 0, write an empty subtitle
4972 * at dts == 0 for any subtitle track with no samples in it.
4974 * 2) For each subtitle track, check if the current packet's
4975 * dts is past the duration of the last subtitle sample. If
4976 * so, we now need to write an end sample for that subtitle.
4978 * This must be done conditionally to allow for subtitles that
4979 * immediately replace each other, in which case an end sample
4980 * is not needed, and is, in fact, actively harmful.
4982 * 3) See mov_write_trailer for how the final end sample is
4985 for (i = 0; i < mov->nb_streams; i++) {
4986 MOVTrack *trk = &mov->tracks[i];
4989 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
4990 trk->track_duration < pkt->dts &&
4991 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
4992 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
4993 if (ret < 0) return ret;
4994 trk->last_sample_is_subtitle_end = 1;
4998 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4999 AVPacket *opkt = pkt;
5000 int reshuffle_ret, ret;
5001 if (trk->is_unaligned_qt_rgb) {
5002 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5003 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5004 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5005 if (reshuffle_ret < 0)
5006 return reshuffle_ret;
5009 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5010 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5015 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5016 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5017 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5018 for (i = 0; i < pkt->size; i++)
5019 pkt->data[i] = ~pkt->data[i];
5021 if (reshuffle_ret) {
5022 ret = mov_write_single_packet(s, pkt);
5025 av_packet_free(&pkt);
5030 return mov_write_single_packet(s, pkt);
5034 // QuickTime chapters involve an additional text track with the chapter names
5035 // as samples, and a tref pointing from the other tracks to the chapter one.
5036 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5040 MOVMuxContext *mov = s->priv_data;
5041 MOVTrack *track = &mov->tracks[tracknum];
5042 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5045 track->mode = mov->mode;
5046 track->tag = MKTAG('t','e','x','t');
5047 track->timescale = MOV_TIMESCALE;
5048 track->par = avcodec_parameters_alloc();
5050 return AVERROR(ENOMEM);
5051 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5053 // These properties are required to make QT recognize the chapter track
5054 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5055 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5056 return AVERROR(ENOMEM);
5057 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5059 if (avio_open_dyn_buf(&pb) >= 0) {
5063 /* Stub header (usually for Quicktime chapter track) */
5065 avio_wb32(pb, 0x01); // displayFlags
5066 avio_w8(pb, 0x00); // horizontal justification
5067 avio_w8(pb, 0x00); // vertical justification
5068 avio_w8(pb, 0x00); // bgColourRed
5069 avio_w8(pb, 0x00); // bgColourGreen
5070 avio_w8(pb, 0x00); // bgColourBlue
5071 avio_w8(pb, 0x00); // bgColourAlpha
5073 avio_wb16(pb, 0x00); // defTextBoxTop
5074 avio_wb16(pb, 0x00); // defTextBoxLeft
5075 avio_wb16(pb, 0x00); // defTextBoxBottom
5076 avio_wb16(pb, 0x00); // defTextBoxRight
5078 avio_wb16(pb, 0x00); // startChar
5079 avio_wb16(pb, 0x00); // endChar
5080 avio_wb16(pb, 0x01); // fontID
5081 avio_w8(pb, 0x00); // fontStyleFlags
5082 avio_w8(pb, 0x00); // fontSize
5083 avio_w8(pb, 0x00); // fgColourRed
5084 avio_w8(pb, 0x00); // fgColourGreen
5085 avio_w8(pb, 0x00); // fgColourBlue
5086 avio_w8(pb, 0x00); // fgColourAlpha
5088 avio_wb32(pb, 0x0D); // box size
5089 ffio_wfourcc(pb, "ftab"); // box atom name
5090 avio_wb16(pb, 0x01); // entry count
5092 avio_wb16(pb, 0x01); // font ID
5093 avio_w8(pb, 0x00); // font name length
5095 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5096 track->par->extradata = buf;
5097 track->par->extradata_size = size;
5104 for (i = 0; i < s->nb_chapters; i++) {
5105 AVChapter *c = s->chapters[i];
5106 AVDictionaryEntry *t;
5108 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5109 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5110 pkt.duration = end - pkt.dts;
5112 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5113 static const char encd[12] = {
5114 0x00, 0x00, 0x00, 0x0C,
5116 0x00, 0x00, 0x01, 0x00 };
5117 len = strlen(t->value);
5118 pkt.size = len + 2 + 12;
5119 pkt.data = av_malloc(pkt.size);
5121 return AVERROR(ENOMEM);
5122 AV_WB16(pkt.data, len);
5123 memcpy(pkt.data + 2, t->value, len);
5124 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5125 ff_mov_write_packet(s, &pkt);
5126 av_freep(&pkt.data);
5134 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5138 /* compute the frame number */
5139 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5143 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5146 MOVMuxContext *mov = s->priv_data;
5147 MOVTrack *track = &mov->tracks[index];
5148 AVStream *src_st = s->streams[src_index];
5149 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5150 AVRational rate = find_fps(s, src_st);
5152 /* tmcd track based on video stream */
5153 track->mode = mov->mode;
5154 track->tag = MKTAG('t','m','c','d');
5155 track->src_track = src_index;
5156 track->timescale = mov->tracks[src_index].timescale;
5157 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5158 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5160 /* set st to src_st for metadata access*/
5163 /* encode context: tmcd data stream */
5164 track->par = avcodec_parameters_alloc();
5166 return AVERROR(ENOMEM);
5167 track->par->codec_type = AVMEDIA_TYPE_DATA;
5168 track->par->codec_tag = track->tag;
5169 track->st->avg_frame_rate = av_inv_q(rate);
5171 /* the tmcd track just contains one packet with the frame number */
5172 pkt.data = av_malloc(pkt.size);
5174 return AVERROR(ENOMEM);
5175 AV_WB32(pkt.data, tc.start);
5176 ret = ff_mov_write_packet(s, &pkt);
5182 * st->disposition controls the "enabled" flag in the tkhd tag.
5183 * QuickTime will not play a track if it is not enabled. So make sure
5184 * that one track of each type (audio, video, subtitle) is enabled.
5186 * Subtitles are special. For audio and video, setting "enabled" also
5187 * makes the track "default" (i.e. it is rendered when played). For
5188 * subtitles, an "enabled" subtitle is not rendered by default, but
5189 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5192 static void enable_tracks(AVFormatContext *s)
5194 MOVMuxContext *mov = s->priv_data;
5196 int enabled[AVMEDIA_TYPE_NB];
5197 int first[AVMEDIA_TYPE_NB];
5199 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5204 for (i = 0; i < s->nb_streams; i++) {
5205 AVStream *st = s->streams[i];
5207 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5208 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5211 if (first[st->codecpar->codec_type] < 0)
5212 first[st->codecpar->codec_type] = i;
5213 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5214 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5215 enabled[st->codecpar->codec_type]++;
5219 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5221 case AVMEDIA_TYPE_VIDEO:
5222 case AVMEDIA_TYPE_AUDIO:
5223 case AVMEDIA_TYPE_SUBTITLE:
5225 mov->per_stream_grouping = 1;
5226 if (!enabled[i] && first[i] >= 0)
5227 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5233 static void mov_free(AVFormatContext *s)
5235 MOVMuxContext *mov = s->priv_data;
5238 if (mov->chapter_track) {
5239 if (mov->tracks[mov->chapter_track].par)
5240 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5241 av_freep(&mov->tracks[mov->chapter_track].par);
5244 for (i = 0; i < mov->nb_streams; i++) {
5245 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5246 ff_mov_close_hinting(&mov->tracks[i]);
5247 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5248 av_freep(&mov->tracks[i].par);
5249 av_freep(&mov->tracks[i].cluster);
5250 av_freep(&mov->tracks[i].frag_info);
5252 if (mov->tracks[i].vos_len)
5253 av_freep(&mov->tracks[i].vos_data);
5255 ff_mov_cenc_free(&mov->tracks[i].cenc);
5258 av_freep(&mov->tracks);
5261 static uint32_t rgb_to_yuv(uint32_t rgb)
5266 r = (rgb >> 16) & 0xFF;
5267 g = (rgb >> 8) & 0xFF;
5270 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5271 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5272 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5274 return (y << 16) | (cr << 8) | cb;
5277 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5280 int i, width = 720, height = 480;
5281 int have_palette = 0, have_size = 0;
5282 uint32_t palette[16];
5283 char *cur = st->codecpar->extradata;
5285 while (cur && *cur) {
5286 if (strncmp("palette:", cur, 8) == 0) {
5288 count = sscanf(cur + 8,
5289 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5290 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5291 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5292 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5293 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5294 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5295 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5296 &palette[12], &palette[13], &palette[14], &palette[15]);
5298 for (i = 0; i < count; i++) {
5299 palette[i] = rgb_to_yuv(palette[i]);
5302 } else if (!strncmp("size:", cur, 5)) {
5303 sscanf(cur + 5, "%dx%d", &width, &height);
5306 if (have_palette && have_size)
5308 cur += strcspn(cur, "\n\r");
5309 cur += strspn(cur, "\n\r");
5312 track->vos_data = av_malloc(16*4);
5313 if (!track->vos_data)
5314 return AVERROR(ENOMEM);
5315 for (i = 0; i < 16; i++) {
5316 AV_WB32(track->vos_data + i * 4, palette[i]);
5318 track->vos_len = 16 * 4;
5320 st->codecpar->width = width;
5321 st->codecpar->height = track->height = height;
5326 static int mov_write_header(AVFormatContext *s)
5328 AVIOContext *pb = s->pb;
5329 MOVMuxContext *mov = s->priv_data;
5330 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5331 int i, ret, hint_track = 0, tmcd_track = 0;
5335 /* Default mode == MP4 */
5336 mov->mode = MODE_MP4;
5339 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5340 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5341 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5342 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5343 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5344 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5345 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5348 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5349 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5351 /* Set the FRAGMENT flag if any of the fragmentation methods are
5353 if (mov->max_fragment_duration || mov->max_fragment_size ||
5354 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5355 FF_MOV_FLAG_FRAG_KEYFRAME |
5356 FF_MOV_FLAG_FRAG_CUSTOM))
5357 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5359 /* Set other implicit flags immediately */
5360 if (mov->mode == MODE_ISM)
5361 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5362 FF_MOV_FLAG_FRAGMENT;
5363 if (mov->flags & FF_MOV_FLAG_DASH)
5364 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5365 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5367 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5368 mov->reserved_moov_size = -1;
5371 if (mov->use_editlist < 0) {
5372 mov->use_editlist = 1;
5373 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5374 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5375 // If we can avoid needing an edit list by shifting the
5376 // tracks, prefer that over (trying to) write edit lists
5377 // in fragmented output.
5378 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5379 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5380 mov->use_editlist = 0;
5383 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5384 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5385 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5387 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5388 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5390 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5391 * if the latter is set that's enough and omit_tfhd_offset doesn't
5392 * add anything extra on top of that. */
5393 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5394 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5395 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5397 if (mov->frag_interleave &&
5398 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5399 av_log(s, AV_LOG_ERROR,
5400 "Sample interleaving in fragments is mutually exclusive with "
5401 "omit_tfhd_offset and separate_moof\n");
5402 return AVERROR(EINVAL);
5405 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5406 * is enabled, we don't support non-seekable output at all. */
5407 if (!s->pb->seekable &&
5408 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5409 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5410 return AVERROR(EINVAL);
5413 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5414 if ((ret = mov_write_identification(pb, s)) < 0)
5418 mov->nb_streams = s->nb_streams;
5419 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5420 mov->chapter_track = mov->nb_streams++;
5422 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5423 /* Add hint tracks for each audio and video stream */
5424 hint_track = mov->nb_streams;
5425 for (i = 0; i < s->nb_streams; i++) {
5426 AVStream *st = s->streams[i];
5427 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5428 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5434 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4) {
5435 tmcd_track = mov->nb_streams;
5437 /* +1 tmcd track for each video stream with a timecode */
5438 for (i = 0; i < s->nb_streams; i++) {
5439 AVStream *st = s->streams[i];
5441 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5442 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5444 ret = mov_check_timecode_track(s, &tc, i, t->value);
5446 mov->nb_meta_tmcd++;
5450 /* check if there is already a tmcd track to remux */
5451 if (mov->nb_meta_tmcd) {
5452 for (i = 0; i < s->nb_streams; i++) {
5453 AVStream *st = s->streams[i];
5454 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5455 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5456 "so timecode metadata are now ignored\n");
5457 mov->nb_meta_tmcd = 0;
5462 mov->nb_streams += mov->nb_meta_tmcd;
5465 // Reserve an extra stream for chapters for the case where chapters
5466 // are written in the trailer
5467 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5469 return AVERROR(ENOMEM);
5471 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5472 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5473 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5475 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5476 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5477 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5478 ret = AVERROR(EINVAL);
5482 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5483 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5484 mov->encryption_kid_len, CENC_KID_SIZE);
5485 ret = AVERROR(EINVAL);
5489 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5490 mov->encryption_scheme_str);
5491 ret = AVERROR(EINVAL);
5496 for (i = 0; i < s->nb_streams; i++) {
5497 AVStream *st= s->streams[i];
5498 MOVTrack *track= &mov->tracks[i];
5499 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5502 track->par = st->codecpar;
5503 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5504 if (track->language < 0)
5505 track->language = 0;
5506 track->mode = mov->mode;
5507 track->tag = mov_find_codec_tag(s, track);
5509 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5510 "codec not currently supported in container\n",
5511 avcodec_get_name(st->codecpar->codec_id), i);
5512 ret = AVERROR(EINVAL);
5515 /* If hinting of this track is enabled by a later hint track,
5516 * this is updated. */
5517 track->hint_track = -1;
5518 track->start_dts = AV_NOPTS_VALUE;
5519 track->start_cts = AV_NOPTS_VALUE;
5520 track->end_pts = AV_NOPTS_VALUE;
5521 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5522 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5523 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5524 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5525 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5526 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5527 ret = AVERROR(EINVAL);
5530 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5532 if (mov->video_track_timescale) {
5533 track->timescale = mov->video_track_timescale;
5535 track->timescale = st->time_base.den;
5536 while(track->timescale < 10000)
5537 track->timescale *= 2;
5539 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5540 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5541 ret = AVERROR(EINVAL);
5544 if (track->mode == MODE_MOV && track->timescale > 100000)
5545 av_log(s, AV_LOG_WARNING,
5546 "WARNING codec timebase is very high. If duration is too long,\n"
5547 "file may not be playable by quicktime. Specify a shorter timebase\n"
5548 "or choose different container.\n");
5549 if (track->mode == MODE_MOV &&
5550 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5551 track->tag == MKTAG('r','a','w',' ')) {
5552 enum AVPixelFormat pix_fmt = track->par->format;
5553 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5554 pix_fmt = AV_PIX_FMT_MONOWHITE;
5555 track->is_unaligned_qt_rgb =
5556 pix_fmt == AV_PIX_FMT_RGB24 ||
5557 pix_fmt == AV_PIX_FMT_BGR24 ||
5558 pix_fmt == AV_PIX_FMT_PAL8 ||
5559 pix_fmt == AV_PIX_FMT_GRAY8 ||
5560 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5561 pix_fmt == AV_PIX_FMT_MONOBLACK;
5563 if (track->mode == MODE_MP4 &&
5564 track->par->codec_id == AV_CODEC_ID_VP9) {
5565 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
5566 av_log(s, AV_LOG_ERROR,
5567 "VP9 in MP4 support is experimental, add "
5568 "'-strict %d' if you want to use it.\n",
5569 FF_COMPLIANCE_EXPERIMENTAL);
5570 ret = AVERROR_EXPERIMENTAL;
5574 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5575 track->timescale = st->codecpar->sample_rate;
5576 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
5577 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
5578 track->audio_vbr = 1;
5579 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
5580 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
5581 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
5582 if (!st->codecpar->block_align) {
5583 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
5584 ret = AVERROR(EINVAL);
5587 track->sample_size = st->codecpar->block_align;
5588 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
5589 track->audio_vbr = 1;
5591 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
5593 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
5594 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
5595 track->audio_vbr = 1;
5597 if (track->mode != MODE_MOV &&
5598 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
5599 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
5600 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
5601 i, track->par->sample_rate);
5602 ret = AVERROR(EINVAL);
5605 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
5606 i, track->par->sample_rate);
5609 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5610 track->timescale = st->time_base.den;
5611 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
5612 track->timescale = st->time_base.den;
5614 track->timescale = MOV_TIMESCALE;
5617 track->height = st->codecpar->height;
5618 /* The ism specific timescale isn't mandatory, but is assumed by
5619 * some tools, such as mp4split. */
5620 if (mov->mode == MODE_ISM)
5621 track->timescale = 10000000;
5623 avpriv_set_pts_info(st, 64, 1, track->timescale);
5625 /* copy extradata if it exists */
5626 if (st->codecpar->extradata_size) {
5627 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
5628 mov_create_dvd_sub_decoder_specific_info(track, st);
5629 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
5630 track->vos_len = st->codecpar->extradata_size;
5631 track->vos_data = av_malloc(track->vos_len);
5632 if (!track->vos_data) {
5633 ret = AVERROR(ENOMEM);
5636 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
5640 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5641 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
5642 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
5649 for (i = 0; i < s->nb_streams; i++) {
5651 AVStream *st= s->streams[i];
5652 MOVTrack *track= &mov->tracks[i];
5654 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5655 track->par->channel_layout != AV_CH_LAYOUT_MONO)
5658 for (j = 0; j < s->nb_streams; j++) {
5659 AVStream *stj= s->streams[j];
5660 MOVTrack *trackj= &mov->tracks[j];
5664 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5665 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
5666 trackj->language != track->language ||
5667 trackj->tag != track->tag
5670 track->multichannel_as_mono++;
5677 if (mov->reserved_moov_size){
5678 mov->reserved_header_pos = avio_tell(pb);
5679 if (mov->reserved_moov_size > 0)
5680 avio_skip(pb, mov->reserved_moov_size);
5683 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5684 /* If no fragmentation options have been set, set a default. */
5685 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
5686 FF_MOV_FLAG_FRAG_CUSTOM)) &&
5687 !mov->max_fragment_duration && !mov->max_fragment_size)
5688 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
5690 if (mov->flags & FF_MOV_FLAG_FASTSTART)
5691 mov->reserved_header_pos = avio_tell(pb);
5692 mov_write_mdat_tag(pb, mov);
5695 ff_parse_creation_time_metadata(s, &mov->time, 1);
5697 mov->time += 0x7C25B080; // 1970 based -> 1904 based
5699 if (mov->chapter_track)
5700 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5703 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5704 /* Initialize the hint tracks for each audio and video stream */
5705 for (i = 0; i < s->nb_streams; i++) {
5706 AVStream *st = s->streams[i];
5707 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5708 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5709 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
5716 if (mov->nb_meta_tmcd) {
5717 /* Initialize the tmcd tracks */
5718 for (i = 0; i < s->nb_streams; i++) {
5719 AVStream *st = s->streams[i];
5722 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5725 t = av_dict_get(st->metadata, "timecode", NULL, 0);
5728 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
5730 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
5739 if (mov->flags & FF_MOV_FLAG_ISML)
5740 mov_write_isml_manifest(pb, mov);
5742 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5743 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5744 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
5747 mov->moov_written = 1;
5748 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5749 mov->reserved_header_pos = avio_tell(pb);
5758 static int get_moov_size(AVFormatContext *s)
5761 AVIOContext *moov_buf;
5762 MOVMuxContext *mov = s->priv_data;
5764 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
5766 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
5768 return ffio_close_null_buf(moov_buf);
5771 static int get_sidx_size(AVFormatContext *s)
5775 MOVMuxContext *mov = s->priv_data;
5777 if ((ret = ffio_open_null_buf(&buf)) < 0)
5779 mov_write_sidx_tags(buf, mov, -1, 0);
5780 return ffio_close_null_buf(buf);
5784 * This function gets the moov size if moved to the top of the file: the chunk
5785 * offset table can switch between stco (32-bit entries) to co64 (64-bit
5786 * entries) when the moov is moved to the beginning, so the size of the moov
5787 * would change. It also updates the chunk offset tables.
5789 static int compute_moov_size(AVFormatContext *s)
5791 int i, moov_size, moov_size2;
5792 MOVMuxContext *mov = s->priv_data;
5794 moov_size = get_moov_size(s);
5798 for (i = 0; i < mov->nb_streams; i++)
5799 mov->tracks[i].data_offset += moov_size;
5801 moov_size2 = get_moov_size(s);
5805 /* if the size changed, we just switched from stco to co64 and need to
5806 * update the offsets */
5807 if (moov_size2 != moov_size)
5808 for (i = 0; i < mov->nb_streams; i++)
5809 mov->tracks[i].data_offset += moov_size2 - moov_size;
5814 static int compute_sidx_size(AVFormatContext *s)
5817 MOVMuxContext *mov = s->priv_data;
5819 sidx_size = get_sidx_size(s);
5823 for (i = 0; i < mov->nb_streams; i++)
5824 mov->tracks[i].data_offset += sidx_size;
5829 static int shift_data(AVFormatContext *s)
5831 int ret = 0, moov_size;
5832 MOVMuxContext *mov = s->priv_data;
5833 int64_t pos, pos_end = avio_tell(s->pb);
5834 uint8_t *buf, *read_buf[2];
5835 int read_buf_id = 0;
5837 AVIOContext *read_pb;
5839 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
5840 moov_size = compute_sidx_size(s);
5842 moov_size = compute_moov_size(s);
5846 buf = av_malloc(moov_size * 2);
5848 return AVERROR(ENOMEM);
5850 read_buf[1] = buf + moov_size;
5852 /* Shift the data: the AVIO context of the output can only be used for
5853 * writing, so we re-open the same output, but for reading. It also avoids
5854 * a read/seek/write/seek back and forth. */
5856 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
5858 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
5859 "the second pass (faststart)\n", s->filename);
5863 /* mark the end of the shift to up to the last data we wrote, and get ready
5865 pos_end = avio_tell(s->pb);
5866 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
5868 /* start reading at where the new moov will be placed */
5869 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
5870 pos = avio_tell(read_pb);
5872 #define READ_BLOCK do { \
5873 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
5877 /* shift data by chunk of at most moov_size */
5882 n = read_size[read_buf_id];
5885 avio_write(s->pb, read_buf[read_buf_id], n);
5887 } while (pos < pos_end);
5888 ff_format_io_close(s, &read_pb);
5895 static int mov_write_trailer(AVFormatContext *s)
5897 MOVMuxContext *mov = s->priv_data;
5898 AVIOContext *pb = s->pb;
5904 * Before actually writing the trailer, make sure that there are no
5905 * dangling subtitles, that need a terminating sample.
5907 for (i = 0; i < mov->nb_streams; i++) {
5908 MOVTrack *trk = &mov->tracks[i];
5909 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5910 !trk->last_sample_is_subtitle_end) {
5911 mov_write_subtitle_end_packet(s, i, trk->track_duration);
5912 trk->last_sample_is_subtitle_end = 1;
5916 // If there were no chapters when the header was written, but there
5917 // are chapters now, write them in the trailer. This only works
5918 // when we are not doing fragments.
5919 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5920 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
5921 mov->chapter_track = mov->nb_streams++;
5922 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5927 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5928 moov_pos = avio_tell(pb);
5930 /* Write size of mdat tag */
5931 if (mov->mdat_size + 8 <= UINT32_MAX) {
5932 avio_seek(pb, mov->mdat_pos, SEEK_SET);
5933 avio_wb32(pb, mov->mdat_size + 8);
5935 /* overwrite 'wide' placeholder atom */
5936 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
5937 /* special value: real atom size will be 64 bit value after
5940 ffio_wfourcc(pb, "mdat");
5941 avio_wb64(pb, mov->mdat_size + 16);
5943 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
5945 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5946 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
5947 res = shift_data(s);
5950 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
5951 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5953 } else if (mov->reserved_moov_size > 0) {
5955 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5957 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
5959 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
5960 res = AVERROR(EINVAL);
5963 avio_wb32(pb, size);
5964 ffio_wfourcc(pb, "free");
5965 ffio_fill(pb, 0, size - 8);
5966 avio_seek(pb, moov_pos, SEEK_SET);
5968 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5973 mov_auto_flush_fragment(s, 1);
5974 for (i = 0; i < mov->nb_streams; i++)
5975 mov->tracks[i].data_offset = 0;
5976 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
5978 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
5979 res = shift_data(s);
5982 end = avio_tell(pb);
5983 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
5984 mov_write_sidx_tags(pb, mov, -1, 0);
5985 avio_seek(pb, end, SEEK_SET);
5986 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
5987 mov_write_mfra_tag(pb, mov);
5989 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
5990 mov_write_mfra_tag(pb, mov);
6000 #if CONFIG_MOV_MUXER
6002 AVOutputFormat ff_mov_muxer = {
6004 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6005 .extensions = "mov",
6006 .priv_data_size = sizeof(MOVMuxContext),
6007 .audio_codec = AV_CODEC_ID_AAC,
6008 .video_codec = CONFIG_LIBX264_ENCODER ?
6009 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6010 .write_header = mov_write_header,
6011 .write_packet = mov_write_packet,
6012 .write_trailer = mov_write_trailer,
6013 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6014 .codec_tag = (const AVCodecTag* const []){
6015 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6017 .priv_class = &mov_muxer_class,
6020 #if CONFIG_TGP_MUXER
6022 AVOutputFormat ff_tgp_muxer = {
6024 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6025 .extensions = "3gp",
6026 .priv_data_size = sizeof(MOVMuxContext),
6027 .audio_codec = AV_CODEC_ID_AMR_NB,
6028 .video_codec = AV_CODEC_ID_H263,
6029 .write_header = mov_write_header,
6030 .write_packet = mov_write_packet,
6031 .write_trailer = mov_write_trailer,
6032 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6033 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6034 .priv_class = &tgp_muxer_class,
6037 #if CONFIG_MP4_MUXER
6039 AVOutputFormat ff_mp4_muxer = {
6041 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6042 .mime_type = "video/mp4",
6043 .extensions = "mp4",
6044 .priv_data_size = sizeof(MOVMuxContext),
6045 .audio_codec = AV_CODEC_ID_AAC,
6046 .video_codec = CONFIG_LIBX264_ENCODER ?
6047 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6048 .write_header = mov_write_header,
6049 .write_packet = mov_write_packet,
6050 .write_trailer = mov_write_trailer,
6051 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6052 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6053 .priv_class = &mp4_muxer_class,
6056 #if CONFIG_PSP_MUXER
6058 AVOutputFormat ff_psp_muxer = {
6060 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6061 .extensions = "mp4,psp",
6062 .priv_data_size = sizeof(MOVMuxContext),
6063 .audio_codec = AV_CODEC_ID_AAC,
6064 .video_codec = CONFIG_LIBX264_ENCODER ?
6065 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6066 .write_header = mov_write_header,
6067 .write_packet = mov_write_packet,
6068 .write_trailer = mov_write_trailer,
6069 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6070 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6071 .priv_class = &psp_muxer_class,
6074 #if CONFIG_TG2_MUXER
6076 AVOutputFormat ff_tg2_muxer = {
6078 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6079 .extensions = "3g2",
6080 .priv_data_size = sizeof(MOVMuxContext),
6081 .audio_codec = AV_CODEC_ID_AMR_NB,
6082 .video_codec = AV_CODEC_ID_H263,
6083 .write_header = mov_write_header,
6084 .write_packet = mov_write_packet,
6085 .write_trailer = mov_write_trailer,
6086 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6087 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6088 .priv_class = &tg2_muxer_class,
6091 #if CONFIG_IPOD_MUXER
6093 AVOutputFormat ff_ipod_muxer = {
6095 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6096 .mime_type = "video/mp4",
6097 .extensions = "m4v,m4a",
6098 .priv_data_size = sizeof(MOVMuxContext),
6099 .audio_codec = AV_CODEC_ID_AAC,
6100 .video_codec = AV_CODEC_ID_H264,
6101 .write_header = mov_write_header,
6102 .write_packet = mov_write_packet,
6103 .write_trailer = mov_write_trailer,
6104 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6105 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6106 .priv_class = &ipod_muxer_class,
6109 #if CONFIG_ISMV_MUXER
6111 AVOutputFormat ff_ismv_muxer = {
6113 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6114 .mime_type = "video/mp4",
6115 .extensions = "ismv,isma",
6116 .priv_data_size = sizeof(MOVMuxContext),
6117 .audio_codec = AV_CODEC_ID_AAC,
6118 .video_codec = AV_CODEC_ID_H264,
6119 .write_header = mov_write_header,
6120 .write_packet = mov_write_packet,
6121 .write_trailer = mov_write_trailer,
6122 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6123 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6124 .priv_class = &ismv_muxer_class,
6127 #if CONFIG_F4V_MUXER
6129 AVOutputFormat ff_f4v_muxer = {
6131 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6132 .mime_type = "application/f4v",
6133 .extensions = "f4v",
6134 .priv_data_size = sizeof(MOVMuxContext),
6135 .audio_codec = AV_CODEC_ID_AAC,
6136 .video_codec = AV_CODEC_ID_H264,
6137 .write_header = mov_write_header,
6138 .write_packet = mov_write_packet,
6139 .write_trailer = mov_write_trailer,
6140 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6141 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6142 .priv_class = &f4v_muxer_class,