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"
53 static const AVOption options[] = {
54 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
55 { "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" },
56 { "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 },
57 { "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" },
58 { "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" },
59 { "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" },
60 { "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" },
61 { "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" },
62 { "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" },
63 { "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" },
64 { "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" },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
73 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
74 { "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},
75 { "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},
76 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
77 { "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},
78 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
79 { "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},
80 { "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},
81 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
82 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
83 { "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},
84 { "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},
85 { "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 },
86 { "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 },
87 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
88 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
92 #define MOV_CLASS(flavor)\
93 static const AVClass flavor ## _muxer_class = {\
94 .class_name = #flavor " muxer",\
95 .item_name = av_default_item_name,\
97 .version = LIBAVUTIL_VERSION_INT,\
100 static int get_moov_size(AVFormatContext *s);
102 static int utf8len(const uint8_t *b)
107 GET_UTF8(val, *b++, return -1;)
113 //FIXME support 64 bit variant with wide placeholders
114 static int64_t update_size(AVIOContext *pb, int64_t pos)
116 int64_t curpos = avio_tell(pb);
117 avio_seek(pb, pos, SEEK_SET);
118 avio_wb32(pb, curpos - pos); /* rewrite size */
119 avio_seek(pb, curpos, SEEK_SET);
124 static int co64_required(const MOVTrack *track)
126 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
131 /* Chunk offset atom */
132 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
135 int mode64 = co64_required(track); // use 32 bit size variant if possible
136 int64_t pos = avio_tell(pb);
137 avio_wb32(pb, 0); /* size */
139 ffio_wfourcc(pb, "co64");
141 ffio_wfourcc(pb, "stco");
142 avio_wb32(pb, 0); /* version & flags */
143 avio_wb32(pb, track->chunkCount); /* entry count */
144 for (i = 0; i < track->entry; i++) {
145 if (!track->cluster[i].chunkNum)
148 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
150 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
152 return update_size(pb, pos);
155 /* Sample size atom */
156 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
159 int i, j, entries = 0, tst = -1, oldtst = -1;
161 int64_t pos = avio_tell(pb);
162 avio_wb32(pb, 0); /* size */
163 ffio_wfourcc(pb, "stsz");
164 avio_wb32(pb, 0); /* version & flags */
166 for (i = 0; i < track->entry; i++) {
167 tst = track->cluster[i].size / track->cluster[i].entries;
168 if (oldtst != -1 && tst != oldtst)
171 entries += track->cluster[i].entries;
173 if (equalChunks && track->entry) {
174 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
175 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
176 avio_wb32(pb, sSize); // sample size
177 avio_wb32(pb, entries); // sample count
179 avio_wb32(pb, 0); // sample size
180 avio_wb32(pb, entries); // sample count
181 for (i = 0; i < track->entry; i++) {
182 for (j = 0; j < track->cluster[i].entries; j++) {
183 avio_wb32(pb, track->cluster[i].size /
184 track->cluster[i].entries);
188 return update_size(pb, pos);
191 /* Sample to chunk atom */
192 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
194 int index = 0, oldval = -1, i;
195 int64_t entryPos, curpos;
197 int64_t pos = avio_tell(pb);
198 avio_wb32(pb, 0); /* size */
199 ffio_wfourcc(pb, "stsc");
200 avio_wb32(pb, 0); // version & flags
201 entryPos = avio_tell(pb);
202 avio_wb32(pb, track->chunkCount); // entry count
203 for (i = 0; i < track->entry; i++) {
204 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
205 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
206 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
207 avio_wb32(pb, 0x1); // sample description index
208 oldval = track->cluster[i].samples_in_chunk;
212 curpos = avio_tell(pb);
213 avio_seek(pb, entryPos, SEEK_SET);
214 avio_wb32(pb, index); // rewrite size
215 avio_seek(pb, curpos, SEEK_SET);
217 return update_size(pb, pos);
220 /* Sync sample atom */
221 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
223 int64_t curpos, entryPos;
225 int64_t pos = avio_tell(pb);
226 avio_wb32(pb, 0); // size
227 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
228 avio_wb32(pb, 0); // version & flags
229 entryPos = avio_tell(pb);
230 avio_wb32(pb, track->entry); // entry count
231 for (i = 0; i < track->entry; i++) {
232 if (track->cluster[i].flags & flag) {
233 avio_wb32(pb, i + 1);
237 curpos = avio_tell(pb);
238 avio_seek(pb, entryPos, SEEK_SET);
239 avio_wb32(pb, index); // rewrite size
240 avio_seek(pb, curpos, SEEK_SET);
241 return update_size(pb, pos);
244 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
246 avio_wb32(pb, 0x11); /* size */
247 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
248 else ffio_wfourcc(pb, "damr");
249 ffio_wfourcc(pb, "FFMP");
250 avio_w8(pb, 0); /* decoder version */
252 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
253 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
254 avio_w8(pb, 0x01); /* Frames per sample */
258 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
263 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
265 if (track->vos_len < 7)
269 ffio_wfourcc(pb, "dac3");
271 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
272 fscod = get_bits(&gbc, 2);
273 frmsizecod = get_bits(&gbc, 6);
274 bsid = get_bits(&gbc, 5);
275 bsmod = get_bits(&gbc, 3);
276 acmod = get_bits(&gbc, 3);
278 skip_bits(&gbc, 2); // dsurmod
280 if ((acmod & 1) && acmod != 1)
281 skip_bits(&gbc, 2); // cmixlev
283 skip_bits(&gbc, 2); // surmixlev
285 lfeon = get_bits1(&gbc);
287 init_put_bits(&pbc, buf, sizeof(buf));
288 put_bits(&pbc, 2, fscod);
289 put_bits(&pbc, 5, bsid);
290 put_bits(&pbc, 3, bsmod);
291 put_bits(&pbc, 3, acmod);
292 put_bits(&pbc, 1, lfeon);
293 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
294 put_bits(&pbc, 5, 0); // reserved
296 flush_put_bits(&pbc);
297 avio_write(pb, buf, sizeof(buf));
307 /* Layout of the EC3SpecificBox */
308 /* maximum bitrate */
310 /* number of independent substreams */
313 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
315 /* bit stream identification 5 bits */
317 /* one bit reserved */
318 /* audio service mixing (not supported yet) 1 bit */
319 /* bit stream mode 3 bits */
321 /* audio coding mode 3 bits */
323 /* sub woofer on 1 bit */
325 /* 3 bits reserved */
326 /* number of dependent substreams associated with this substream 4 bits */
328 /* channel locations of the dependent substream(s), if any, 9 bits */
330 /* if there is no dependent substream, then one bit reserved instead */
331 } substream[1]; /* TODO: support 8 independent substreams */
334 #if CONFIG_AC3_PARSER
335 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
338 AC3HeaderInfo tmp, *hdr = &tmp;
339 struct eac3_info *info;
342 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
343 return AVERROR(ENOMEM);
344 info = track->eac3_priv;
346 init_get_bits(&gbc, pkt->data, pkt->size * 8);
347 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
348 /* drop the packets until we see a good one */
350 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
353 return AVERROR_INVALIDDATA;
356 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
357 num_blocks = hdr->num_blocks;
359 if (!info->ec3_done) {
360 /* AC-3 substream must be the first one */
361 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
362 return AVERROR(EINVAL);
364 /* this should always be the case, given that our AC-3 parser
365 * concatenates dependent frames to their independent parent */
366 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
367 /* substream ids must be incremental */
368 if (hdr->substreamid > info->num_ind_sub + 1)
369 return AVERROR(EINVAL);
371 if (hdr->substreamid == info->num_ind_sub + 1) {
372 //info->num_ind_sub++;
373 avpriv_request_sample(track->par, "Multiple independent substreams");
374 return AVERROR_PATCHWELCOME;
375 } else if (hdr->substreamid < info->num_ind_sub ||
376 hdr->substreamid == 0 && info->substream[0].bsid) {
382 /* fill the info needed for the "dec3" atom */
383 info->substream[hdr->substreamid].fscod = hdr->sr_code;
384 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
385 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
386 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
387 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
389 /* Parse dependent substream(s), if any */
390 if (pkt->size != hdr->frame_size) {
391 int cumul_size = hdr->frame_size;
392 int parent = hdr->substreamid;
394 while (cumul_size != pkt->size) {
396 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
397 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
398 return AVERROR_INVALIDDATA;
399 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
400 return AVERROR(EINVAL);
401 cumul_size += hdr->frame_size;
402 info->substream[parent].num_dep_sub++;
404 /* header is parsed up to lfeon, but custom channel map may be needed */
407 /* skip volume control params */
408 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
409 skip_bits(&gbc, 5); // skip dialog normalization
410 if (get_bits1(&gbc)) {
411 skip_bits(&gbc, 8); // skip compression gain word
414 /* get the dependent stream channel map, if exists */
416 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
418 info->substream[parent].chan_loc |= hdr->channel_mode;
424 if (!info->num_blocks && num_blocks == 6)
426 else if (info->num_blocks + num_blocks > 6)
427 return AVERROR_INVALIDDATA;
429 if (!info->num_blocks) {
431 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
433 info->num_blocks = num_blocks;
437 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
439 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
440 info->num_blocks += num_blocks;
441 info->pkt.duration += pkt->duration;
442 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
444 if (info->num_blocks != 6)
446 av_packet_unref(pkt);
447 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
449 av_packet_unref(&info->pkt);
450 info->num_blocks = 0;
457 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
461 struct eac3_info *info;
464 if (!track->eac3_priv)
465 return AVERROR(EINVAL);
467 info = track->eac3_priv;
468 size = 2 + 4 * (info->num_ind_sub + 1);
469 buf = av_malloc(size);
471 size = AVERROR(ENOMEM);
475 init_put_bits(&pbc, buf, size);
476 put_bits(&pbc, 13, info->data_rate);
477 put_bits(&pbc, 3, info->num_ind_sub);
478 for (i = 0; i <= info->num_ind_sub; i++) {
479 put_bits(&pbc, 2, info->substream[i].fscod);
480 put_bits(&pbc, 5, info->substream[i].bsid);
481 put_bits(&pbc, 1, 0); /* reserved */
482 put_bits(&pbc, 1, 0); /* asvc */
483 put_bits(&pbc, 3, info->substream[i].bsmod);
484 put_bits(&pbc, 3, info->substream[i].acmod);
485 put_bits(&pbc, 1, info->substream[i].lfeon);
486 put_bits(&pbc, 5, 0); /* reserved */
487 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
488 if (!info->substream[i].num_dep_sub) {
489 put_bits(&pbc, 1, 0); /* reserved */
492 put_bits(&pbc, 9, info->substream[i].chan_loc);
495 flush_put_bits(&pbc);
497 avio_wb32(pb, size + 8);
498 ffio_wfourcc(pb, "dec3");
499 avio_write(pb, buf, size);
504 av_packet_unref(&info->pkt);
505 av_freep(&track->eac3_priv);
511 * This function writes extradata "as is".
512 * Extradata must be formatted like a valid atom (with size and tag).
514 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
516 avio_write(pb, track->par->extradata, track->par->extradata_size);
517 return track->par->extradata_size;
520 static int mov_write_enda_tag(AVIOContext *pb)
523 ffio_wfourcc(pb, "enda");
524 avio_wb16(pb, 1); /* little endian */
528 static int mov_write_enda_tag_be(AVIOContext *pb)
531 ffio_wfourcc(pb, "enda");
532 avio_wb16(pb, 0); /* big endian */
536 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
541 avio_w8(pb, (size >> (7 * i)) | 0x80);
542 avio_w8(pb, size & 0x7F);
545 static unsigned compute_avg_bitrate(MOVTrack *track)
549 if (!track->track_duration)
551 for (i = 0; i < track->entry; i++)
552 size += track->cluster[i].size;
553 return size * 8 * track->timescale / track->track_duration;
556 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
558 AVCPBProperties *props;
559 int64_t pos = avio_tell(pb);
560 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
561 unsigned avg_bitrate;
563 avio_wb32(pb, 0); // size
564 ffio_wfourcc(pb, "esds");
565 avio_wb32(pb, 0); // Version
568 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
569 avio_wb16(pb, track->track_id);
570 avio_w8(pb, 0x00); // flags (= no flags)
572 // DecoderConfig descriptor
573 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
575 // Object type indication
576 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
577 track->par->codec_id == AV_CODEC_ID_MP3) &&
578 track->par->sample_rate > 24000)
579 avio_w8(pb, 0x6B); // 11172-3
581 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
583 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
584 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
585 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
586 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
587 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
588 avio_w8(pb, 0x15); // flags (= Audiostream)
590 avio_w8(pb, 0x11); // flags (= Visualstream)
592 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
595 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
597 avg_bitrate = compute_avg_bitrate(track);
598 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)
599 avio_wb32(pb, avg_bitrate);
601 if (track->vos_len) {
602 // DecoderSpecific info descriptor
603 put_descr(pb, 0x05, track->vos_len);
604 avio_write(pb, track->vos_data, track->vos_len);
608 put_descr(pb, 0x06, 1);
610 return update_size(pb, pos);
613 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
615 return codec_id == AV_CODEC_ID_PCM_S24LE ||
616 codec_id == AV_CODEC_ID_PCM_S32LE ||
617 codec_id == AV_CODEC_ID_PCM_F32LE ||
618 codec_id == AV_CODEC_ID_PCM_F64LE;
621 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
623 return codec_id == AV_CODEC_ID_PCM_S24BE ||
624 codec_id == AV_CODEC_ID_PCM_S32BE ||
625 codec_id == AV_CODEC_ID_PCM_F32BE ||
626 codec_id == AV_CODEC_ID_PCM_F64BE;
629 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
632 int64_t pos = avio_tell(pb);
634 avio_wl32(pb, track->tag); // store it byteswapped
635 track->par->codec_tag = av_bswap16(track->tag >> 16);
636 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
638 return update_size(pb, pos);
641 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
644 int64_t pos = avio_tell(pb);
646 ffio_wfourcc(pb, "wfex");
647 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
649 return update_size(pb, pos);
652 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
654 uint32_t layout_tag, bitmap;
655 int64_t pos = avio_tell(pb);
657 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
658 track->par->channel_layout,
661 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
662 "lack of channel information\n");
666 if (track->multichannel_as_mono)
669 avio_wb32(pb, 0); // Size
670 ffio_wfourcc(pb, "chan"); // Type
671 avio_w8(pb, 0); // Version
672 avio_wb24(pb, 0); // Flags
673 avio_wb32(pb, layout_tag); // mChannelLayoutTag
674 avio_wb32(pb, bitmap); // mChannelBitmap
675 avio_wb32(pb, 0); // mNumberChannelDescriptions
677 return update_size(pb, pos);
680 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
682 int64_t pos = avio_tell(pb);
684 avio_wb32(pb, 0); /* size */
685 ffio_wfourcc(pb, "wave");
687 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
688 avio_wb32(pb, 12); /* size */
689 ffio_wfourcc(pb, "frma");
690 avio_wl32(pb, track->tag);
693 if (track->par->codec_id == AV_CODEC_ID_AAC) {
694 /* useless atom needed by mplayer, ipod, not needed by quicktime */
695 avio_wb32(pb, 12); /* size */
696 ffio_wfourcc(pb, "mp4a");
698 mov_write_esds_tag(pb, track);
699 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
700 mov_write_enda_tag(pb);
701 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
702 mov_write_enda_tag_be(pb);
703 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
704 mov_write_amr_tag(pb, track);
705 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
706 mov_write_ac3_tag(pb, track);
707 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
708 mov_write_eac3_tag(pb, track);
709 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
710 track->par->codec_id == AV_CODEC_ID_QDM2) {
711 mov_write_extradata_tag(pb, track);
712 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
713 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
714 mov_write_ms_tag(s, pb, track);
717 avio_wb32(pb, 8); /* size */
718 avio_wb32(pb, 0); /* null tag */
720 return update_size(pb, pos);
723 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
726 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
727 int unescaped_size, seq_found = 0;
728 int level = 0, interlace = 0;
729 int packet_seq = track->vc1_info.packet_seq;
730 int packet_entry = track->vc1_info.packet_entry;
731 int slices = track->vc1_info.slices;
734 if (track->start_dts == AV_NOPTS_VALUE) {
735 /* No packets written yet, vc1_info isn't authoritative yet. */
736 /* Assume inline sequence and entry headers. */
737 packet_seq = packet_entry = 1;
738 av_log(NULL, AV_LOG_WARNING,
739 "moov atom written before any packets, unable to write correct "
740 "dvc1 atom. Set the delay_moov flag to fix this.\n");
743 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
745 return AVERROR(ENOMEM);
746 start = find_next_marker(track->vos_data, end);
747 for (next = start; next < end; start = next) {
750 next = find_next_marker(start + 4, end);
751 size = next - start - 4;
754 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
755 init_get_bits(&gb, unescaped, 8 * unescaped_size);
756 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
757 int profile = get_bits(&gb, 2);
758 if (profile != PROFILE_ADVANCED) {
760 return AVERROR(ENOSYS);
763 level = get_bits(&gb, 3);
764 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
766 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
767 skip_bits(&gb, 1); /* broadcast */
768 interlace = get_bits1(&gb);
769 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
774 return AVERROR(ENOSYS);
777 init_put_bits(&pbc, buf, 7);
778 /* VC1DecSpecStruc */
779 put_bits(&pbc, 4, 12); /* profile - advanced */
780 put_bits(&pbc, 3, level);
781 put_bits(&pbc, 1, 0); /* reserved */
782 /* VC1AdvDecSpecStruc */
783 put_bits(&pbc, 3, level);
784 put_bits(&pbc, 1, 0); /* cbr */
785 put_bits(&pbc, 6, 0); /* reserved */
786 put_bits(&pbc, 1, !interlace); /* no interlace */
787 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
788 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
789 put_bits(&pbc, 1, !slices); /* no slice code */
790 put_bits(&pbc, 1, 0); /* no bframe */
791 put_bits(&pbc, 1, 0); /* reserved */
794 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
795 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
797 put_bits32(&pbc, 0xffffffff);
799 flush_put_bits(&pbc);
806 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
808 uint8_t buf[7] = { 0 };
811 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
814 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
815 ffio_wfourcc(pb, "dvc1");
816 avio_write(pb, buf, sizeof(buf));
817 avio_write(pb, track->vos_data, track->vos_len);
822 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
824 avio_wb32(pb, track->vos_len + 8);
825 ffio_wfourcc(pb, "glbl");
826 avio_write(pb, track->vos_data, track->vos_len);
827 return 8 + track->vos_len;
831 * Compute flags for 'lpcm' tag.
832 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
834 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
837 case AV_CODEC_ID_PCM_F32BE:
838 case AV_CODEC_ID_PCM_F64BE:
840 case AV_CODEC_ID_PCM_F32LE:
841 case AV_CODEC_ID_PCM_F64LE:
843 case AV_CODEC_ID_PCM_U8:
845 case AV_CODEC_ID_PCM_S16BE:
846 case AV_CODEC_ID_PCM_S24BE:
847 case AV_CODEC_ID_PCM_S32BE:
849 case AV_CODEC_ID_PCM_S8:
850 case AV_CODEC_ID_PCM_S16LE:
851 case AV_CODEC_ID_PCM_S24LE:
852 case AV_CODEC_ID_PCM_S32LE:
859 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
863 if (cluster_idx >= track->entry)
866 if (cluster_idx + 1 == track->entry)
867 next_dts = track->track_duration + track->start_dts;
869 next_dts = track->cluster[cluster_idx + 1].dts;
871 next_dts -= track->cluster[cluster_idx].dts;
873 av_assert0(next_dts >= 0);
874 av_assert0(next_dts <= INT_MAX);
879 static int get_samples_per_packet(MOVTrack *track)
881 int i, first_duration;
883 // return track->par->frame_size;
885 /* use 1 for raw PCM */
886 if (!track->audio_vbr)
889 /* check to see if duration is constant for all clusters */
892 first_duration = get_cluster_duration(track, 0);
893 for (i = 1; i < track->entry; i++) {
894 if (get_cluster_duration(track, i) != first_duration)
897 return first_duration;
900 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
902 int64_t pos = avio_tell(pb);
904 uint32_t tag = track->tag;
906 if (track->mode == MODE_MOV) {
907 if (track->timescale > UINT16_MAX) {
908 if (mov_get_lpcm_flags(track->par->codec_id))
909 tag = AV_RL32("lpcm");
911 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
912 mov_pcm_be_gt16(track->par->codec_id) ||
913 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
914 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
915 track->par->codec_id == AV_CODEC_ID_QDM2) {
920 avio_wb32(pb, 0); /* size */
921 if (mov->encryption_scheme != MOV_ENC_NONE) {
922 ffio_wfourcc(pb, "enca");
924 avio_wl32(pb, tag); // store it byteswapped
926 avio_wb32(pb, 0); /* Reserved */
927 avio_wb16(pb, 0); /* Reserved */
928 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
930 /* SoundDescription */
931 avio_wb16(pb, version); /* Version */
932 avio_wb16(pb, 0); /* Revision level */
933 avio_wb32(pb, 0); /* Reserved */
938 avio_wb16(pb, 0xfffe);
940 avio_wb32(pb, 0x00010000);
942 avio_wb64(pb, av_double2int(track->par->sample_rate));
943 avio_wb32(pb, track->par->channels);
944 avio_wb32(pb, 0x7F000000);
945 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
946 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
947 avio_wb32(pb, track->sample_size);
948 avio_wb32(pb, get_samples_per_packet(track));
950 if (track->mode == MODE_MOV) {
951 avio_wb16(pb, track->par->channels);
952 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
953 track->par->codec_id == AV_CODEC_ID_PCM_S8)
954 avio_wb16(pb, 8); /* bits per sample */
955 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
956 avio_wb16(pb, track->par->bits_per_coded_sample);
959 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
960 } else { /* reserved for mp4/3gp */
966 avio_wb16(pb, 0); /* packet size (= 0) */
967 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
968 track->par->sample_rate : 0);
969 avio_wb16(pb, 0); /* Reserved */
972 if (version == 1) { /* SoundDescription V1 extended info */
973 if (mov_pcm_le_gt16(track->par->codec_id) ||
974 mov_pcm_be_gt16(track->par->codec_id))
975 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
977 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
978 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
979 avio_wb32(pb, track->sample_size); /* Bytes per frame */
980 avio_wb32(pb, 2); /* Bytes per sample */
983 if (track->mode == MODE_MOV &&
984 (track->par->codec_id == AV_CODEC_ID_AAC ||
985 track->par->codec_id == AV_CODEC_ID_AC3 ||
986 track->par->codec_id == AV_CODEC_ID_EAC3 ||
987 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
988 track->par->codec_id == AV_CODEC_ID_ALAC ||
989 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
990 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
991 track->par->codec_id == AV_CODEC_ID_QDM2 ||
992 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
993 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
994 mov_write_wave_tag(s, pb, track);
995 else if (track->tag == MKTAG('m','p','4','a'))
996 mov_write_esds_tag(pb, track);
997 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
998 mov_write_amr_tag(pb, track);
999 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1000 mov_write_ac3_tag(pb, track);
1001 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1002 mov_write_eac3_tag(pb, track);
1003 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1004 mov_write_extradata_tag(pb, track);
1005 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1006 mov_write_wfex_tag(s, pb, track);
1007 else if (track->vos_len > 0)
1008 mov_write_glbl_tag(pb, track);
1010 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1011 mov_write_chan_tag(s, pb, track);
1013 if (mov->encryption_scheme != MOV_ENC_NONE) {
1014 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1017 return update_size(pb, pos);
1020 static int mov_write_d263_tag(AVIOContext *pb)
1022 avio_wb32(pb, 0xf); /* size */
1023 ffio_wfourcc(pb, "d263");
1024 ffio_wfourcc(pb, "FFMP");
1025 avio_w8(pb, 0); /* decoder version */
1026 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1027 avio_w8(pb, 0xa); /* level */
1028 avio_w8(pb, 0); /* profile */
1032 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1034 int64_t pos = avio_tell(pb);
1037 ffio_wfourcc(pb, "avcC");
1038 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1039 return update_size(pb, pos);
1042 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1044 int64_t pos = avio_tell(pb);
1047 ffio_wfourcc(pb, "hvcC");
1048 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1049 return update_size(pb, pos);
1052 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1053 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1059 if (track->vos_data && track->vos_len > 0x29) {
1060 if (track->vos_data[0] == 0x00 &&
1061 track->vos_data[1] == 0x00 &&
1062 track->vos_data[2] == 0x02 &&
1063 track->vos_data[3] == 0x80 &&
1064 (track->vos_data[4] == 0x01 || track->vos_data[4] == 0x02)) {
1065 /* looks like a DNxHD bit stream */
1066 interlaced = (track->vos_data[5] & 2);
1067 cid = AV_RB32(track->vos_data + 0x28);
1069 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1073 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1077 avio_wb32(pb, 24); /* size */
1078 ffio_wfourcc(pb, "ACLR");
1079 ffio_wfourcc(pb, "ACLR");
1080 ffio_wfourcc(pb, "0001");
1081 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1082 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1083 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1084 } else { /* Full range (0-255) */
1085 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1087 avio_wb32(pb, 0); /* unknown */
1089 avio_wb32(pb, 24); /* size */
1090 ffio_wfourcc(pb, "APRG");
1091 ffio_wfourcc(pb, "APRG");
1092 ffio_wfourcc(pb, "0001");
1093 avio_wb32(pb, 1); /* unknown */
1094 avio_wb32(pb, 0); /* unknown */
1096 avio_wb32(pb, 120); /* size */
1097 ffio_wfourcc(pb, "ARES");
1098 ffio_wfourcc(pb, "ARES");
1099 ffio_wfourcc(pb, "0001");
1100 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1101 avio_wb32(pb, track->par->width);
1102 /* values below are based on samples created with quicktime and avid codecs */
1104 avio_wb32(pb, track->par->height / 2);
1105 avio_wb32(pb, 2); /* unknown */
1106 avio_wb32(pb, 0); /* unknown */
1107 avio_wb32(pb, 4); /* unknown */
1109 avio_wb32(pb, track->par->height);
1110 avio_wb32(pb, 1); /* unknown */
1111 avio_wb32(pb, 0); /* unknown */
1112 if (track->par->height == 1080)
1113 avio_wb32(pb, 5); /* unknown */
1115 avio_wb32(pb, 6); /* unknown */
1118 for (i = 0; i < 10; i++)
1124 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1127 ffio_wfourcc(pb, "DpxE");
1128 if (track->par->extradata_size >= 12 &&
1129 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1130 avio_wb32(pb, track->par->extradata[11]);
1137 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1139 int tag = track->par->codec_tag;
1141 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
1144 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1145 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1146 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1147 else if (track->par->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1148 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1149 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1150 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1151 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1152 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1153 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1158 static const AVCodecTag codec_ipod_tags[] = {
1159 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1160 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1161 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1162 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1163 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1164 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1165 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1166 { AV_CODEC_ID_NONE, 0 },
1169 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1171 int tag = track->par->codec_tag;
1173 // keep original tag for subs, ipod supports both formats
1174 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1175 (tag == MKTAG('t', 'x', '3', 'g') ||
1176 tag == MKTAG('t', 'e', 'x', 't'))))
1177 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
1179 if (!av_match_ext(s->filename, "m4a") &&
1180 !av_match_ext(s->filename, "m4b") &&
1181 !av_match_ext(s->filename, "m4v"))
1182 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1183 "Quicktime/Ipod might not play the file\n");
1188 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1192 if (track->par->width == 720) { /* SD */
1193 if (track->par->height == 480) { /* NTSC */
1194 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1195 else tag = MKTAG('d','v','c',' ');
1196 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1197 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1198 else tag = MKTAG('d','v','p','p');
1199 } else if (track->par->height == 720) { /* HD 720 line */
1200 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1201 else tag = MKTAG('d','v','h','p');
1202 } else if (track->par->height == 1080) { /* HD 1080 line */
1203 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1204 else tag = MKTAG('d','v','h','6');
1206 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1213 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1215 AVRational rate = st->avg_frame_rate;
1217 #if FF_API_LAVF_AVCTX
1218 FF_DISABLE_DEPRECATION_WARNINGS
1219 rate = av_inv_q(st->codec->time_base);
1220 if (av_timecode_check_frame_rate(rate) < 0) {
1221 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1222 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1223 rate = st->avg_frame_rate;
1225 FF_ENABLE_DEPRECATION_WARNINGS
1231 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1233 int tag = track->par->codec_tag;
1234 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1235 AVStream *st = track->st;
1236 int rate = av_q2d(find_fps(s, st));
1239 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1241 if (track->par->format == AV_PIX_FMT_YUV420P) {
1242 if (track->par->width == 1280 && track->par->height == 720) {
1244 if (rate == 24) tag = MKTAG('x','d','v','4');
1245 else if (rate == 25) tag = MKTAG('x','d','v','5');
1246 else if (rate == 30) tag = MKTAG('x','d','v','1');
1247 else if (rate == 50) tag = MKTAG('x','d','v','a');
1248 else if (rate == 60) tag = MKTAG('x','d','v','9');
1250 } else if (track->par->width == 1440 && track->par->height == 1080) {
1252 if (rate == 24) tag = MKTAG('x','d','v','6');
1253 else if (rate == 25) tag = MKTAG('x','d','v','7');
1254 else if (rate == 30) tag = MKTAG('x','d','v','8');
1256 if (rate == 25) tag = MKTAG('x','d','v','3');
1257 else if (rate == 30) tag = MKTAG('x','d','v','2');
1259 } else if (track->par->width == 1920 && track->par->height == 1080) {
1261 if (rate == 24) tag = MKTAG('x','d','v','d');
1262 else if (rate == 25) tag = MKTAG('x','d','v','e');
1263 else if (rate == 30) tag = MKTAG('x','d','v','f');
1265 if (rate == 25) tag = MKTAG('x','d','v','c');
1266 else if (rate == 30) tag = MKTAG('x','d','v','b');
1269 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1270 if (track->par->width == 1280 && track->par->height == 720) {
1272 if (rate == 24) tag = MKTAG('x','d','5','4');
1273 else if (rate == 25) tag = MKTAG('x','d','5','5');
1274 else if (rate == 30) tag = MKTAG('x','d','5','1');
1275 else if (rate == 50) tag = MKTAG('x','d','5','a');
1276 else if (rate == 60) tag = MKTAG('x','d','5','9');
1278 } else if (track->par->width == 1920 && track->par->height == 1080) {
1280 if (rate == 24) tag = MKTAG('x','d','5','d');
1281 else if (rate == 25) tag = MKTAG('x','d','5','e');
1282 else if (rate == 30) tag = MKTAG('x','d','5','f');
1284 if (rate == 25) tag = MKTAG('x','d','5','c');
1285 else if (rate == 30) tag = MKTAG('x','d','5','b');
1293 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1295 int tag = track->par->codec_tag;
1296 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1297 AVStream *st = track->st;
1298 int rate = av_q2d(find_fps(s, st));
1301 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1303 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1304 if (track->par->width == 960 && track->par->height == 720) {
1306 if (rate == 24) tag = MKTAG('a','i','5','p');
1307 else if (rate == 25) tag = MKTAG('a','i','5','q');
1308 else if (rate == 30) tag = MKTAG('a','i','5','p');
1309 else if (rate == 50) tag = MKTAG('a','i','5','q');
1310 else if (rate == 60) tag = MKTAG('a','i','5','p');
1312 } else if (track->par->width == 1440 && track->par->height == 1080) {
1314 if (rate == 24) tag = MKTAG('a','i','5','3');
1315 else if (rate == 25) tag = MKTAG('a','i','5','2');
1316 else if (rate == 30) tag = MKTAG('a','i','5','3');
1318 if (rate == 50) tag = MKTAG('a','i','5','5');
1319 else if (rate == 60) tag = MKTAG('a','i','5','6');
1322 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1323 if (track->par->width == 1280 && track->par->height == 720) {
1325 if (rate == 24) tag = MKTAG('a','i','1','p');
1326 else if (rate == 25) tag = MKTAG('a','i','1','q');
1327 else if (rate == 30) tag = MKTAG('a','i','1','p');
1328 else if (rate == 50) tag = MKTAG('a','i','1','q');
1329 else if (rate == 60) tag = MKTAG('a','i','1','p');
1331 } else if (track->par->width == 1920 && track->par->height == 1080) {
1333 if (rate == 24) tag = MKTAG('a','i','1','3');
1334 else if (rate == 25) tag = MKTAG('a','i','1','2');
1335 else if (rate == 30) tag = MKTAG('a','i','1','3');
1337 if (rate == 25) tag = MKTAG('a','i','1','5');
1338 else if (rate == 50) tag = MKTAG('a','i','1','5');
1339 else if (rate == 60) tag = MKTAG('a','i','1','6');
1341 } else if ( track->par->width == 4096 && track->par->height == 2160
1342 || track->par->width == 3840 && track->par->height == 2160
1343 || track->par->width == 2048 && track->par->height == 1080) {
1344 tag = MKTAG('a','i','v','x');
1351 static const struct {
1352 enum AVPixelFormat pix_fmt;
1355 } mov_pix_fmt_tags[] = {
1356 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1357 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1358 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1359 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1360 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1361 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1362 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1363 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1364 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1365 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1366 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1367 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1368 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1369 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1370 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1373 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1375 int tag = track->par->codec_tag;
1377 enum AVPixelFormat pix_fmt;
1379 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1380 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1381 tag = mov_pix_fmt_tags[i].tag;
1382 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1383 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1388 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1389 track->par->bits_per_coded_sample);
1390 if (tag == MKTAG('r','a','w',' ') &&
1391 track->par->format != pix_fmt &&
1392 track->par->format != AV_PIX_FMT_NONE)
1393 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1394 av_get_pix_fmt_name(track->par->format));
1398 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1400 int tag = track->par->codec_tag;
1402 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1403 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1404 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1405 track->par->codec_id == AV_CODEC_ID_H263 ||
1406 track->par->codec_id == AV_CODEC_ID_H264 ||
1407 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1408 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1409 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1410 tag = mov_get_dv_codec_tag(s, track);
1411 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1412 tag = mov_get_rawvideo_codec_tag(s, track);
1413 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1414 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1415 else if (track->par->codec_id == AV_CODEC_ID_H264)
1416 tag = mov_get_h264_codec_tag(s, track);
1417 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1418 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1419 if (!tag) { // if no mac fcc found, try with Microsoft tags
1420 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1422 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1423 "the file may be unplayable!\n");
1425 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1426 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1427 if (!tag) { // if no mac fcc found, try with Microsoft tags
1428 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1430 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1431 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1432 "the file may be unplayable!\n");
1435 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1436 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1442 static const AVCodecTag codec_3gp_tags[] = {
1443 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1444 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1445 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1446 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1447 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1448 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1449 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1450 { AV_CODEC_ID_NONE, 0 },
1453 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1454 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1455 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1456 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1457 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1458 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1459 { AV_CODEC_ID_NONE, 0 },
1462 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1466 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1467 tag = mp4_get_codec_tag(s, track);
1468 else if (track->mode == MODE_ISM) {
1469 tag = mp4_get_codec_tag(s, track);
1470 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
1471 tag = MKTAG('w', 'm', 'a', ' ');
1472 } else if (track->mode == MODE_IPOD)
1473 tag = ipod_get_codec_tag(s, track);
1474 else if (track->mode & MODE_3GP)
1475 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
1476 else if (track->mode == MODE_F4V)
1477 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
1479 tag = mov_get_codec_tag(s, track);
1484 /** Write uuid atom.
1485 * Needed to make file play in iPods running newest firmware
1486 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1488 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1491 ffio_wfourcc(pb, "uuid");
1492 avio_wb32(pb, 0x6b6840f2);
1493 avio_wb32(pb, 0x5f244fc5);
1494 avio_wb32(pb, 0xba39a51b);
1495 avio_wb32(pb, 0xcf0323f3);
1500 static const uint16_t fiel_data[] = {
1501 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1504 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1506 unsigned mov_field_order = 0;
1507 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1508 mov_field_order = fiel_data[field_order];
1512 ffio_wfourcc(pb, "fiel");
1513 avio_wb16(pb, mov_field_order);
1517 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1519 int64_t pos = avio_tell(pb);
1520 avio_wb32(pb, 0); /* size */
1521 avio_wl32(pb, track->tag); // store it byteswapped
1522 avio_wb32(pb, 0); /* Reserved */
1523 avio_wb16(pb, 0); /* Reserved */
1524 avio_wb16(pb, 1); /* Data-reference index */
1526 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1527 mov_write_esds_tag(pb, track);
1528 else if (track->par->extradata_size)
1529 avio_write(pb, track->par->extradata, track->par->extradata_size);
1531 return update_size(pb, pos);
1534 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1537 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1538 track->par->sample_aspect_ratio.den, INT_MAX);
1541 ffio_wfourcc(pb, "pasp");
1542 avio_wb32(pb, sar.num);
1543 avio_wb32(pb, sar.den);
1547 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1552 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1554 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1557 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1558 av_log(pb, AV_LOG_DEBUG, "writing gama value %d\n", gama);
1560 av_assert0(track->mode == MODE_MOV);
1562 ffio_wfourcc(pb, "gama");
1563 avio_wb32(pb, gama);
1567 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1572 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1574 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1575 // Ref (MP4): ISO/IEC 14496-12:2012
1577 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1578 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1579 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1580 if ((track->par->width >= 1920 && track->par->height >= 1080)
1581 || (track->par->width == 1280 && track->par->height == 720)) {
1582 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1583 track->par->color_primaries = AVCOL_PRI_BT709;
1584 } else if (track->par->width == 720 && track->height == 576) {
1585 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1586 track->par->color_primaries = AVCOL_PRI_BT470BG;
1587 } else if (track->par->width == 720 &&
1588 (track->height == 486 || track->height == 480)) {
1589 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1590 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1592 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1594 switch (track->par->color_primaries) {
1595 case AVCOL_PRI_BT709:
1596 track->par->color_trc = AVCOL_TRC_BT709;
1597 track->par->color_space = AVCOL_SPC_BT709;
1599 case AVCOL_PRI_SMPTE170M:
1600 case AVCOL_PRI_BT470BG:
1601 track->par->color_trc = AVCOL_TRC_BT709;
1602 track->par->color_space = AVCOL_SPC_SMPTE170M;
1607 /* We should only ever be called by MOV or MP4. */
1608 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1610 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1611 ffio_wfourcc(pb, "colr");
1612 if (track->mode == MODE_MP4)
1613 ffio_wfourcc(pb, "nclx");
1615 ffio_wfourcc(pb, "nclc");
1616 switch (track->par->color_primaries) {
1617 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1618 case AVCOL_PRI_SMPTE170M:
1619 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1620 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1621 default: avio_wb16(pb, 2);
1623 switch (track->par->color_trc) {
1624 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1625 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1626 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1627 default: avio_wb16(pb, 2);
1629 switch (track->par->color_space) {
1630 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1631 case AVCOL_SPC_BT470BG:
1632 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1633 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1634 default: avio_wb16(pb, 2);
1637 if (track->mode == MODE_MP4) {
1638 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1639 avio_w8(pb, full_range << 7);
1646 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1648 AVDictionaryEntry *encoder;
1649 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1650 || (track->par->width == 1440 && track->par->height == 1080)
1651 || (track->par->width == 1920 && track->par->height == 1080);
1653 if (track->mode == MODE_MOV &&
1654 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1655 av_strlcpy(compressor_name, encoder->value, 32);
1656 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1657 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1658 AVStream *st = track->st;
1659 int rate = av_q2d(find_fps(NULL, st));
1660 av_strlcatf(compressor_name, len, "XDCAM");
1661 if (track->par->format == AV_PIX_FMT_YUV422P) {
1662 av_strlcatf(compressor_name, len, " HD422");
1663 } else if(track->par->width == 1440) {
1664 av_strlcatf(compressor_name, len, " HD");
1666 av_strlcatf(compressor_name, len, " EX");
1668 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1670 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1674 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1676 int64_t pos = avio_tell(pb);
1677 char compressor_name[32] = { 0 };
1680 avio_wb32(pb, 0); /* size */
1681 if (mov->encryption_scheme != MOV_ENC_NONE) {
1682 ffio_wfourcc(pb, "encv");
1684 avio_wl32(pb, track->tag); // store it byteswapped
1686 avio_wb32(pb, 0); /* Reserved */
1687 avio_wb16(pb, 0); /* Reserved */
1688 avio_wb16(pb, 1); /* Data-reference index */
1690 avio_wb16(pb, 0); /* Codec stream version */
1691 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1692 if (track->mode == MODE_MOV) {
1693 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1694 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1695 avio_wb32(pb, 0); /* Temporal Quality */
1696 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1698 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1699 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1702 avio_wb32(pb, 0); /* Reserved */
1703 avio_wb32(pb, 0); /* Reserved */
1704 avio_wb32(pb, 0); /* Reserved */
1706 avio_wb16(pb, track->par->width); /* Video width */
1707 avio_wb16(pb, track->height); /* Video height */
1708 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1709 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1710 avio_wb32(pb, 0); /* Data size (= 0) */
1711 avio_wb16(pb, 1); /* Frame count (= 1) */
1713 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1714 find_compressor(compressor_name, 32, track);
1715 avio_w8(pb, strlen(compressor_name));
1716 avio_write(pb, compressor_name, 31);
1718 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1719 avio_wb16(pb, track->par->bits_per_coded_sample |
1720 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1722 avio_wb16(pb, 0x18); /* Reserved */
1724 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1725 int pal_size = 1 << track->par->bits_per_coded_sample;
1727 avio_wb16(pb, 0); /* Color table ID */
1728 avio_wb32(pb, 0); /* Color table seed */
1729 avio_wb16(pb, 0x8000); /* Color table flags */
1730 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1731 for (i = 0; i < pal_size; i++) {
1732 uint32_t rgb = track->palette[i];
1733 uint16_t r = (rgb >> 16) & 0xff;
1734 uint16_t g = (rgb >> 8) & 0xff;
1735 uint16_t b = rgb & 0xff;
1737 avio_wb16(pb, (r << 8) | r);
1738 avio_wb16(pb, (g << 8) | g);
1739 avio_wb16(pb, (b << 8) | b);
1742 avio_wb16(pb, 0xffff); /* Reserved */
1744 if (track->tag == MKTAG('m','p','4','v'))
1745 mov_write_esds_tag(pb, track);
1746 else if (track->par->codec_id == AV_CODEC_ID_H263)
1747 mov_write_d263_tag(pb);
1748 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1749 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1750 mov_write_extradata_tag(pb, track);
1752 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1753 mov_write_avid_tag(pb, track);
1755 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1756 mov_write_hvcc_tag(pb, track);
1757 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1758 mov_write_avcc_tag(pb, track);
1759 if (track->mode == MODE_IPOD)
1760 mov_write_uuid_tag_ipod(pb);
1761 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1762 mov_write_dvc1_tag(pb, track);
1763 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1764 track->par->codec_id == AV_CODEC_ID_VP6A) {
1765 /* Don't write any potential extradata here - the cropping
1766 * is signalled via the normal width/height fields. */
1767 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1768 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1769 mov_write_dpxe_tag(pb, track);
1770 } else if (track->vos_len > 0)
1771 mov_write_glbl_tag(pb, track);
1773 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1774 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1775 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1776 int field_order = track->par->field_order;
1778 #if FF_API_LAVF_AVCTX
1779 FF_DISABLE_DEPRECATION_WARNINGS
1780 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1781 field_order = track->st->codec->field_order;
1782 FF_ENABLE_DEPRECATION_WARNINGS
1785 if (field_order != AV_FIELD_UNKNOWN)
1786 mov_write_fiel_tag(pb, track, field_order);
1789 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1790 if (track->mode == MODE_MOV)
1791 mov_write_gama_tag(pb, track, mov->gamma);
1793 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1795 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1796 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1797 mov_write_colr_tag(pb, track);
1799 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1802 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num &&
1803 track->par->sample_aspect_ratio.den != track->par->sample_aspect_ratio.num) {
1804 mov_write_pasp_tag(pb, track);
1807 if (mov->encryption_scheme != MOV_ENC_NONE) {
1808 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1811 /* extra padding for avid stsd */
1812 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1816 return update_size(pb, pos);
1819 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1821 int64_t pos = avio_tell(pb);
1822 avio_wb32(pb, 0); /* size */
1823 ffio_wfourcc(pb, "rtp ");
1824 avio_wb32(pb, 0); /* Reserved */
1825 avio_wb16(pb, 0); /* Reserved */
1826 avio_wb16(pb, 1); /* Data-reference index */
1828 avio_wb16(pb, 1); /* Hint track version */
1829 avio_wb16(pb, 1); /* Highest compatible version */
1830 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1832 avio_wb32(pb, 12); /* size */
1833 ffio_wfourcc(pb, "tims");
1834 avio_wb32(pb, track->timescale);
1836 return update_size(pb, pos);
1839 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1841 uint64_t str_size =strlen(reel_name);
1842 int64_t pos = avio_tell(pb);
1844 if (str_size >= UINT16_MAX){
1845 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1847 return AVERROR(EINVAL);
1850 avio_wb32(pb, 0); /* size */
1851 ffio_wfourcc(pb, "name"); /* Data format */
1852 avio_wb16(pb, str_size); /* string size */
1853 avio_wb16(pb, track->language); /* langcode */
1854 avio_write(pb, reel_name, str_size); /* reel name */
1855 return update_size(pb,pos);
1858 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1860 int64_t pos = avio_tell(pb);
1864 AVDictionaryEntry *t = NULL;
1866 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
1867 #if FF_API_LAVF_AVCTX
1868 FF_DISABLE_DEPRECATION_WARNINGS
1869 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
1870 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
1871 FF_ENABLE_DEPRECATION_WARNINGS
1873 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
1874 return AVERROR(EINVAL);
1877 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
1878 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
1881 if (nb_frames > 255) {
1882 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1883 return AVERROR(EINVAL);
1886 avio_wb32(pb, 0); /* size */
1887 ffio_wfourcc(pb, "tmcd"); /* Data format */
1888 avio_wb32(pb, 0); /* Reserved */
1889 avio_wb32(pb, 1); /* Data reference index */
1890 avio_wb32(pb, 0); /* Flags */
1891 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1892 avio_wb32(pb, track->timescale); /* Timescale */
1893 avio_wb32(pb, frame_duration); /* Frame duration */
1894 avio_w8(pb, nb_frames); /* Number of frames */
1895 avio_w8(pb, 0); /* Reserved */
1898 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1900 if (t && utf8len(t->value) && track->mode != MODE_MP4)
1901 mov_write_source_reference_tag(pb, track, t->value);
1903 avio_wb16(pb, 0); /* zero size */
1906 avio_wb32(pb, 0); /* size */
1907 ffio_wfourcc(pb, "tmcd"); /* Data format */
1908 avio_wb32(pb, 0); /* Reserved */
1909 avio_wb32(pb, 1); /* Data reference index */
1910 if (track->par->extradata_size)
1911 avio_write(pb, track->par->extradata, track->par->extradata_size);
1913 return update_size(pb, pos);
1916 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1918 int64_t pos = avio_tell(pb);
1919 avio_wb32(pb, 0); /* size */
1920 ffio_wfourcc(pb, "stsd");
1921 avio_wb32(pb, 0); /* version & flags */
1922 avio_wb32(pb, 1); /* entry count */
1923 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
1924 mov_write_video_tag(pb, mov, track);
1925 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1926 mov_write_audio_tag(s, pb, mov, track);
1927 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1928 mov_write_subtitle_tag(pb, track);
1929 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
1930 mov_write_rtp_tag(pb, track);
1931 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
1932 mov_write_tmcd_tag(pb, track);
1933 return update_size(pb, pos);
1936 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1938 MOVStts *ctts_entries;
1939 uint32_t entries = 0;
1943 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1945 return AVERROR(ENOMEM);
1946 ctts_entries[0].count = 1;
1947 ctts_entries[0].duration = track->cluster[0].cts;
1948 for (i = 1; i < track->entry; i++) {
1949 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1950 ctts_entries[entries].count++; /* compress */
1953 ctts_entries[entries].duration = track->cluster[i].cts;
1954 ctts_entries[entries].count = 1;
1957 entries++; /* last one */
1958 atom_size = 16 + (entries * 8);
1959 avio_wb32(pb, atom_size); /* size */
1960 ffio_wfourcc(pb, "ctts");
1961 avio_wb32(pb, 0); /* version & flags */
1962 avio_wb32(pb, entries); /* entry count */
1963 for (i = 0; i < entries; i++) {
1964 avio_wb32(pb, ctts_entries[i].count);
1965 avio_wb32(pb, ctts_entries[i].duration);
1967 av_free(ctts_entries);
1971 /* Time to sample atom */
1972 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1974 MOVStts *stts_entries = NULL;
1975 uint32_t entries = -1;
1979 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1980 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1982 return AVERROR(ENOMEM);
1983 stts_entries[0].count = track->sample_count;
1984 stts_entries[0].duration = 1;
1988 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
1990 return AVERROR(ENOMEM);
1992 for (i = 0; i < track->entry; i++) {
1993 int duration = get_cluster_duration(track, i);
1994 if (i && duration == stts_entries[entries].duration) {
1995 stts_entries[entries].count++; /* compress */
1998 stts_entries[entries].duration = duration;
1999 stts_entries[entries].count = 1;
2002 entries++; /* last one */
2004 atom_size = 16 + (entries * 8);
2005 avio_wb32(pb, atom_size); /* size */
2006 ffio_wfourcc(pb, "stts");
2007 avio_wb32(pb, 0); /* version & flags */
2008 avio_wb32(pb, entries); /* entry count */
2009 for (i = 0; i < entries; i++) {
2010 avio_wb32(pb, stts_entries[i].count);
2011 avio_wb32(pb, stts_entries[i].duration);
2013 av_free(stts_entries);
2017 static int mov_write_dref_tag(AVIOContext *pb)
2019 avio_wb32(pb, 28); /* size */
2020 ffio_wfourcc(pb, "dref");
2021 avio_wb32(pb, 0); /* version & flags */
2022 avio_wb32(pb, 1); /* entry count */
2024 avio_wb32(pb, 0xc); /* size */
2025 //FIXME add the alis and rsrc atom
2026 ffio_wfourcc(pb, "url ");
2027 avio_wb32(pb, 1); /* version & flags */
2032 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2034 int64_t pos = avio_tell(pb);
2037 avio_wb32(pb, 0); /* size */
2038 ffio_wfourcc(pb, "stbl");
2039 mov_write_stsd_tag(s, pb, mov, track);
2040 mov_write_stts_tag(pb, track);
2041 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2042 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2043 track->has_keyframes && track->has_keyframes < track->entry)
2044 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2045 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2046 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2047 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2048 track->flags & MOV_TRACK_CTTS && track->entry) {
2050 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2053 mov_write_stsc_tag(pb, track);
2054 mov_write_stsz_tag(pb, track);
2055 mov_write_stco_tag(pb, track);
2056 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
2057 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2059 return update_size(pb, pos);
2062 static int mov_write_dinf_tag(AVIOContext *pb)
2064 int64_t pos = avio_tell(pb);
2065 avio_wb32(pb, 0); /* size */
2066 ffio_wfourcc(pb, "dinf");
2067 mov_write_dref_tag(pb);
2068 return update_size(pb, pos);
2071 static int mov_write_nmhd_tag(AVIOContext *pb)
2074 ffio_wfourcc(pb, "nmhd");
2079 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2081 int64_t pos = avio_tell(pb);
2082 const char *font = "Lucida Grande";
2083 avio_wb32(pb, 0); /* size */
2084 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2085 avio_wb32(pb, 0); /* version & flags */
2086 avio_wb16(pb, 0); /* text font */
2087 avio_wb16(pb, 0); /* text face */
2088 avio_wb16(pb, 12); /* text size */
2089 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2090 avio_wb16(pb, 0x0000); /* text color (red) */
2091 avio_wb16(pb, 0x0000); /* text color (green) */
2092 avio_wb16(pb, 0x0000); /* text color (blue) */
2093 avio_wb16(pb, 0xffff); /* background color (red) */
2094 avio_wb16(pb, 0xffff); /* background color (green) */
2095 avio_wb16(pb, 0xffff); /* background color (blue) */
2096 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2097 avio_write(pb, font, strlen(font)); /* font name */
2098 return update_size(pb, pos);
2101 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2103 int64_t pos = avio_tell(pb);
2104 avio_wb32(pb, 0); /* size */
2105 ffio_wfourcc(pb, "gmhd");
2106 avio_wb32(pb, 0x18); /* gmin size */
2107 ffio_wfourcc(pb, "gmin");/* generic media info */
2108 avio_wb32(pb, 0); /* version & flags */
2109 avio_wb16(pb, 0x40); /* graphics mode = */
2110 avio_wb16(pb, 0x8000); /* opColor (r?) */
2111 avio_wb16(pb, 0x8000); /* opColor (g?) */
2112 avio_wb16(pb, 0x8000); /* opColor (b?) */
2113 avio_wb16(pb, 0); /* balance */
2114 avio_wb16(pb, 0); /* reserved */
2117 * This special text atom is required for
2118 * Apple Quicktime chapters. The contents
2119 * don't appear to be documented, so the
2120 * bytes are copied verbatim.
2122 if (track->tag != MKTAG('c','6','0','8')) {
2123 avio_wb32(pb, 0x2C); /* size */
2124 ffio_wfourcc(pb, "text");
2125 avio_wb16(pb, 0x01);
2126 avio_wb32(pb, 0x00);
2127 avio_wb32(pb, 0x00);
2128 avio_wb32(pb, 0x00);
2129 avio_wb32(pb, 0x01);
2130 avio_wb32(pb, 0x00);
2131 avio_wb32(pb, 0x00);
2132 avio_wb32(pb, 0x00);
2133 avio_wb32(pb, 0x00004000);
2134 avio_wb16(pb, 0x0000);
2137 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2138 int64_t tmcd_pos = avio_tell(pb);
2139 avio_wb32(pb, 0); /* size */
2140 ffio_wfourcc(pb, "tmcd");
2141 mov_write_tcmi_tag(pb, track);
2142 update_size(pb, tmcd_pos);
2144 return update_size(pb, pos);
2147 static int mov_write_smhd_tag(AVIOContext *pb)
2149 avio_wb32(pb, 16); /* size */
2150 ffio_wfourcc(pb, "smhd");
2151 avio_wb32(pb, 0); /* version & flags */
2152 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2153 avio_wb16(pb, 0); /* reserved */
2157 static int mov_write_vmhd_tag(AVIOContext *pb)
2159 avio_wb32(pb, 0x14); /* size (always 0x14) */
2160 ffio_wfourcc(pb, "vmhd");
2161 avio_wb32(pb, 0x01); /* version & flags */
2162 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2166 static int is_clcp_track(MOVTrack *track)
2168 return track->tag == MKTAG('c','7','0','8') ||
2169 track->tag == MKTAG('c','6','0','8');
2172 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2174 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2175 int64_t pos = avio_tell(pb);
2179 descr = "DataHandler";
2182 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2183 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2185 descr = "VideoHandler";
2186 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2188 descr = "SoundHandler";
2189 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2190 if (is_clcp_track(track)) {
2192 descr = "ClosedCaptionHandler";
2194 if (track->tag == MKTAG('t','x','3','g')) {
2196 } else if (track->tag == MKTAG('m','p','4','s')) {
2201 descr = "SubtitleHandler";
2203 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2205 descr = "HintHandler";
2206 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2208 descr = "TimeCodeHandler";
2211 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
2212 track->par->codec_tag);
2214 av_log(s, AV_LOG_WARNING,
2215 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
2216 tag_buf, track->par->codec_tag);
2219 // hdlr.name is used by some players to identify the content title
2220 // of the track. So if an alternate handler description is
2221 // specified, use it.
2222 AVDictionaryEntry *t;
2223 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2224 if (t && utf8len(t->value))
2229 avio_wb32(pb, 0); /* size */
2230 ffio_wfourcc(pb, "hdlr");
2231 avio_wb32(pb, 0); /* Version & flags */
2232 avio_write(pb, hdlr, 4); /* handler */
2233 ffio_wfourcc(pb, hdlr_type); /* handler type */
2234 avio_wb32(pb, 0); /* reserved */
2235 avio_wb32(pb, 0); /* reserved */
2236 avio_wb32(pb, 0); /* reserved */
2237 if (!track || track->mode == MODE_MOV)
2238 avio_w8(pb, strlen(descr)); /* pascal string */
2239 avio_write(pb, descr, strlen(descr)); /* handler description */
2240 if (track && track->mode != MODE_MOV)
2241 avio_w8(pb, 0); /* c string */
2242 return update_size(pb, pos);
2245 static int mov_write_hmhd_tag(AVIOContext *pb)
2247 /* This atom must be present, but leaving the values at zero
2248 * seems harmless. */
2249 avio_wb32(pb, 28); /* size */
2250 ffio_wfourcc(pb, "hmhd");
2251 avio_wb32(pb, 0); /* version, flags */
2252 avio_wb16(pb, 0); /* maxPDUsize */
2253 avio_wb16(pb, 0); /* avgPDUsize */
2254 avio_wb32(pb, 0); /* maxbitrate */
2255 avio_wb32(pb, 0); /* avgbitrate */
2256 avio_wb32(pb, 0); /* reserved */
2260 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2262 int64_t pos = avio_tell(pb);
2265 avio_wb32(pb, 0); /* size */
2266 ffio_wfourcc(pb, "minf");
2267 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2268 mov_write_vmhd_tag(pb);
2269 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2270 mov_write_smhd_tag(pb);
2271 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2272 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2273 mov_write_gmhd_tag(pb, track);
2275 mov_write_nmhd_tag(pb);
2277 } else if (track->tag == MKTAG('r','t','p',' ')) {
2278 mov_write_hmhd_tag(pb);
2279 } else if (track->tag == MKTAG('t','m','c','d')) {
2280 if (track->mode == MODE_MP4)
2281 mov_write_nmhd_tag(pb);
2283 mov_write_gmhd_tag(pb, track);
2285 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2286 mov_write_hdlr_tag(s, pb, NULL);
2287 mov_write_dinf_tag(pb);
2288 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2290 return update_size(pb, pos);
2293 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2296 int version = track->track_duration < INT32_MAX ? 0 : 1;
2298 if (track->mode == MODE_ISM)
2301 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2302 ffio_wfourcc(pb, "mdhd");
2303 avio_w8(pb, version);
2304 avio_wb24(pb, 0); /* flags */
2306 avio_wb64(pb, track->time);
2307 avio_wb64(pb, track->time);
2309 avio_wb32(pb, track->time); /* creation time */
2310 avio_wb32(pb, track->time); /* modification time */
2312 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2313 if (!track->entry && mov->mode == MODE_ISM)
2314 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2315 else if (!track->entry)
2316 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2318 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2319 avio_wb16(pb, track->language); /* language */
2320 avio_wb16(pb, 0); /* reserved (quality) */
2322 if (version != 0 && track->mode == MODE_MOV) {
2323 av_log(NULL, AV_LOG_ERROR,
2324 "FATAL error, file duration too long for timebase, this file will not be\n"
2325 "playable with quicktime. Choose a different timebase or a different\n"
2326 "container format\n");
2332 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2333 MOVMuxContext *mov, MOVTrack *track)
2335 int64_t pos = avio_tell(pb);
2338 avio_wb32(pb, 0); /* size */
2339 ffio_wfourcc(pb, "mdia");
2340 mov_write_mdhd_tag(pb, mov, track);
2341 mov_write_hdlr_tag(s, pb, track);
2342 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2344 return update_size(pb, pos);
2347 /* transformation matrix
2351 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2352 int16_t d, int16_t tx, int16_t ty)
2354 avio_wb32(pb, a << 16); /* 16.16 format */
2355 avio_wb32(pb, b << 16); /* 16.16 format */
2356 avio_wb32(pb, 0); /* u in 2.30 format */
2357 avio_wb32(pb, c << 16); /* 16.16 format */
2358 avio_wb32(pb, d << 16); /* 16.16 format */
2359 avio_wb32(pb, 0); /* v in 2.30 format */
2360 avio_wb32(pb, tx << 16); /* 16.16 format */
2361 avio_wb32(pb, ty << 16); /* 16.16 format */
2362 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2365 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2366 MOVTrack *track, AVStream *st)
2368 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2369 track->timescale, AV_ROUND_UP);
2370 int version = duration < INT32_MAX ? 0 : 1;
2371 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2375 uint32_t *display_matrix = NULL;
2376 int display_matrix_size, i;
2379 if (mov->per_stream_grouping)
2382 group = st->codecpar->codec_type;
2384 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2385 &display_matrix_size);
2386 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2387 display_matrix = NULL;
2390 if (track->flags & MOV_TRACK_ENABLED)
2391 flags |= MOV_TKHD_FLAG_ENABLED;
2393 if (track->mode == MODE_ISM)
2396 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2397 ffio_wfourcc(pb, "tkhd");
2398 avio_w8(pb, version);
2399 avio_wb24(pb, flags);
2401 avio_wb64(pb, track->time);
2402 avio_wb64(pb, track->time);
2404 avio_wb32(pb, track->time); /* creation time */
2405 avio_wb32(pb, track->time); /* modification time */
2407 avio_wb32(pb, track->track_id); /* track-id */
2408 avio_wb32(pb, 0); /* reserved */
2409 if (!track->entry && mov->mode == MODE_ISM)
2410 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2411 else if (!track->entry)
2412 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2414 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2416 avio_wb32(pb, 0); /* reserved */
2417 avio_wb32(pb, 0); /* reserved */
2418 avio_wb16(pb, 0); /* layer */
2419 avio_wb16(pb, group); /* alternate group) */
2420 /* Volume, only for audio */
2421 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2422 avio_wb16(pb, 0x0100);
2425 avio_wb16(pb, 0); /* reserved */
2427 /* Matrix structure */
2428 if (st && st->metadata) {
2429 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2430 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2432 if (display_matrix) {
2433 for (i = 0; i < 9; i++)
2434 avio_wb32(pb, display_matrix[i]);
2435 } else if (rotation == 90) {
2436 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2437 } else if (rotation == 180) {
2438 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2439 } else if (rotation == 270) {
2440 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2442 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2444 /* Track width and height, for visual only */
2445 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2446 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2447 if (track->mode == MODE_MOV) {
2448 avio_wb32(pb, track->par->width << 16);
2449 avio_wb32(pb, track->height << 16);
2451 int64_t track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2452 track->par->width * 0x10000LL,
2453 st->sample_aspect_ratio.den);
2454 if (!track_width_1616 ||
2455 track->height != track->par->height ||
2456 track_width_1616 > UINT32_MAX)
2457 track_width_1616 = track->par->width * 0x10000U;
2458 avio_wb32(pb, track_width_1616);
2459 avio_wb32(pb, track->height * 0x10000U);
2468 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2470 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2471 track->par->sample_aspect_ratio.den);
2473 int64_t pos = avio_tell(pb);
2475 avio_wb32(pb, 0); /* size */
2476 ffio_wfourcc(pb, "tapt");
2479 ffio_wfourcc(pb, "clef");
2481 avio_wb32(pb, width << 16);
2482 avio_wb32(pb, track->par->height << 16);
2485 ffio_wfourcc(pb, "prof");
2487 avio_wb32(pb, width << 16);
2488 avio_wb32(pb, track->par->height << 16);
2491 ffio_wfourcc(pb, "enof");
2493 avio_wb32(pb, track->par->width << 16);
2494 avio_wb32(pb, track->par->height << 16);
2496 return update_size(pb, pos);
2499 // This box seems important for the psp playback ... without it the movie seems to hang
2500 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2503 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2504 track->timescale, AV_ROUND_UP);
2505 int version = duration < INT32_MAX ? 0 : 1;
2506 int entry_size, entry_count, size;
2507 int64_t delay, start_ct = track->start_cts;
2508 int64_t start_dts = track->start_dts;
2511 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2513 av_log(mov->fc, AV_LOG_DEBUG,
2514 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2515 track->cluster[0].dts, track->cluster[0].cts,
2516 start_dts, start_ct, track->track_id);
2517 start_dts = track->cluster[0].dts;
2518 start_ct = track->cluster[0].cts;
2522 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2523 track->timescale, AV_ROUND_DOWN);
2524 version |= delay < INT32_MAX ? 0 : 1;
2526 entry_size = (version == 1) ? 20 : 12;
2527 entry_count = 1 + (delay > 0);
2528 size = 24 + entry_count * entry_size;
2530 /* write the atom data */
2531 avio_wb32(pb, size);
2532 ffio_wfourcc(pb, "edts");
2533 avio_wb32(pb, size - 8);
2534 ffio_wfourcc(pb, "elst");
2535 avio_w8(pb, version);
2536 avio_wb24(pb, 0); /* flags */
2538 avio_wb32(pb, entry_count);
2539 if (delay > 0) { /* add an empty edit to delay presentation */
2540 /* In the positive delay case, the delay includes the cts
2541 * offset, and the second edit list entry below trims out
2542 * the same amount from the actual content. This makes sure
2543 * that the offsetted last sample is included in the edit
2544 * list duration as well. */
2546 avio_wb64(pb, delay);
2549 avio_wb32(pb, delay);
2552 avio_wb32(pb, 0x00010000);
2554 /* Avoid accidentally ending up with start_ct = -1 which has got a
2555 * special meaning. Normally start_ct should end up positive or zero
2556 * here, but use FFMIN in case dts is a small positive integer
2557 * rounded to 0 when represented in MOV_TIMESCALE units. */
2558 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2559 start_ct = -FFMIN(start_dts, 0);
2560 /* Note, this delay is calculated from the pts of the first sample,
2561 * ensuring that we don't reduce the duration for cases with
2566 /* For fragmented files, we don't know the full length yet. Setting
2567 * duration to 0 allows us to only specify the offset, including
2568 * the rest of the content (from all future fragments) without specifying
2569 * an explicit duration. */
2570 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2575 avio_wb64(pb, duration);
2576 avio_wb64(pb, start_ct);
2578 avio_wb32(pb, duration);
2579 avio_wb32(pb, start_ct);
2581 avio_wb32(pb, 0x00010000);
2585 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2587 avio_wb32(pb, 20); // size
2588 ffio_wfourcc(pb, "tref");
2589 avio_wb32(pb, 12); // size (subatom)
2590 avio_wl32(pb, track->tref_tag);
2591 avio_wb32(pb, track->tref_id);
2595 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2596 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2598 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2599 ffio_wfourcc(pb, "uuid");
2600 ffio_wfourcc(pb, "USMT");
2601 avio_wb32(pb, 0x21d24fce);
2602 avio_wb32(pb, 0xbb88695c);
2603 avio_wb32(pb, 0xfac9c740);
2604 avio_wb32(pb, 0x1c); // another size here!
2605 ffio_wfourcc(pb, "MTDT");
2606 avio_wb32(pb, 0x00010012);
2607 avio_wb32(pb, 0x0a);
2608 avio_wb32(pb, 0x55c40000);
2614 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2616 AVFormatContext *ctx = track->rtp_ctx;
2617 char buf[1000] = "";
2620 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2621 NULL, NULL, 0, 0, ctx);
2622 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2625 avio_wb32(pb, len + 24);
2626 ffio_wfourcc(pb, "udta");
2627 avio_wb32(pb, len + 16);
2628 ffio_wfourcc(pb, "hnti");
2629 avio_wb32(pb, len + 8);
2630 ffio_wfourcc(pb, "sdp ");
2631 avio_write(pb, buf, len);
2635 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2636 const char *tag, const char *str)
2638 int64_t pos = avio_tell(pb);
2639 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2640 if (!t || !utf8len(t->value))
2643 avio_wb32(pb, 0); /* size */
2644 ffio_wfourcc(pb, tag); /* type */
2645 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2646 return update_size(pb, pos);
2649 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2652 AVIOContext *pb_buf;
2659 ret = avio_open_dyn_buf(&pb_buf);
2663 if (mov->mode & MODE_MP4)
2664 mov_write_track_metadata(pb_buf, st, "name", "title");
2666 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2667 avio_wb32(pb, size + 8);
2668 ffio_wfourcc(pb, "udta");
2669 avio_write(pb, buf, size);
2676 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2677 MOVTrack *track, AVStream *st)
2679 int64_t pos = avio_tell(pb);
2680 int entry_backup = track->entry;
2681 int chunk_backup = track->chunkCount;
2684 /* If we want to have an empty moov, but some samples already have been
2685 * buffered (delay_moov), pretend that no samples have been written yet. */
2686 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2687 track->chunkCount = track->entry = 0;
2689 avio_wb32(pb, 0); /* size */
2690 ffio_wfourcc(pb, "trak");
2691 mov_write_tkhd_tag(pb, mov, track, st);
2693 av_assert2(mov->use_editlist >= 0);
2695 if (track->start_dts != AV_NOPTS_VALUE) {
2696 if (mov->use_editlist)
2697 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2698 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2699 av_log(mov->fc, AV_LOG_WARNING,
2700 "Not writing any edit list even though one would have been required\n");
2703 if (track->tref_tag)
2704 mov_write_tref_tag(pb, track);
2706 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
2708 if (track->mode == MODE_PSP)
2709 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2710 if (track->tag == MKTAG('r','t','p',' '))
2711 mov_write_udta_sdp(pb, track);
2712 if (track->mode == MODE_MOV) {
2713 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2714 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2715 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2716 mov_write_tapt_tag(pb, track);
2719 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2720 mov_write_tapt_tag(pb, track);
2723 mov_write_track_udta_tag(pb, mov, st);
2724 track->entry = entry_backup;
2725 track->chunkCount = chunk_backup;
2726 return update_size(pb, pos);
2729 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2731 int i, has_audio = 0, has_video = 0;
2732 int64_t pos = avio_tell(pb);
2733 int audio_profile = mov->iods_audio_profile;
2734 int video_profile = mov->iods_video_profile;
2735 for (i = 0; i < mov->nb_streams; i++) {
2736 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2737 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
2738 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
2741 if (audio_profile < 0)
2742 audio_profile = 0xFF - has_audio;
2743 if (video_profile < 0)
2744 video_profile = 0xFF - has_video;
2745 avio_wb32(pb, 0x0); /* size */
2746 ffio_wfourcc(pb, "iods");
2747 avio_wb32(pb, 0); /* version & flags */
2748 put_descr(pb, 0x10, 7);
2749 avio_wb16(pb, 0x004f);
2752 avio_w8(pb, audio_profile);
2753 avio_w8(pb, video_profile);
2755 return update_size(pb, pos);
2758 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2760 avio_wb32(pb, 0x20); /* size */
2761 ffio_wfourcc(pb, "trex");
2762 avio_wb32(pb, 0); /* version & flags */
2763 avio_wb32(pb, track->track_id); /* track ID */
2764 avio_wb32(pb, 1); /* default sample description index */
2765 avio_wb32(pb, 0); /* default sample duration */
2766 avio_wb32(pb, 0); /* default sample size */
2767 avio_wb32(pb, 0); /* default sample flags */
2771 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2773 int64_t pos = avio_tell(pb);
2775 avio_wb32(pb, 0x0); /* size */
2776 ffio_wfourcc(pb, "mvex");
2777 for (i = 0; i < mov->nb_streams; i++)
2778 mov_write_trex_tag(pb, &mov->tracks[i]);
2779 return update_size(pb, pos);
2782 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2784 int max_track_id = 1, i;
2785 int64_t max_track_len = 0;
2788 for (i = 0; i < mov->nb_streams; i++) {
2789 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2790 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2792 mov->tracks[i].timescale,
2794 if (max_track_len < max_track_len_temp)
2795 max_track_len = max_track_len_temp;
2796 if (max_track_id < mov->tracks[i].track_id)
2797 max_track_id = mov->tracks[i].track_id;
2800 /* If using delay_moov, make sure the output is the same as if no
2801 * samples had been written yet. */
2802 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2807 version = max_track_len < UINT32_MAX ? 0 : 1;
2808 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
2810 ffio_wfourcc(pb, "mvhd");
2811 avio_w8(pb, version);
2812 avio_wb24(pb, 0); /* flags */
2814 avio_wb64(pb, mov->time);
2815 avio_wb64(pb, mov->time);
2817 avio_wb32(pb, mov->time); /* creation time */
2818 avio_wb32(pb, mov->time); /* modification time */
2820 avio_wb32(pb, MOV_TIMESCALE);
2821 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2823 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2824 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2825 avio_wb16(pb, 0); /* reserved */
2826 avio_wb32(pb, 0); /* reserved */
2827 avio_wb32(pb, 0); /* reserved */
2829 /* Matrix structure */
2830 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2832 avio_wb32(pb, 0); /* reserved (preview time) */
2833 avio_wb32(pb, 0); /* reserved (preview duration) */
2834 avio_wb32(pb, 0); /* reserved (poster time) */
2835 avio_wb32(pb, 0); /* reserved (selection time) */
2836 avio_wb32(pb, 0); /* reserved (selection duration) */
2837 avio_wb32(pb, 0); /* reserved (current time) */
2838 avio_wb32(pb, max_track_id + 1); /* Next track id */
2842 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2845 avio_wb32(pb, 33); /* size */
2846 ffio_wfourcc(pb, "hdlr");
2849 ffio_wfourcc(pb, "mdir");
2850 ffio_wfourcc(pb, "appl");
2857 /* helper function to write a data tag with the specified string as data */
2858 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2861 int size = 16 + strlen(data);
2862 avio_wb32(pb, size); /* size */
2863 ffio_wfourcc(pb, "data");
2866 avio_write(pb, data, strlen(data));
2870 lang = ff_mov_iso639_to_lang("und", 1);
2871 avio_wb16(pb, strlen(data)); /* string length */
2872 avio_wb16(pb, lang);
2873 avio_write(pb, data, strlen(data));
2874 return strlen(data) + 4;
2878 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2879 const char *value, int lang, int long_style)
2882 if (value && value[0]) {
2883 int64_t pos = avio_tell(pb);
2884 avio_wb32(pb, 0); /* size */
2885 ffio_wfourcc(pb, name);
2886 mov_write_string_data_tag(pb, value, lang, long_style);
2887 size = update_size(pb, pos);
2892 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2893 const char *name, const char *tag,
2896 int l, lang = 0, len, len2;
2897 AVDictionaryEntry *t, *t2 = NULL;
2900 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2903 len = strlen(t->key);
2904 snprintf(tag2, sizeof(tag2), "%s-", tag);
2905 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2906 len2 = strlen(t2->key);
2907 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2908 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2913 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2916 /* iTunes bpm number */
2917 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2919 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2920 int size = 0, tmpo = t ? atoi(t->value) : 0;
2923 avio_wb32(pb, size);
2924 ffio_wfourcc(pb, "tmpo");
2925 avio_wb32(pb, size-8); /* size */
2926 ffio_wfourcc(pb, "data");
2927 avio_wb32(pb, 0x15); //type specifier
2929 avio_wb16(pb, tmpo); // data
2934 /* iTunes track or disc number */
2935 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2936 AVFormatContext *s, int disc)
2938 AVDictionaryEntry *t = av_dict_get(s->metadata,
2939 disc ? "disc" : "track",
2941 int size = 0, track = t ? atoi(t->value) : 0;
2944 char *slash = strchr(t->value, '/');
2946 tracks = atoi(slash + 1);
2947 avio_wb32(pb, 32); /* size */
2948 ffio_wfourcc(pb, disc ? "disk" : "trkn");
2949 avio_wb32(pb, 24); /* size */
2950 ffio_wfourcc(pb, "data");
2951 avio_wb32(pb, 0); // 8 bytes empty
2953 avio_wb16(pb, 0); // empty
2954 avio_wb16(pb, track); // track / disc number
2955 avio_wb16(pb, tracks); // total track / disc number
2956 avio_wb16(pb, 0); // empty
2962 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2963 const char *name, const char *tag,
2966 AVDictionaryEntry *t = NULL;
2968 int size = 24 + len;
2970 if (len != 1 && len != 4)
2973 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2975 num = atoi(t->value);
2977 avio_wb32(pb, size);
2978 ffio_wfourcc(pb, name);
2979 avio_wb32(pb, size - 8);
2980 ffio_wfourcc(pb, "data");
2981 avio_wb32(pb, 0x15);
2983 if (len==4) avio_wb32(pb, num);
2984 else avio_w8 (pb, num);
2989 /* iTunes meta data list */
2990 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2993 int64_t pos = avio_tell(pb);
2994 avio_wb32(pb, 0); /* size */
2995 ffio_wfourcc(pb, "ilst");
2996 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
2997 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
2998 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2999 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3000 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3001 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3002 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3003 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3004 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3006 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3007 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3008 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3009 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3010 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3011 mov_write_string_metadata(s, pb, "desc", "description",1);
3012 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3013 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3014 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3015 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3016 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3017 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3018 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3019 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3020 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3021 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3022 mov_write_trkn_tag(pb, mov, s, 0); // track number
3023 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3024 mov_write_tmpo_tag(pb, s);
3025 return update_size(pb, pos);
3028 /* iTunes meta data tag */
3029 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3033 int64_t pos = avio_tell(pb);
3034 avio_wb32(pb, 0); /* size */
3035 ffio_wfourcc(pb, "meta");
3037 mov_write_itunes_hdlr_tag(pb, mov, s);
3038 mov_write_ilst_tag(pb, mov, s);
3039 size = update_size(pb, pos);
3043 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3044 const char *name, const char *key)
3047 AVDictionaryEntry *t;
3049 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3052 len = strlen(t->value);
3055 avio_wb32(pb, size);
3056 ffio_wfourcc(pb, name);
3057 avio_write(pb, t->value, len);
3063 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3067 GET_UTF8(val, *b++, return -1;)
3070 avio_wb16(pb, 0x00);
3074 static uint16_t language_code(const char *str)
3076 return (((str[0] - 0x60) & 0x1F) << 10) +
3077 (((str[1] - 0x60) & 0x1F) << 5) +
3078 (( str[2] - 0x60) & 0x1F);
3081 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3082 const char *tag, const char *str)
3084 int64_t pos = avio_tell(pb);
3085 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3086 if (!t || !utf8len(t->value))
3088 avio_wb32(pb, 0); /* size */
3089 ffio_wfourcc(pb, tag); /* type */
3090 avio_wb32(pb, 0); /* version + flags */
3091 if (!strcmp(tag, "yrrc"))
3092 avio_wb16(pb, atoi(t->value));
3094 avio_wb16(pb, language_code("eng")); /* language */
3095 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3096 if (!strcmp(tag, "albm") &&
3097 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3098 avio_w8(pb, atoi(t->value));
3100 return update_size(pb, pos);
3103 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3105 int64_t pos = avio_tell(pb);
3106 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3108 avio_wb32(pb, 0); // size
3109 ffio_wfourcc(pb, "chpl");
3110 avio_wb32(pb, 0x01000000); // version + flags
3111 avio_wb32(pb, 0); // unknown
3112 avio_w8(pb, nb_chapters);
3114 for (i = 0; i < nb_chapters; i++) {
3115 AVChapter *c = s->chapters[i];
3116 AVDictionaryEntry *t;
3117 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3119 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3120 int len = FFMIN(strlen(t->value), 255);
3122 avio_write(pb, t->value, len);
3126 return update_size(pb, pos);
3129 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3132 AVIOContext *pb_buf;
3136 ret = avio_open_dyn_buf(&pb_buf);
3140 if (mov->mode & MODE_3GP) {
3141 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3142 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3143 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3144 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3145 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3146 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3147 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3148 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3149 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
3150 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3151 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3152 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3153 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3154 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3155 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3156 // currently ignored by mov.c
3157 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3158 // add support for libquicktime, this atom is also actually read by mov.c
3159 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3160 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3161 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3162 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3163 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3164 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3165 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3167 /* iTunes meta data */
3168 mov_write_meta_tag(pb_buf, mov, s);
3171 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3172 mov_write_chpl_tag(pb_buf, s);
3174 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3175 avio_wb32(pb, size + 8);
3176 ffio_wfourcc(pb, "udta");
3177 avio_write(pb, buf, size);
3184 static void mov_write_psp_udta_tag(AVIOContext *pb,
3185 const char *str, const char *lang, int type)
3187 int len = utf8len(str) + 1;
3190 avio_wb16(pb, len * 2 + 10); /* size */
3191 avio_wb32(pb, type); /* type */
3192 avio_wb16(pb, language_code(lang)); /* language */
3193 avio_wb16(pb, 0x01); /* ? */
3194 ascii_to_wc(pb, str);
3197 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3199 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3203 pos = avio_tell(pb);
3204 avio_wb32(pb, 0); /* size placeholder*/
3205 ffio_wfourcc(pb, "uuid");
3206 ffio_wfourcc(pb, "USMT");
3207 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3208 avio_wb32(pb, 0xbb88695c);
3209 avio_wb32(pb, 0xfac9c740);
3211 pos2 = avio_tell(pb);
3212 avio_wb32(pb, 0); /* size placeholder*/
3213 ffio_wfourcc(pb, "MTDT");
3217 avio_wb16(pb, 0x0C); /* size */
3218 avio_wb32(pb, 0x0B); /* type */
3219 avio_wb16(pb, language_code("und")); /* language */
3220 avio_wb16(pb, 0x0); /* ? */
3221 avio_wb16(pb, 0x021C); /* data */
3223 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3224 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3225 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3226 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3228 update_size(pb, pos2);
3229 return update_size(pb, pos);
3235 static void build_chunks(MOVTrack *trk)
3238 MOVIentry *chunk = &trk->cluster[0];
3239 uint64_t chunkSize = chunk->size;
3240 chunk->chunkNum = 1;
3241 if (trk->chunkCount)
3243 trk->chunkCount = 1;
3244 for (i = 1; i<trk->entry; i++){
3245 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3246 chunkSize + trk->cluster[i].size < (1<<20)){
3247 chunkSize += trk->cluster[i].size;
3248 chunk->samples_in_chunk += trk->cluster[i].entries;
3250 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3251 chunk=&trk->cluster[i];
3252 chunkSize = chunk->size;
3258 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3262 int64_t pos = avio_tell(pb);
3263 avio_wb32(pb, 0); /* size placeholder*/
3264 ffio_wfourcc(pb, "moov");
3266 for (i = 0; i < mov->nb_streams; i++) {
3267 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3270 mov->tracks[i].time = mov->time;
3271 mov->tracks[i].track_id = i + 1;
3273 if (mov->tracks[i].entry)
3274 build_chunks(&mov->tracks[i]);
3277 if (mov->chapter_track)
3278 for (i = 0; i < s->nb_streams; i++) {
3279 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3280 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3282 for (i = 0; i < mov->nb_streams; i++) {
3283 MOVTrack *track = &mov->tracks[i];
3284 if (track->tag == MKTAG('r','t','p',' ')) {
3285 track->tref_tag = MKTAG('h','i','n','t');
3286 track->tref_id = mov->tracks[track->src_track].track_id;
3287 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3288 int * fallback, size;
3289 fallback = (int*)av_stream_get_side_data(track->st,
3290 AV_PKT_DATA_FALLBACK_TRACK,
3292 if (fallback != NULL && size == sizeof(int)) {
3293 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3294 track->tref_tag = MKTAG('f','a','l','l');
3295 track->tref_id = mov->tracks[*fallback].track_id;
3300 for (i = 0; i < mov->nb_streams; i++) {
3301 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3302 int src_trk = mov->tracks[i].src_track;
3303 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3304 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3305 //src_trk may have a different timescale than the tmcd track
3306 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3307 mov->tracks[i].timescale,
3308 mov->tracks[src_trk].timescale);
3312 mov_write_mvhd_tag(pb, mov);
3313 if (mov->mode != MODE_MOV && !mov->iods_skip)
3314 mov_write_iods_tag(pb, mov);
3315 for (i = 0; i < mov->nb_streams; i++) {
3316 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3317 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3322 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3323 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3325 if (mov->mode == MODE_PSP)
3326 mov_write_uuidusmt_tag(pb, s);
3328 mov_write_udta_tag(pb, mov, s);
3330 return update_size(pb, pos);
3333 static void param_write_int(AVIOContext *pb, const char *name, int value)
3335 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3338 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3340 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3343 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3346 len = FFMIN(sizeof(buf) / 2 - 1, len);
3347 ff_data_to_hex(buf, value, len, 0);
3348 buf[2 * len] = '\0';
3349 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3352 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
3354 int64_t pos = avio_tell(pb);
3356 static const uint8_t uuid[] = {
3357 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3358 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3362 ffio_wfourcc(pb, "uuid");
3363 avio_write(pb, uuid, sizeof(uuid));
3366 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3367 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3368 avio_printf(pb, "<head>\n");
3369 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3370 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3372 avio_printf(pb, "</head>\n");
3373 avio_printf(pb, "<body>\n");
3374 avio_printf(pb, "<switch>\n");
3375 for (i = 0; i < mov->nb_streams; i++) {
3376 MOVTrack *track = &mov->tracks[i];
3378 /* track->track_id is initialized in write_moov, and thus isn't known
3380 int track_id = i + 1;
3382 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3384 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3389 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3390 (int64_t)track->par->bit_rate);
3391 param_write_int(pb, "systemBitrate", track->par->bit_rate);
3392 param_write_int(pb, "trackID", track_id);
3393 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3394 if (track->par->codec_id == AV_CODEC_ID_H264) {
3396 int size = track->par->extradata_size;
3397 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3399 param_write_hex(pb, "CodecPrivateData",
3400 ptr ? ptr : track->par->extradata,
3404 param_write_string(pb, "FourCC", "H264");
3405 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3406 param_write_string(pb, "FourCC", "WVC1");
3407 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3408 track->par->extradata_size);
3410 param_write_int(pb, "MaxWidth", track->par->width);
3411 param_write_int(pb, "MaxHeight", track->par->height);
3412 param_write_int(pb, "DisplayWidth", track->par->width);
3413 param_write_int(pb, "DisplayHeight", track->par->height);
3415 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3416 switch (track->par->profile)
3418 case FF_PROFILE_AAC_HE_V2:
3419 param_write_string(pb, "FourCC", "AACP");
3421 case FF_PROFILE_AAC_HE:
3422 param_write_string(pb, "FourCC", "AACH");
3425 param_write_string(pb, "FourCC", "AACL");
3427 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3428 param_write_string(pb, "FourCC", "WMAP");
3430 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3431 track->par->extradata_size);
3432 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3433 track->par->codec_id));
3434 param_write_int(pb, "Channels", track->par->channels);
3435 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3436 param_write_int(pb, "BitsPerSample", 16);
3437 param_write_int(pb, "PacketSize", track->par->block_align ?
3438 track->par->block_align : 4);
3440 avio_printf(pb, "</%s>\n", type);
3442 avio_printf(pb, "</switch>\n");
3443 avio_printf(pb, "</body>\n");
3444 avio_printf(pb, "</smil>\n");
3446 return update_size(pb, pos);
3449 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3452 ffio_wfourcc(pb, "mfhd");
3454 avio_wb32(pb, mov->fragments);
3458 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3460 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3461 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3464 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3465 MOVTrack *track, int64_t moof_offset)
3467 int64_t pos = avio_tell(pb);
3468 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3469 MOV_TFHD_BASE_DATA_OFFSET;
3470 if (!track->entry) {
3471 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3473 flags |= MOV_TFHD_DEFAULT_FLAGS;
3475 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3476 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3477 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3478 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3479 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3482 /* Don't set a default sample size, the silverlight player refuses
3483 * to play files with that set. Don't set a default sample duration,
3484 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3485 * file format says it MUST NOT be set. */
3486 if (track->mode == MODE_ISM)
3487 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3488 MOV_TFHD_BASE_DATA_OFFSET);
3490 avio_wb32(pb, 0); /* size placeholder */
3491 ffio_wfourcc(pb, "tfhd");
3492 avio_w8(pb, 0); /* version */
3493 avio_wb24(pb, flags);
3495 avio_wb32(pb, track->track_id); /* track-id */
3496 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3497 avio_wb64(pb, moof_offset);
3498 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3499 track->default_duration = get_cluster_duration(track, 0);
3500 avio_wb32(pb, track->default_duration);
3502 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3503 track->default_size = track->entry ? track->cluster[0].size : 1;
3504 avio_wb32(pb, track->default_size);
3506 track->default_size = -1;
3508 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3509 /* Set the default flags based on the second sample, if available.
3510 * If the first sample is different, that can be signaled via a separate field. */
3511 if (track->entry > 1)
3512 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
3514 track->default_sample_flags =
3515 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
3516 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3517 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3518 avio_wb32(pb, track->default_sample_flags);
3521 return update_size(pb, pos);
3524 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3525 MOVTrack *track, int moof_size,
3528 int64_t pos = avio_tell(pb);
3529 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3532 for (i = first; i < end; i++) {
3533 if (get_cluster_duration(track, i) != track->default_duration)
3534 flags |= MOV_TRUN_SAMPLE_DURATION;
3535 if (track->cluster[i].size != track->default_size)
3536 flags |= MOV_TRUN_SAMPLE_SIZE;
3537 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3538 flags |= MOV_TRUN_SAMPLE_FLAGS;
3540 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
3541 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
3542 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3543 if (track->flags & MOV_TRACK_CTTS)
3544 flags |= MOV_TRUN_SAMPLE_CTS;
3546 avio_wb32(pb, 0); /* size placeholder */
3547 ffio_wfourcc(pb, "trun");
3548 avio_w8(pb, 0); /* version */
3549 avio_wb24(pb, flags);
3551 avio_wb32(pb, end - first); /* sample count */
3552 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3553 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3555 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3557 avio_wb32(pb, moof_size + 8 + track->data_offset +
3558 track->cluster[first].pos); /* data offset */
3559 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3560 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
3562 for (i = first; i < end; i++) {
3563 if (flags & MOV_TRUN_SAMPLE_DURATION)
3564 avio_wb32(pb, get_cluster_duration(track, i));
3565 if (flags & MOV_TRUN_SAMPLE_SIZE)
3566 avio_wb32(pb, track->cluster[i].size);
3567 if (flags & MOV_TRUN_SAMPLE_FLAGS)
3568 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3569 if (flags & MOV_TRUN_SAMPLE_CTS)
3570 avio_wb32(pb, track->cluster[i].cts);
3573 mov->first_trun = 0;
3574 return update_size(pb, pos);
3577 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3579 int64_t pos = avio_tell(pb);
3580 static const uint8_t uuid[] = {
3581 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3582 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3585 avio_wb32(pb, 0); /* size placeholder */
3586 ffio_wfourcc(pb, "uuid");
3587 avio_write(pb, uuid, sizeof(uuid));
3590 avio_wb64(pb, track->start_dts + track->frag_start +
3591 track->cluster[0].cts);
3592 avio_wb64(pb, track->end_pts -
3593 (track->cluster[0].dts + track->cluster[0].cts));
3595 return update_size(pb, pos);
3598 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3599 MOVTrack *track, int entry)
3601 int n = track->nb_frag_info - 1 - entry, i;
3602 int size = 8 + 16 + 4 + 1 + 16*n;
3603 static const uint8_t uuid[] = {
3604 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3605 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3611 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3612 avio_wb32(pb, size);
3613 ffio_wfourcc(pb, "uuid");
3614 avio_write(pb, uuid, sizeof(uuid));
3618 for (i = 0; i < n; i++) {
3619 int index = entry + 1 + i;
3620 avio_wb64(pb, track->frag_info[index].time);
3621 avio_wb64(pb, track->frag_info[index].duration);
3623 if (n < mov->ism_lookahead) {
3624 int free_size = 16 * (mov->ism_lookahead - n);
3625 avio_wb32(pb, free_size);
3626 ffio_wfourcc(pb, "free");
3627 ffio_fill(pb, 0, free_size - 8);
3633 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3636 int64_t pos = avio_tell(pb);
3638 for (i = 0; i < mov->ism_lookahead; i++) {
3639 /* Update the tfrf tag for the last ism_lookahead fragments,
3640 * nb_frag_info - 1 is the next fragment to be written. */
3641 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3643 avio_seek(pb, pos, SEEK_SET);
3647 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3651 for (i = 0; i < mov->nb_streams; i++) {
3652 MOVTrack *track = &mov->tracks[i];
3653 MOVFragmentInfo *info;
3654 if ((tracks >= 0 && i != tracks) || !track->entry)
3656 track->nb_frag_info++;
3657 if (track->nb_frag_info >= track->frag_info_capacity) {
3658 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3659 if (av_reallocp_array(&track->frag_info,
3661 sizeof(*track->frag_info)))
3662 return AVERROR(ENOMEM);
3663 track->frag_info_capacity = new_capacity;
3665 info = &track->frag_info[track->nb_frag_info - 1];
3666 info->offset = avio_tell(pb);
3668 // Try to recreate the original pts for the first packet
3669 // from the fields we have stored
3670 info->time = track->start_dts + track->frag_start +
3671 track->cluster[0].cts;
3672 info->duration = track->end_pts -
3673 (track->cluster[0].dts + track->cluster[0].cts);
3674 // If the pts is less than zero, we will have trimmed
3675 // away parts of the media track using an edit list,
3676 // and the corresponding start presentation time is zero.
3677 if (info->time < 0) {
3678 info->duration += info->time;
3681 info->tfrf_offset = 0;
3682 mov_write_tfrf_tags(pb, mov, track);
3687 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3689 int64_t pos = avio_tell(pb);
3691 avio_wb32(pb, 0); /* size */
3692 ffio_wfourcc(pb, "tfdt");
3693 avio_w8(pb, 1); /* version */
3695 avio_wb64(pb, track->frag_start);
3696 return update_size(pb, pos);
3699 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3700 MOVTrack *track, int64_t moof_offset,
3703 int64_t pos = avio_tell(pb);
3705 avio_wb32(pb, 0); /* size placeholder */
3706 ffio_wfourcc(pb, "traf");
3708 mov_write_tfhd_tag(pb, mov, track, moof_offset);
3709 if (mov->mode != MODE_ISM)
3710 mov_write_tfdt_tag(pb, track);
3711 for (i = 1; i < track->entry; i++) {
3712 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
3713 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
3717 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
3718 if (mov->mode == MODE_ISM) {
3719 mov_write_tfxd_tag(pb, track);
3721 if (mov->ism_lookahead) {
3722 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3724 if (track->nb_frag_info > 0) {
3725 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3726 if (!info->tfrf_offset)
3727 info->tfrf_offset = avio_tell(pb);
3729 avio_wb32(pb, 8 + size);
3730 ffio_wfourcc(pb, "free");
3731 for (i = 0; i < size; i++)
3736 return update_size(pb, pos);
3739 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3740 int tracks, int moof_size)
3742 int64_t pos = avio_tell(pb);
3745 avio_wb32(pb, 0); /* size placeholder */
3746 ffio_wfourcc(pb, "moof");
3747 mov->first_trun = 1;
3749 mov_write_mfhd_tag(pb, mov);
3750 for (i = 0; i < mov->nb_streams; i++) {
3751 MOVTrack *track = &mov->tracks[i];
3752 if (tracks >= 0 && i != tracks)
3756 mov_write_traf_tag(pb, mov, track, pos, moof_size);
3759 return update_size(pb, pos);
3762 static int mov_write_sidx_tag(AVIOContext *pb,
3763 MOVTrack *track, int ref_size, int total_sidx_size)
3765 int64_t pos = avio_tell(pb), offset_pos, end_pos;
3766 int64_t presentation_time, duration, offset;
3767 int starts_with_SAP, i, entries;
3771 presentation_time = track->start_dts + track->frag_start +
3772 track->cluster[0].cts;
3773 duration = track->end_pts -
3774 (track->cluster[0].dts + track->cluster[0].cts);
3775 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
3777 // pts<0 should be cut away using edts
3778 if (presentation_time < 0) {
3779 duration += presentation_time;
3780 presentation_time = 0;
3783 entries = track->nb_frag_info;
3786 presentation_time = track->frag_info[0].time;
3789 avio_wb32(pb, 0); /* size */
3790 ffio_wfourcc(pb, "sidx");
3791 avio_w8(pb, 1); /* version */
3793 avio_wb32(pb, track->track_id); /* reference_ID */
3794 avio_wb32(pb, track->timescale); /* timescale */
3795 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
3796 offset_pos = avio_tell(pb);
3797 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
3798 avio_wb16(pb, 0); /* reserved */
3800 avio_wb16(pb, entries); /* reference_count */
3801 for (i = 0; i < entries; i++) {
3802 if (!track->entry) {
3803 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
3804 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
3806 duration = track->frag_info[i].duration;
3807 ref_size = track->frag_info[i].size;
3808 starts_with_SAP = 1;
3810 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
3811 avio_wb32(pb, duration); /* subsegment_duration */
3812 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
3815 end_pos = avio_tell(pb);
3816 offset = pos + total_sidx_size - end_pos;
3817 avio_seek(pb, offset_pos, SEEK_SET);
3818 avio_wb64(pb, offset);
3819 avio_seek(pb, end_pos, SEEK_SET);
3820 return update_size(pb, pos);
3823 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
3824 int tracks, int ref_size)
3827 AVIOContext *avio_buf;
3829 for (round = 0; round < 2; round++) {
3830 // First run one round to calculate the total size of all
3832 // This would be much simpler if we'd only write one sidx
3833 // atom, for the first track in the moof.
3835 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3840 for (i = 0; i < mov->nb_streams; i++) {
3841 MOVTrack *track = &mov->tracks[i];
3842 if (tracks >= 0 && i != tracks)
3844 // When writing a sidx for the full file, entry is 0, but
3845 // we want to include all tracks. ref_size is 0 in this case,
3846 // since we read it from frag_info instead.
3847 if (!track->entry && ref_size > 0)
3849 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
3853 total_size = ffio_close_null_buf(avio_buf);
3858 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3861 AVIOContext *avio_buf;
3864 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3866 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
3867 moof_size = ffio_close_null_buf(avio_buf);
3869 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
3870 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
3872 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
3875 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
3878 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
3880 int64_t pos = avio_tell(pb);
3883 avio_wb32(pb, 0); /* size placeholder */
3884 ffio_wfourcc(pb, "tfra");
3885 avio_w8(pb, 1); /* version */
3888 avio_wb32(pb, track->track_id);
3889 avio_wb32(pb, 0); /* length of traf/trun/sample num */
3890 avio_wb32(pb, track->nb_frag_info);
3891 for (i = 0; i < track->nb_frag_info; i++) {
3892 avio_wb64(pb, track->frag_info[i].time);
3893 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
3894 avio_w8(pb, 1); /* traf number */
3895 avio_w8(pb, 1); /* trun number */
3896 avio_w8(pb, 1); /* sample number */
3899 return update_size(pb, pos);
3902 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
3904 int64_t pos = avio_tell(pb);
3907 avio_wb32(pb, 0); /* size placeholder */
3908 ffio_wfourcc(pb, "mfra");
3909 /* An empty mfra atom is enough to indicate to the publishing point that
3910 * the stream has ended. */
3911 if (mov->flags & FF_MOV_FLAG_ISML)
3912 return update_size(pb, pos);
3914 for (i = 0; i < mov->nb_streams; i++) {
3915 MOVTrack *track = &mov->tracks[i];
3916 if (track->nb_frag_info)
3917 mov_write_tfra_tag(pb, track);
3921 ffio_wfourcc(pb, "mfro");
3922 avio_wb32(pb, 0); /* version + flags */
3923 avio_wb32(pb, avio_tell(pb) + 4 - pos);
3925 return update_size(pb, pos);
3928 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
3930 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
3931 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
3933 mov->mdat_pos = avio_tell(pb);
3934 avio_wb32(pb, 0); /* size placeholder*/
3935 ffio_wfourcc(pb, "mdat");
3939 /* TODO: This needs to be more general */
3940 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
3942 MOVMuxContext *mov = s->priv_data;
3943 int64_t pos = avio_tell(pb);
3944 int has_h264 = 0, has_video = 0;
3948 for (i = 0; i < s->nb_streams; i++) {
3949 AVStream *st = s->streams[i];
3950 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
3952 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
3956 avio_wb32(pb, 0); /* size */
3957 ffio_wfourcc(pb, "ftyp");
3959 if (mov->major_brand && strlen(mov->major_brand) >= 4)
3960 ffio_wfourcc(pb, mov->major_brand);
3961 else if (mov->mode == MODE_3GP) {
3962 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
3963 minor = has_h264 ? 0x100 : 0x200;
3964 } else if (mov->mode & MODE_3G2) {
3965 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
3966 minor = has_h264 ? 0x20000 : 0x10000;
3967 } else if (mov->mode == MODE_PSP)
3968 ffio_wfourcc(pb, "MSNV");
3969 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
3970 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
3971 else if (mov->mode == MODE_MP4)
3972 ffio_wfourcc(pb, "isom");
3973 else if (mov->mode == MODE_IPOD)
3974 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3975 else if (mov->mode == MODE_ISM)
3976 ffio_wfourcc(pb, "isml");
3977 else if (mov->mode == MODE_F4V)
3978 ffio_wfourcc(pb, "f4v ");
3980 ffio_wfourcc(pb, "qt ");
3982 avio_wb32(pb, minor);
3984 if (mov->mode == MODE_MOV)
3985 ffio_wfourcc(pb, "qt ");
3986 else if (mov->mode == MODE_ISM) {
3987 ffio_wfourcc(pb, "piff");
3988 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
3989 ffio_wfourcc(pb, "isom");
3990 ffio_wfourcc(pb, "iso2");
3992 ffio_wfourcc(pb, "avc1");
3995 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
3996 // brand. This is compatible with users that don't understand tfdt.
3997 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
3998 ffio_wfourcc(pb, "iso6");
4000 if (mov->mode == MODE_3GP)
4001 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4002 else if (mov->mode & MODE_3G2)
4003 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4004 else if (mov->mode == MODE_PSP)
4005 ffio_wfourcc(pb, "MSNV");
4006 else if (mov->mode == MODE_MP4)
4007 ffio_wfourcc(pb, "mp41");
4009 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4010 ffio_wfourcc(pb, "dash");
4012 return update_size(pb, pos);
4015 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4017 AVStream *video_st = s->streams[0];
4018 AVCodecParameters *video_par = s->streams[0]->codecpar;
4019 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4020 int audio_rate = audio_par->sample_rate;
4021 // TODO: should be avg_frame_rate
4022 int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
4023 int audio_kbitrate = audio_par->bit_rate / 1000;
4024 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4026 avio_wb32(pb, 0x94); /* size */
4027 ffio_wfourcc(pb, "uuid");
4028 ffio_wfourcc(pb, "PROF");
4030 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4031 avio_wb32(pb, 0xbb88695c);
4032 avio_wb32(pb, 0xfac9c740);
4034 avio_wb32(pb, 0x0); /* ? */
4035 avio_wb32(pb, 0x3); /* 3 sections ? */
4037 avio_wb32(pb, 0x14); /* size */
4038 ffio_wfourcc(pb, "FPRF");
4039 avio_wb32(pb, 0x0); /* ? */
4040 avio_wb32(pb, 0x0); /* ? */
4041 avio_wb32(pb, 0x0); /* ? */
4043 avio_wb32(pb, 0x2c); /* size */
4044 ffio_wfourcc(pb, "APRF"); /* audio */
4046 avio_wb32(pb, 0x2); /* TrackID */
4047 ffio_wfourcc(pb, "mp4a");
4048 avio_wb32(pb, 0x20f);
4050 avio_wb32(pb, audio_kbitrate);
4051 avio_wb32(pb, audio_kbitrate);
4052 avio_wb32(pb, audio_rate);
4053 avio_wb32(pb, audio_par->channels);
4055 avio_wb32(pb, 0x34); /* size */
4056 ffio_wfourcc(pb, "VPRF"); /* video */
4058 avio_wb32(pb, 0x1); /* TrackID */
4059 if (video_par->codec_id == AV_CODEC_ID_H264) {
4060 ffio_wfourcc(pb, "avc1");
4061 avio_wb16(pb, 0x014D);
4062 avio_wb16(pb, 0x0015);
4064 ffio_wfourcc(pb, "mp4v");
4065 avio_wb16(pb, 0x0000);
4066 avio_wb16(pb, 0x0103);
4069 avio_wb32(pb, video_kbitrate);
4070 avio_wb32(pb, video_kbitrate);
4071 avio_wb32(pb, frame_rate);
4072 avio_wb32(pb, frame_rate);
4073 avio_wb16(pb, video_par->width);
4074 avio_wb16(pb, video_par->height);
4075 avio_wb32(pb, 0x010001); /* ? */
4078 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4080 MOVMuxContext *mov = s->priv_data;
4083 mov_write_ftyp_tag(pb,s);
4084 if (mov->mode == MODE_PSP) {
4085 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4086 for (i = 0; i < s->nb_streams; i++) {
4087 AVStream *st = s->streams[i];
4088 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4090 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4096 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4097 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4098 return AVERROR(EINVAL);
4100 mov_write_uuidprof_tag(pb, s);
4105 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4108 int i, closed_gop = 0;
4110 for (i = 0; i < pkt->size - 4; i++) {
4111 c = (c << 8) + pkt->data[i];
4112 if (c == 0x1b8) { // gop
4113 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4114 } else if (c == 0x100) { // pic
4115 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4116 if (!temp_ref || closed_gop) // I picture is not reordered
4117 *flags = MOV_SYNC_SAMPLE;
4119 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4126 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4128 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4129 int seq = 0, entry = 0;
4130 int key = pkt->flags & AV_PKT_FLAG_KEY;
4131 start = find_next_marker(pkt->data, end);
4132 for (next = start; next < end; start = next) {
4133 next = find_next_marker(start + 4, end);
4134 switch (AV_RB32(start)) {
4135 case VC1_CODE_SEQHDR:
4138 case VC1_CODE_ENTRYPOINT:
4141 case VC1_CODE_SLICE:
4142 trk->vc1_info.slices = 1;
4146 if (!trk->entry && trk->vc1_info.first_packet_seen)
4147 trk->vc1_info.first_frag_written = 1;
4148 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4149 /* First packet in first fragment */
4150 trk->vc1_info.first_packet_seq = seq;
4151 trk->vc1_info.first_packet_entry = entry;
4152 trk->vc1_info.first_packet_seen = 1;
4153 } else if ((seq && !trk->vc1_info.packet_seq) ||
4154 (entry && !trk->vc1_info.packet_entry)) {
4156 for (i = 0; i < trk->entry; i++)
4157 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4158 trk->has_keyframes = 0;
4160 trk->vc1_info.packet_seq = 1;
4162 trk->vc1_info.packet_entry = 1;
4163 if (!trk->vc1_info.first_frag_written) {
4164 /* First fragment */
4165 if ((!seq || trk->vc1_info.first_packet_seq) &&
4166 (!entry || trk->vc1_info.first_packet_entry)) {
4167 /* First packet had the same headers as this one, readd the
4168 * sync sample flag. */
4169 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4170 trk->has_keyframes = 1;
4174 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4176 else if (trk->vc1_info.packet_seq)
4178 else if (trk->vc1_info.packet_entry)
4181 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4182 trk->has_keyframes++;
4186 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4188 MOVMuxContext *mov = s->priv_data;
4193 if (!track->mdat_buf)
4195 if (!mov->mdat_buf) {
4196 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4199 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4200 track->mdat_buf = NULL;
4202 offset = avio_tell(mov->mdat_buf);
4203 avio_write(mov->mdat_buf, buf, buf_size);
4206 for (i = track->entries_flushed; i < track->entry; i++)
4207 track->cluster[i].pos += offset;
4208 track->entries_flushed = track->entry;
4212 static int mov_flush_fragment(AVFormatContext *s, int force)
4214 MOVMuxContext *mov = s->priv_data;
4215 int i, first_track = -1;
4216 int64_t mdat_size = 0;
4219 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4222 for (i = 0; i < mov->nb_streams; i++) {
4223 MOVTrack *track = &mov->tracks[i];
4224 if (track->entry <= 1)
4226 // Sample durations are calculated as the diff of dts values,
4227 // but for the last sample in a fragment, we don't know the dts
4228 // of the first sample in the next fragment, so we have to rely
4229 // on what was set as duration in the AVPacket. Not all callers
4230 // set this though, so we might want to replace it with an
4231 // estimate if it currently is zero.
4232 if (get_cluster_duration(track, track->entry - 1) != 0)
4234 // Use the duration (i.e. dts diff) of the second last sample for
4235 // the last one. This is a wild guess (and fatal if it turns out
4236 // to be too long), but probably the best we can do - having a zero
4237 // duration is bad as well.
4238 track->track_duration += get_cluster_duration(track, track->entry - 2);
4239 track->end_pts += get_cluster_duration(track, track->entry - 2);
4240 if (!mov->missing_duration_warned) {
4241 av_log(s, AV_LOG_WARNING,
4242 "Estimating the duration of the last packet in a "
4243 "fragment, consider setting the duration field in "
4244 "AVPacket instead.\n");
4245 mov->missing_duration_warned = 1;
4249 if (!mov->moov_written) {
4250 int64_t pos = avio_tell(s->pb);
4252 int buf_size, moov_size;
4254 for (i = 0; i < mov->nb_streams; i++)
4255 if (!mov->tracks[i].entry)
4257 /* Don't write the initial moov unless all tracks have data */
4258 if (i < mov->nb_streams && !force)
4261 moov_size = get_moov_size(s);
4262 for (i = 0; i < mov->nb_streams; i++)
4263 mov->tracks[i].data_offset = pos + moov_size + 8;
4265 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4266 mov_write_identification(s->pb, s);
4267 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4270 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4271 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4272 mov->reserved_header_pos = avio_tell(s->pb);
4274 mov->moov_written = 1;
4278 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4279 mov->mdat_buf = NULL;
4280 avio_wb32(s->pb, buf_size + 8);
4281 ffio_wfourcc(s->pb, "mdat");
4282 avio_write(s->pb, buf, buf_size);
4285 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4286 mov->reserved_header_pos = avio_tell(s->pb);
4288 mov->moov_written = 1;
4290 for (i = 0; i < mov->nb_streams; i++) {
4291 if (mov->tracks[i].entry)
4292 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4293 mov->tracks[i].track_duration -
4294 mov->tracks[i].cluster[0].dts;
4295 mov->tracks[i].entry = 0;
4301 if (mov->frag_interleave) {
4302 for (i = 0; i < mov->nb_streams; i++) {
4303 MOVTrack *track = &mov->tracks[i];
4305 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4311 mdat_size = avio_tell(mov->mdat_buf);
4314 for (i = 0; i < mov->nb_streams; i++) {
4315 MOVTrack *track = &mov->tracks[i];
4316 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4317 track->data_offset = 0;
4319 track->data_offset = mdat_size;
4322 if (track->mdat_buf)
4323 mdat_size += avio_tell(track->mdat_buf);
4324 if (first_track < 0)
4331 for (i = 0; i < mov->nb_streams; i++) {
4332 MOVTrack *track = &mov->tracks[i];
4333 int buf_size, write_moof = 1, moof_tracks = -1;
4335 int64_t duration = 0;
4338 duration = track->start_dts + track->track_duration -
4339 track->cluster[0].dts;
4340 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4341 if (!track->mdat_buf)
4343 mdat_size = avio_tell(track->mdat_buf);
4346 write_moof = i == first_track;
4352 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4355 avio_wb32(s->pb, mdat_size + 8);
4356 ffio_wfourcc(s->pb, "mdat");
4360 track->frag_start += duration;
4362 track->entries_flushed = 0;
4363 if (!mov->frag_interleave) {
4364 if (!track->mdat_buf)
4366 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4367 track->mdat_buf = NULL;
4371 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4372 mov->mdat_buf = NULL;
4375 avio_write(s->pb, buf, buf_size);
4385 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4387 MOVMuxContext *mov = s->priv_data;
4388 int had_moov = mov->moov_written;
4389 int ret = mov_flush_fragment(s, force);
4392 // If using delay_moov, the first flush only wrote the moov,
4393 // not the actual moof+mdat pair, thus flush once again.
4394 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4395 ret = mov_flush_fragment(s, force);
4399 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4401 MOVMuxContext *mov = s->priv_data;
4402 AVIOContext *pb = s->pb;
4403 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4404 AVCodecParameters *par = trk->par;
4405 unsigned int samples_in_chunk = 0;
4406 int size = pkt->size, ret = 0;
4407 uint8_t *reformatted_data = NULL;
4410 int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
4411 if (duration < 0 || duration > INT_MAX) {
4412 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4416 pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
4417 pkt->pts = AV_NOPTS_VALUE;
4420 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
4421 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
4422 return AVERROR(EINVAL);
4424 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4426 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4427 if (mov->frag_interleave && mov->fragments > 0) {
4428 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
4429 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
4434 if (!trk->mdat_buf) {
4435 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4440 if (!mov->mdat_buf) {
4441 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4448 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
4449 /* We must find out how many AMR blocks there are in one packet */
4450 static const uint16_t packed_size[16] =
4451 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4454 while (len < size && samples_in_chunk < 100) {
4455 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4458 if (samples_in_chunk > 1) {
4459 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4462 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
4463 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4464 samples_in_chunk = trk->par->frame_size;
4465 } else if (trk->sample_size)
4466 samples_in_chunk = size / trk->sample_size;
4468 samples_in_chunk = 1;
4470 /* copy extradata if it exists */
4471 if (trk->vos_len == 0 && par->extradata_size > 0 &&
4472 !TAG_IS_AVCI(trk->tag) &&
4473 (par->codec_id != AV_CODEC_ID_DNXHD)) {
4474 trk->vos_len = par->extradata_size;
4475 trk->vos_data = av_malloc(trk->vos_len);
4476 if (!trk->vos_data) {
4477 ret = AVERROR(ENOMEM);
4480 memcpy(trk->vos_data, par->extradata, trk->vos_len);
4483 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4484 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4485 if (!s->streams[pkt->stream_index]->nb_frames) {
4486 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4487 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4488 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4491 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4493 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4494 /* from x264 or from bytestream h264 */
4495 /* nal reformating needed */
4496 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4497 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4499 avio_write(pb, reformatted_data, size);
4501 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4502 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
4508 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4511 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4512 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4513 /* extradata is Annex B, assume the bitstream is too and convert it */
4514 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4515 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4516 avio_write(pb, reformatted_data, size);
4518 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4520 #if CONFIG_AC3_PARSER
4521 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
4522 size = handle_eac3(mov, pkt, trk);
4527 avio_write(pb, pkt->data, size);
4530 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4531 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
4532 int nal_size_length = (par->extradata[4] & 0x3) + 1;
4533 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
4535 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
4542 avio_write(pb, pkt->data, size);
4546 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
4547 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4548 /* copy frame to create needed atoms */
4549 trk->vos_len = size;
4550 trk->vos_data = av_malloc(size);
4551 if (!trk->vos_data) {
4552 ret = AVERROR(ENOMEM);
4555 memcpy(trk->vos_data, pkt->data, size);
4558 if (trk->entry >= trk->cluster_capacity) {
4559 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4560 if (av_reallocp_array(&trk->cluster, new_capacity,
4561 sizeof(*trk->cluster))) {
4562 ret = AVERROR(ENOMEM);
4565 trk->cluster_capacity = new_capacity;
4568 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
4569 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4570 trk->cluster[trk->entry].chunkNum = 0;
4571 trk->cluster[trk->entry].size = size;
4572 trk->cluster[trk->entry].entries = samples_in_chunk;
4573 trk->cluster[trk->entry].dts = pkt->dts;
4574 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4575 if (!trk->frag_discont) {
4576 /* First packet of a new fragment. We already wrote the duration
4577 * of the last packet of the previous fragment based on track_duration,
4578 * which might not exactly match our dts. Therefore adjust the dts
4579 * of this packet to be what the previous packets duration implies. */
4580 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4581 /* We also may have written the pts and the corresponding duration
4582 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
4583 * the next fragment. This means the cts of the first sample must
4584 * be the same in all fragments. */
4585 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
4586 mov->mode == MODE_ISM)
4587 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
4589 /* New fragment, but discontinuous from previous fragments.
4590 * Pretend the duration sum of the earlier fragments is
4591 * pkt->dts - trk->start_dts. */
4592 trk->frag_start = pkt->dts - trk->start_dts;
4593 trk->end_pts = AV_NOPTS_VALUE;
4594 trk->frag_discont = 0;
4598 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4599 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4600 /* Not using edit lists and shifting the first track to start from zero.
4601 * If the other streams start from a later timestamp, we won't be able
4602 * to signal the difference in starting time without an edit list.
4603 * Thus move the timestamp for this first sample to 0, increasing
4604 * its duration instead. */
4605 trk->cluster[trk->entry].dts = trk->start_dts = 0;
4607 if (trk->start_dts == AV_NOPTS_VALUE) {
4608 trk->start_dts = pkt->dts;
4609 if (trk->frag_discont) {
4610 if (mov->use_editlist) {
4611 /* Pretend the whole stream started at pts=0, with earlier fragments
4612 * already written. If the stream started at pts=0, the duration sum
4613 * of earlier fragments would have been pkt->pts. */
4614 trk->frag_start = pkt->pts;
4615 trk->start_dts = pkt->dts - pkt->pts;
4617 /* Pretend the whole stream started at dts=0, with earlier fragments
4618 * already written, with a duration summing up to pkt->dts. */
4619 trk->frag_start = pkt->dts;
4622 trk->frag_discont = 0;
4623 } else if (pkt->dts && mov->moov_written)
4624 av_log(s, AV_LOG_WARNING,
4625 "Track %d starts with a nonzero dts %"PRId64", while the moov "
4626 "already has been written. Set the delay_moov flag to handle "
4628 pkt->stream_index, pkt->dts);
4630 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4631 trk->last_sample_is_subtitle_end = 0;
4633 if (pkt->pts == AV_NOPTS_VALUE) {
4634 av_log(s, AV_LOG_WARNING, "pts has no value\n");
4635 pkt->pts = pkt->dts;
4637 if (pkt->dts != pkt->pts)
4638 trk->flags |= MOV_TRACK_CTTS;
4639 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
4640 trk->cluster[trk->entry].flags = 0;
4641 if (trk->start_cts == AV_NOPTS_VALUE)
4642 trk->start_cts = pkt->pts - pkt->dts;
4643 if (trk->end_pts == AV_NOPTS_VALUE)
4644 trk->end_pts = trk->cluster[trk->entry].dts +
4645 trk->cluster[trk->entry].cts + pkt->duration;
4647 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
4648 trk->cluster[trk->entry].cts +
4651 if (par->codec_id == AV_CODEC_ID_VC1) {
4652 mov_parse_vc1_frame(pkt, trk);
4653 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4654 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4655 trk->entry > 0) { // force sync sample for the first key frame
4656 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4657 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4658 trk->flags |= MOV_TRACK_STPS;
4660 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
4662 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
4663 trk->has_keyframes++;
4666 trk->sample_count += samples_in_chunk;
4667 mov->mdat_size += size;
4669 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
4670 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
4671 reformatted_data, size);
4676 av_free(reformatted_data);
4680 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
4682 MOVMuxContext *mov = s->priv_data;
4683 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4684 AVCodecParameters *par = trk->par;
4685 int64_t frag_duration = 0;
4686 int size = pkt->size;
4688 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
4690 for (i = 0; i < s->nb_streams; i++)
4691 mov->tracks[i].frag_discont = 1;
4692 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
4696 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
4697 trk->start_dts = pkt->dts;
4698 if (pkt->pts != AV_NOPTS_VALUE)
4699 trk->start_cts = pkt->pts - pkt->dts;
4704 return 0; /* Discard 0 sized packets */
4707 if (trk->entry && pkt->stream_index < s->nb_streams)
4708 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
4709 s->streams[pkt->stream_index]->time_base,
4711 if ((mov->max_fragment_duration &&
4712 frag_duration >= mov->max_fragment_duration) ||
4713 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
4714 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
4715 par->codec_type == AVMEDIA_TYPE_VIDEO &&
4716 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
4717 if (frag_duration >= mov->min_fragment_duration) {
4718 // Set the duration of this track to line up with the next
4719 // sample in this track. This avoids relying on AVPacket
4720 // duration, but only helps for this particular track, not
4721 // for the other ones that are flushed at the same time.
4722 trk->track_duration = pkt->dts - trk->start_dts;
4723 trk->end_pts = pkt->pts;
4724 mov_auto_flush_fragment(s, 0);
4728 return ff_mov_write_packet(s, pkt);
4731 static int mov_write_subtitle_end_packet(AVFormatContext *s,
4735 uint8_t data[2] = {0};
4738 av_init_packet(&end);
4739 end.size = sizeof(data);
4744 end.stream_index = stream_index;
4746 ret = mov_write_single_packet(s, &end);
4747 av_packet_unref(&end);
4752 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4755 mov_flush_fragment(s, 1);
4759 MOVMuxContext *mov = s->priv_data;
4760 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4763 return mov_write_single_packet(s, pkt); /* Passthrough. */
4766 * Subtitles require special handling.
4768 * 1) For full complaince, every track must have a sample at
4769 * dts == 0, which is rarely true for subtitles. So, as soon
4770 * as we see any packet with dts > 0, write an empty subtitle
4771 * at dts == 0 for any subtitle track with no samples in it.
4773 * 2) For each subtitle track, check if the current packet's
4774 * dts is past the duration of the last subtitle sample. If
4775 * so, we now need to write an end sample for that subtitle.
4777 * This must be done conditionally to allow for subtitles that
4778 * immediately replace each other, in which case an end sample
4779 * is not needed, and is, in fact, actively harmful.
4781 * 3) See mov_write_trailer for how the final end sample is
4784 for (i = 0; i < mov->nb_streams; i++) {
4785 MOVTrack *trk = &mov->tracks[i];
4788 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
4789 trk->track_duration < pkt->dts &&
4790 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
4791 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
4792 if (ret < 0) return ret;
4793 trk->last_sample_is_subtitle_end = 1;
4797 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4798 AVPacket *opkt = pkt;
4800 if (trk->is_unaligned_qt_rgb) {
4801 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
4802 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
4803 ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
4808 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
4809 int ret2 = ff_get_packet_palette(s, opkt, ret, trk->palette);
4814 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
4815 (trk->par->format == AV_PIX_FMT_GRAY8 ||
4816 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
4817 for (i = 0; i < pkt->size; i++)
4818 pkt->data[i] = ~pkt->data[i];
4821 ret = mov_write_single_packet(s, pkt);
4822 av_packet_free(&pkt);
4827 return mov_write_single_packet(s, pkt);
4831 // QuickTime chapters involve an additional text track with the chapter names
4832 // as samples, and a tref pointing from the other tracks to the chapter one.
4833 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
4837 MOVMuxContext *mov = s->priv_data;
4838 MOVTrack *track = &mov->tracks[tracknum];
4839 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
4842 track->mode = mov->mode;
4843 track->tag = MKTAG('t','e','x','t');
4844 track->timescale = MOV_TIMESCALE;
4845 track->par = avcodec_parameters_alloc();
4847 return AVERROR(ENOMEM);
4848 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
4850 // These properties are required to make QT recognize the chapter track
4851 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
4852 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
4853 return AVERROR(ENOMEM);
4854 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
4856 if (avio_open_dyn_buf(&pb) >= 0) {
4860 /* Stub header (usually for Quicktime chapter track) */
4862 avio_wb32(pb, 0x01); // displayFlags
4863 avio_w8(pb, 0x00); // horizontal justification
4864 avio_w8(pb, 0x00); // vertical justification
4865 avio_w8(pb, 0x00); // bgColourRed
4866 avio_w8(pb, 0x00); // bgColourGreen
4867 avio_w8(pb, 0x00); // bgColourBlue
4868 avio_w8(pb, 0x00); // bgColourAlpha
4870 avio_wb16(pb, 0x00); // defTextBoxTop
4871 avio_wb16(pb, 0x00); // defTextBoxLeft
4872 avio_wb16(pb, 0x00); // defTextBoxBottom
4873 avio_wb16(pb, 0x00); // defTextBoxRight
4875 avio_wb16(pb, 0x00); // startChar
4876 avio_wb16(pb, 0x00); // endChar
4877 avio_wb16(pb, 0x01); // fontID
4878 avio_w8(pb, 0x00); // fontStyleFlags
4879 avio_w8(pb, 0x00); // fontSize
4880 avio_w8(pb, 0x00); // fgColourRed
4881 avio_w8(pb, 0x00); // fgColourGreen
4882 avio_w8(pb, 0x00); // fgColourBlue
4883 avio_w8(pb, 0x00); // fgColourAlpha
4885 avio_wb32(pb, 0x0D); // box size
4886 ffio_wfourcc(pb, "ftab"); // box atom name
4887 avio_wb16(pb, 0x01); // entry count
4889 avio_wb16(pb, 0x01); // font ID
4890 avio_w8(pb, 0x00); // font name length
4892 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
4893 track->par->extradata = buf;
4894 track->par->extradata_size = size;
4901 for (i = 0; i < s->nb_chapters; i++) {
4902 AVChapter *c = s->chapters[i];
4903 AVDictionaryEntry *t;
4905 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
4906 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
4907 pkt.duration = end - pkt.dts;
4909 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
4910 const char encd[12] = {
4911 0x00, 0x00, 0x00, 0x0C,
4913 0x00, 0x00, 0x01, 0x00 };
4914 len = strlen(t->value);
4915 pkt.size = len + 2 + 12;
4916 pkt.data = av_malloc(pkt.size);
4918 return AVERROR(ENOMEM);
4919 AV_WB16(pkt.data, len);
4920 memcpy(pkt.data + 2, t->value, len);
4921 memcpy(pkt.data + len + 2, encd, sizeof(encd));
4922 ff_mov_write_packet(s, &pkt);
4923 av_freep(&pkt.data);
4930 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
4933 MOVMuxContext *mov = s->priv_data;
4934 MOVTrack *track = &mov->tracks[index];
4935 AVStream *src_st = s->streams[src_index];
4937 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
4938 AVRational rate = find_fps(s, src_st);
4940 /* compute the frame number */
4941 ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
4945 /* tmcd track based on video stream */
4946 track->mode = mov->mode;
4947 track->tag = MKTAG('t','m','c','d');
4948 track->src_track = src_index;
4949 track->timescale = mov->tracks[src_index].timescale;
4950 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
4951 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
4953 /* set st to src_st for metadata access*/
4956 /* encode context: tmcd data stream */
4957 track->par = avcodec_parameters_alloc();
4959 return AVERROR(ENOMEM);
4960 track->par->codec_type = AVMEDIA_TYPE_DATA;
4961 track->par->codec_tag = track->tag;
4962 track->st->avg_frame_rate = av_inv_q(rate);
4964 /* the tmcd track just contains one packet with the frame number */
4965 pkt.data = av_malloc(pkt.size);
4967 return AVERROR(ENOMEM);
4968 AV_WB32(pkt.data, tc.start);
4969 ret = ff_mov_write_packet(s, &pkt);
4975 * st->disposition controls the "enabled" flag in the tkhd tag.
4976 * QuickTime will not play a track if it is not enabled. So make sure
4977 * that one track of each type (audio, video, subtitle) is enabled.
4979 * Subtitles are special. For audio and video, setting "enabled" also
4980 * makes the track "default" (i.e. it is rendered when played). For
4981 * subtitles, an "enabled" subtitle is not rendered by default, but
4982 * if no subtitle is enabled, the subtitle menu in QuickTime will be
4985 static void enable_tracks(AVFormatContext *s)
4987 MOVMuxContext *mov = s->priv_data;
4989 int enabled[AVMEDIA_TYPE_NB];
4990 int first[AVMEDIA_TYPE_NB];
4992 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4997 for (i = 0; i < s->nb_streams; i++) {
4998 AVStream *st = s->streams[i];
5000 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5001 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5004 if (first[st->codecpar->codec_type] < 0)
5005 first[st->codecpar->codec_type] = i;
5006 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5007 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5008 enabled[st->codecpar->codec_type]++;
5012 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5014 case AVMEDIA_TYPE_VIDEO:
5015 case AVMEDIA_TYPE_AUDIO:
5016 case AVMEDIA_TYPE_SUBTITLE:
5018 mov->per_stream_grouping = 1;
5019 if (!enabled[i] && first[i] >= 0)
5020 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5026 static void mov_free(AVFormatContext *s)
5028 MOVMuxContext *mov = s->priv_data;
5031 if (mov->chapter_track) {
5032 if (mov->tracks[mov->chapter_track].par)
5033 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5034 av_freep(&mov->tracks[mov->chapter_track].par);
5037 for (i = 0; i < mov->nb_streams; i++) {
5038 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5039 ff_mov_close_hinting(&mov->tracks[i]);
5040 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5041 av_freep(&mov->tracks[i].par);
5042 av_freep(&mov->tracks[i].cluster);
5043 av_freep(&mov->tracks[i].frag_info);
5045 if (mov->tracks[i].vos_len)
5046 av_freep(&mov->tracks[i].vos_data);
5048 ff_mov_cenc_free(&mov->tracks[i].cenc);
5051 av_freep(&mov->tracks);
5054 static uint32_t rgb_to_yuv(uint32_t rgb)
5059 r = (rgb >> 16) & 0xFF;
5060 g = (rgb >> 8) & 0xFF;
5063 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5064 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5065 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5067 return (y << 16) | (cr << 8) | cb;
5070 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5073 int i, width = 720, height = 480;
5074 int have_palette = 0, have_size = 0;
5075 uint32_t palette[16];
5076 char *cur = st->codecpar->extradata;
5078 while (cur && *cur) {
5079 if (strncmp("palette:", cur, 8) == 0) {
5081 count = sscanf(cur + 8,
5082 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5083 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5084 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5085 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5086 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5087 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5088 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5089 &palette[12], &palette[13], &palette[14], &palette[15]);
5091 for (i = 0; i < count; i++) {
5092 palette[i] = rgb_to_yuv(palette[i]);
5095 } else if (!strncmp("size:", cur, 5)) {
5096 sscanf(cur + 5, "%dx%d", &width, &height);
5099 if (have_palette && have_size)
5101 cur += strcspn(cur, "\n\r");
5102 cur += strspn(cur, "\n\r");
5105 track->vos_data = av_malloc(16*4);
5106 if (!track->vos_data)
5107 return AVERROR(ENOMEM);
5108 for (i = 0; i < 16; i++) {
5109 AV_WB32(track->vos_data + i * 4, palette[i]);
5111 track->vos_len = 16 * 4;
5113 st->codecpar->width = width;
5114 st->codecpar->height = track->height = height;
5119 static int mov_write_header(AVFormatContext *s)
5121 AVIOContext *pb = s->pb;
5122 MOVMuxContext *mov = s->priv_data;
5123 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5124 int i, ret, hint_track = 0, tmcd_track = 0;
5128 /* Default mode == MP4 */
5129 mov->mode = MODE_MP4;
5132 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5133 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5134 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5135 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5136 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5137 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5138 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5141 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5142 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5144 /* Set the FRAGMENT flag if any of the fragmentation methods are
5146 if (mov->max_fragment_duration || mov->max_fragment_size ||
5147 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5148 FF_MOV_FLAG_FRAG_KEYFRAME |
5149 FF_MOV_FLAG_FRAG_CUSTOM))
5150 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5152 /* Set other implicit flags immediately */
5153 if (mov->mode == MODE_ISM)
5154 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5155 FF_MOV_FLAG_FRAGMENT;
5156 if (mov->flags & FF_MOV_FLAG_DASH)
5157 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5158 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5160 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5161 mov->reserved_moov_size = -1;
5164 if (mov->use_editlist < 0) {
5165 mov->use_editlist = 1;
5166 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5167 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5168 // If we can avoid needing an edit list by shifting the
5169 // tracks, prefer that over (trying to) write edit lists
5170 // in fragmented output.
5171 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5172 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5173 mov->use_editlist = 0;
5176 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5177 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5178 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5180 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5181 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5183 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5184 * if the latter is set that's enough and omit_tfhd_offset doesn't
5185 * add anything extra on top of that. */
5186 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5187 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5188 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5190 if (mov->frag_interleave &&
5191 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5192 av_log(s, AV_LOG_ERROR,
5193 "Sample interleaving in fragments is mutually exclusive with "
5194 "omit_tfhd_offset and separate_moof\n");
5195 return AVERROR(EINVAL);
5198 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5199 * is enabled, we don't support non-seekable output at all. */
5200 if (!s->pb->seekable &&
5201 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5202 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5203 return AVERROR(EINVAL);
5206 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5207 if ((ret = mov_write_identification(pb, s)) < 0)
5211 mov->nb_streams = s->nb_streams;
5212 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5213 mov->chapter_track = mov->nb_streams++;
5215 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5216 /* Add hint tracks for each audio and video stream */
5217 hint_track = mov->nb_streams;
5218 for (i = 0; i < s->nb_streams; i++) {
5219 AVStream *st = s->streams[i];
5220 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5221 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5227 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4) {
5228 tmcd_track = mov->nb_streams;
5230 /* +1 tmcd track for each video stream with a timecode */
5231 for (i = 0; i < s->nb_streams; i++) {
5232 AVStream *st = s->streams[i];
5233 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5234 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
5235 mov->nb_meta_tmcd++;
5238 /* check if there is already a tmcd track to remux */
5239 if (mov->nb_meta_tmcd) {
5240 for (i = 0; i < s->nb_streams; i++) {
5241 AVStream *st = s->streams[i];
5242 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5243 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5244 "so timecode metadata are now ignored\n");
5245 mov->nb_meta_tmcd = 0;
5250 mov->nb_streams += mov->nb_meta_tmcd;
5253 // Reserve an extra stream for chapters for the case where chapters
5254 // are written in the trailer
5255 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5257 return AVERROR(ENOMEM);
5259 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5260 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5261 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5263 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5264 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5265 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5266 ret = AVERROR(EINVAL);
5270 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5271 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5272 mov->encryption_kid_len, CENC_KID_SIZE);
5273 ret = AVERROR(EINVAL);
5277 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5278 mov->encryption_scheme_str);
5279 ret = AVERROR(EINVAL);
5284 for (i = 0; i < s->nb_streams; i++) {
5285 AVStream *st= s->streams[i];
5286 MOVTrack *track= &mov->tracks[i];
5287 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5290 track->par = st->codecpar;
5291 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5292 if (track->language < 0)
5293 track->language = 0;
5294 track->mode = mov->mode;
5295 track->tag = mov_find_codec_tag(s, track);
5297 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5298 "codec not currently supported in container\n",
5299 avcodec_get_name(st->codecpar->codec_id), i);
5300 ret = AVERROR(EINVAL);
5303 /* If hinting of this track is enabled by a later hint track,
5304 * this is updated. */
5305 track->hint_track = -1;
5306 track->start_dts = AV_NOPTS_VALUE;
5307 track->start_cts = AV_NOPTS_VALUE;
5308 track->end_pts = AV_NOPTS_VALUE;
5309 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5310 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5311 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5312 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5313 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5314 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5315 ret = AVERROR(EINVAL);
5318 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5320 if (mov->video_track_timescale) {
5321 track->timescale = mov->video_track_timescale;
5323 track->timescale = st->time_base.den;
5324 while(track->timescale < 10000)
5325 track->timescale *= 2;
5327 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5328 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5329 ret = AVERROR(EINVAL);
5332 if (track->mode == MODE_MOV && track->timescale > 100000)
5333 av_log(s, AV_LOG_WARNING,
5334 "WARNING codec timebase is very high. If duration is too long,\n"
5335 "file may not be playable by quicktime. Specify a shorter timebase\n"
5336 "or choose different container.\n");
5337 if (track->mode == MODE_MOV &&
5338 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5339 track->tag == MKTAG('r','a','w',' ')) {
5340 enum AVPixelFormat pix_fmt = track->par->format;
5341 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5342 pix_fmt = AV_PIX_FMT_MONOWHITE;
5343 track->is_unaligned_qt_rgb =
5344 pix_fmt == AV_PIX_FMT_RGB24 ||
5345 pix_fmt == AV_PIX_FMT_BGR24 ||
5346 pix_fmt == AV_PIX_FMT_PAL8 ||
5347 pix_fmt == AV_PIX_FMT_GRAY8 ||
5348 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5349 pix_fmt == AV_PIX_FMT_MONOBLACK;
5351 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5352 track->timescale = st->codecpar->sample_rate;
5353 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
5354 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
5355 track->audio_vbr = 1;
5356 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
5357 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
5358 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
5359 if (!st->codecpar->block_align) {
5360 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
5361 ret = AVERROR(EINVAL);
5364 track->sample_size = st->codecpar->block_align;
5365 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
5366 track->audio_vbr = 1;
5368 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
5370 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
5371 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
5372 track->audio_vbr = 1;
5374 if (track->mode != MODE_MOV &&
5375 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
5376 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
5377 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
5378 i, track->par->sample_rate);
5379 ret = AVERROR(EINVAL);
5382 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
5383 i, track->par->sample_rate);
5386 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5387 track->timescale = st->time_base.den;
5388 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
5389 track->timescale = st->time_base.den;
5391 track->timescale = MOV_TIMESCALE;
5394 track->height = st->codecpar->height;
5395 /* The ism specific timescale isn't mandatory, but is assumed by
5396 * some tools, such as mp4split. */
5397 if (mov->mode == MODE_ISM)
5398 track->timescale = 10000000;
5400 avpriv_set_pts_info(st, 64, 1, track->timescale);
5402 /* copy extradata if it exists */
5403 if (st->codecpar->extradata_size) {
5404 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
5405 mov_create_dvd_sub_decoder_specific_info(track, st);
5406 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
5407 track->vos_len = st->codecpar->extradata_size;
5408 track->vos_data = av_malloc(track->vos_len);
5409 if (!track->vos_data) {
5410 ret = AVERROR(ENOMEM);
5413 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
5417 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5418 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
5419 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
5426 for (i = 0; i < s->nb_streams; i++) {
5428 AVStream *st= s->streams[i];
5429 MOVTrack *track= &mov->tracks[i];
5431 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5432 track->par->channel_layout != AV_CH_LAYOUT_MONO)
5435 for (j = 0; j < s->nb_streams; j++) {
5436 AVStream *stj= s->streams[j];
5437 MOVTrack *trackj= &mov->tracks[j];
5441 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5442 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
5443 trackj->language != track->language ||
5444 trackj->tag != track->tag
5447 track->multichannel_as_mono++;
5454 if (mov->reserved_moov_size){
5455 mov->reserved_header_pos = avio_tell(pb);
5456 if (mov->reserved_moov_size > 0)
5457 avio_skip(pb, mov->reserved_moov_size);
5460 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5461 /* If no fragmentation options have been set, set a default. */
5462 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
5463 FF_MOV_FLAG_FRAG_CUSTOM)) &&
5464 !mov->max_fragment_duration && !mov->max_fragment_size)
5465 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
5467 if (mov->flags & FF_MOV_FLAG_FASTSTART)
5468 mov->reserved_header_pos = avio_tell(pb);
5469 mov_write_mdat_tag(pb, mov);
5472 ff_parse_creation_time_metadata(s, &mov->time, 1);
5474 mov->time += 0x7C25B080; // 1970 based -> 1904 based
5476 if (mov->chapter_track)
5477 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5480 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5481 /* Initialize the hint tracks for each audio and video stream */
5482 for (i = 0; i < s->nb_streams; i++) {
5483 AVStream *st = s->streams[i];
5484 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5485 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5486 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
5493 if (mov->nb_meta_tmcd) {
5494 /* Initialize the tmcd tracks */
5495 for (i = 0; i < s->nb_streams; i++) {
5496 AVStream *st = s->streams[i];
5499 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5501 t = av_dict_get(st->metadata, "timecode", NULL, 0);
5504 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
5513 if (mov->flags & FF_MOV_FLAG_ISML)
5514 mov_write_isml_manifest(pb, mov);
5516 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5517 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5518 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
5521 mov->moov_written = 1;
5522 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5523 mov->reserved_header_pos = avio_tell(pb);
5532 static int get_moov_size(AVFormatContext *s)
5535 AVIOContext *moov_buf;
5536 MOVMuxContext *mov = s->priv_data;
5538 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
5540 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
5542 return ffio_close_null_buf(moov_buf);
5545 static int get_sidx_size(AVFormatContext *s)
5549 MOVMuxContext *mov = s->priv_data;
5551 if ((ret = ffio_open_null_buf(&buf)) < 0)
5553 mov_write_sidx_tags(buf, mov, -1, 0);
5554 return ffio_close_null_buf(buf);
5558 * This function gets the moov size if moved to the top of the file: the chunk
5559 * offset table can switch between stco (32-bit entries) to co64 (64-bit
5560 * entries) when the moov is moved to the beginning, so the size of the moov
5561 * would change. It also updates the chunk offset tables.
5563 static int compute_moov_size(AVFormatContext *s)
5565 int i, moov_size, moov_size2;
5566 MOVMuxContext *mov = s->priv_data;
5568 moov_size = get_moov_size(s);
5572 for (i = 0; i < mov->nb_streams; i++)
5573 mov->tracks[i].data_offset += moov_size;
5575 moov_size2 = get_moov_size(s);
5579 /* if the size changed, we just switched from stco to co64 and need to
5580 * update the offsets */
5581 if (moov_size2 != moov_size)
5582 for (i = 0; i < mov->nb_streams; i++)
5583 mov->tracks[i].data_offset += moov_size2 - moov_size;
5588 static int compute_sidx_size(AVFormatContext *s)
5591 MOVMuxContext *mov = s->priv_data;
5593 sidx_size = get_sidx_size(s);
5597 for (i = 0; i < mov->nb_streams; i++)
5598 mov->tracks[i].data_offset += sidx_size;
5603 static int shift_data(AVFormatContext *s)
5605 int ret = 0, moov_size;
5606 MOVMuxContext *mov = s->priv_data;
5607 int64_t pos, pos_end = avio_tell(s->pb);
5608 uint8_t *buf, *read_buf[2];
5609 int read_buf_id = 0;
5611 AVIOContext *read_pb;
5613 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
5614 moov_size = compute_sidx_size(s);
5616 moov_size = compute_moov_size(s);
5620 buf = av_malloc(moov_size * 2);
5622 return AVERROR(ENOMEM);
5624 read_buf[1] = buf + moov_size;
5626 /* Shift the data: the AVIO context of the output can only be used for
5627 * writing, so we re-open the same output, but for reading. It also avoids
5628 * a read/seek/write/seek back and forth. */
5630 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
5632 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
5633 "the second pass (faststart)\n", s->filename);
5637 /* mark the end of the shift to up to the last data we wrote, and get ready
5639 pos_end = avio_tell(s->pb);
5640 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
5642 /* start reading at where the new moov will be placed */
5643 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
5644 pos = avio_tell(read_pb);
5646 #define READ_BLOCK do { \
5647 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
5651 /* shift data by chunk of at most moov_size */
5656 n = read_size[read_buf_id];
5659 avio_write(s->pb, read_buf[read_buf_id], n);
5661 } while (pos < pos_end);
5662 ff_format_io_close(s, &read_pb);
5669 static int mov_write_trailer(AVFormatContext *s)
5671 MOVMuxContext *mov = s->priv_data;
5672 AVIOContext *pb = s->pb;
5678 * Before actually writing the trailer, make sure that there are no
5679 * dangling subtitles, that need a terminating sample.
5681 for (i = 0; i < mov->nb_streams; i++) {
5682 MOVTrack *trk = &mov->tracks[i];
5683 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5684 !trk->last_sample_is_subtitle_end) {
5685 mov_write_subtitle_end_packet(s, i, trk->track_duration);
5686 trk->last_sample_is_subtitle_end = 1;
5690 // If there were no chapters when the header was written, but there
5691 // are chapters now, write them in the trailer. This only works
5692 // when we are not doing fragments.
5693 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5694 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
5695 mov->chapter_track = mov->nb_streams++;
5696 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5701 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5702 moov_pos = avio_tell(pb);
5704 /* Write size of mdat tag */
5705 if (mov->mdat_size + 8 <= UINT32_MAX) {
5706 avio_seek(pb, mov->mdat_pos, SEEK_SET);
5707 avio_wb32(pb, mov->mdat_size + 8);
5709 /* overwrite 'wide' placeholder atom */
5710 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
5711 /* special value: real atom size will be 64 bit value after
5714 ffio_wfourcc(pb, "mdat");
5715 avio_wb64(pb, mov->mdat_size + 16);
5717 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
5719 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5720 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
5721 res = shift_data(s);
5723 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
5724 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5727 } else if (mov->reserved_moov_size > 0) {
5729 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5731 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
5733 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
5734 res = AVERROR(EINVAL);
5737 avio_wb32(pb, size);
5738 ffio_wfourcc(pb, "free");
5739 ffio_fill(pb, 0, size - 8);
5740 avio_seek(pb, moov_pos, SEEK_SET);
5742 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5747 mov_auto_flush_fragment(s, 1);
5748 for (i = 0; i < mov->nb_streams; i++)
5749 mov->tracks[i].data_offset = 0;
5750 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
5751 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
5752 res = shift_data(s);
5754 int64_t end = avio_tell(pb);
5755 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
5756 mov_write_sidx_tags(pb, mov, -1, 0);
5757 avio_seek(pb, end, SEEK_SET);
5758 mov_write_mfra_tag(pb, mov);
5761 mov_write_mfra_tag(pb, mov);
5771 #if CONFIG_MOV_MUXER
5773 AVOutputFormat ff_mov_muxer = {
5775 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5776 .extensions = "mov",
5777 .priv_data_size = sizeof(MOVMuxContext),
5778 .audio_codec = AV_CODEC_ID_AAC,
5779 .video_codec = CONFIG_LIBX264_ENCODER ?
5780 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5781 .write_header = mov_write_header,
5782 .write_packet = mov_write_packet,
5783 .write_trailer = mov_write_trailer,
5784 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5785 .codec_tag = (const AVCodecTag* const []){
5786 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
5788 .priv_class = &mov_muxer_class,
5791 #if CONFIG_TGP_MUXER
5793 AVOutputFormat ff_tgp_muxer = {
5795 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
5796 .extensions = "3gp",
5797 .priv_data_size = sizeof(MOVMuxContext),
5798 .audio_codec = AV_CODEC_ID_AMR_NB,
5799 .video_codec = AV_CODEC_ID_H263,
5800 .write_header = mov_write_header,
5801 .write_packet = mov_write_packet,
5802 .write_trailer = mov_write_trailer,
5803 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5804 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5805 .priv_class = &tgp_muxer_class,
5808 #if CONFIG_MP4_MUXER
5810 AVOutputFormat ff_mp4_muxer = {
5812 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
5813 .mime_type = "video/mp4",
5814 .extensions = "mp4",
5815 .priv_data_size = sizeof(MOVMuxContext),
5816 .audio_codec = AV_CODEC_ID_AAC,
5817 .video_codec = CONFIG_LIBX264_ENCODER ?
5818 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5819 .write_header = mov_write_header,
5820 .write_packet = mov_write_packet,
5821 .write_trailer = mov_write_trailer,
5822 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5823 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5824 .priv_class = &mp4_muxer_class,
5827 #if CONFIG_PSP_MUXER
5829 AVOutputFormat ff_psp_muxer = {
5831 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
5832 .extensions = "mp4,psp",
5833 .priv_data_size = sizeof(MOVMuxContext),
5834 .audio_codec = AV_CODEC_ID_AAC,
5835 .video_codec = CONFIG_LIBX264_ENCODER ?
5836 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5837 .write_header = mov_write_header,
5838 .write_packet = mov_write_packet,
5839 .write_trailer = mov_write_trailer,
5840 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5841 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5842 .priv_class = &psp_muxer_class,
5845 #if CONFIG_TG2_MUXER
5847 AVOutputFormat ff_tg2_muxer = {
5849 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
5850 .extensions = "3g2",
5851 .priv_data_size = sizeof(MOVMuxContext),
5852 .audio_codec = AV_CODEC_ID_AMR_NB,
5853 .video_codec = AV_CODEC_ID_H263,
5854 .write_header = mov_write_header,
5855 .write_packet = mov_write_packet,
5856 .write_trailer = mov_write_trailer,
5857 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5858 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5859 .priv_class = &tg2_muxer_class,
5862 #if CONFIG_IPOD_MUXER
5864 AVOutputFormat ff_ipod_muxer = {
5866 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
5867 .mime_type = "video/mp4",
5868 .extensions = "m4v,m4a",
5869 .priv_data_size = sizeof(MOVMuxContext),
5870 .audio_codec = AV_CODEC_ID_AAC,
5871 .video_codec = AV_CODEC_ID_H264,
5872 .write_header = mov_write_header,
5873 .write_packet = mov_write_packet,
5874 .write_trailer = mov_write_trailer,
5875 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5876 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
5877 .priv_class = &ipod_muxer_class,
5880 #if CONFIG_ISMV_MUXER
5882 AVOutputFormat ff_ismv_muxer = {
5884 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
5885 .mime_type = "video/mp4",
5886 .extensions = "ismv,isma",
5887 .priv_data_size = sizeof(MOVMuxContext),
5888 .audio_codec = AV_CODEC_ID_AAC,
5889 .video_codec = AV_CODEC_ID_H264,
5890 .write_header = mov_write_header,
5891 .write_packet = mov_write_packet,
5892 .write_trailer = mov_write_trailer,
5893 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5894 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5895 .priv_class = &ismv_muxer_class,
5898 #if CONFIG_F4V_MUXER
5900 AVOutputFormat ff_f4v_muxer = {
5902 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
5903 .mime_type = "application/f4v",
5904 .extensions = "f4v",
5905 .priv_data_size = sizeof(MOVMuxContext),
5906 .audio_codec = AV_CODEC_ID_AAC,
5907 .video_codec = AV_CODEC_ID_H264,
5908 .write_header = mov_write_header,
5909 .write_packet = mov_write_packet,
5910 .write_trailer = mov_write_trailer,
5911 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
5912 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
5913 .priv_class = &f4v_muxer_class,