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/opt.h"
44 #include "libavutil/dict.h"
45 #include "libavutil/pixdesc.h"
46 #include "libavutil/timecode.h"
54 static const AVOption options[] = {
55 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
56 { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
57 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
58 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
59 { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
60 { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
61 { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
63 { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
64 { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66 { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
67 { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
68 { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69 { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
70 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
71 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
72 { "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},
73 { "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},
74 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
75 { "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},
76 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
77 { "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},
78 { "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},
79 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
80 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
81 { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
85 #define MOV_CLASS(flavor)\
86 static const AVClass flavor ## _muxer_class = {\
87 .class_name = #flavor " muxer",\
88 .item_name = av_default_item_name,\
90 .version = LIBAVUTIL_VERSION_INT,\
93 static int get_moov_size(AVFormatContext *s);
95 static int utf8len(const uint8_t *b)
100 GET_UTF8(val, *b++, return -1;)
106 //FIXME support 64 bit variant with wide placeholders
107 static int64_t update_size(AVIOContext *pb, int64_t pos)
109 int64_t curpos = avio_tell(pb);
110 avio_seek(pb, pos, SEEK_SET);
111 avio_wb32(pb, curpos - pos); /* rewrite size */
112 avio_seek(pb, curpos, SEEK_SET);
117 static int co64_required(const MOVTrack *track)
119 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
124 /* Chunk offset atom */
125 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
128 int mode64 = co64_required(track); // use 32 bit size variant if possible
129 int64_t pos = avio_tell(pb);
130 avio_wb32(pb, 0); /* size */
132 ffio_wfourcc(pb, "co64");
134 ffio_wfourcc(pb, "stco");
135 avio_wb32(pb, 0); /* version & flags */
136 avio_wb32(pb, track->chunkCount); /* entry count */
137 for (i = 0; i < track->entry; i++) {
138 if (!track->cluster[i].chunkNum)
141 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
143 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
145 return update_size(pb, pos);
148 /* Sample size atom */
149 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
152 int i, j, entries = 0, tst = -1, oldtst = -1;
154 int64_t pos = avio_tell(pb);
155 avio_wb32(pb, 0); /* size */
156 ffio_wfourcc(pb, "stsz");
157 avio_wb32(pb, 0); /* version & flags */
159 for (i = 0; i < track->entry; i++) {
160 tst = track->cluster[i].size / track->cluster[i].entries;
161 if (oldtst != -1 && tst != oldtst)
164 entries += track->cluster[i].entries;
166 if (equalChunks && track->entry) {
167 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
168 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
169 avio_wb32(pb, sSize); // sample size
170 avio_wb32(pb, entries); // sample count
172 avio_wb32(pb, 0); // sample size
173 avio_wb32(pb, entries); // sample count
174 for (i = 0; i < track->entry; i++) {
175 for (j = 0; j < track->cluster[i].entries; j++) {
176 avio_wb32(pb, track->cluster[i].size /
177 track->cluster[i].entries);
181 return update_size(pb, pos);
184 /* Sample to chunk atom */
185 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
187 int index = 0, oldval = -1, i;
188 int64_t entryPos, curpos;
190 int64_t pos = avio_tell(pb);
191 avio_wb32(pb, 0); /* size */
192 ffio_wfourcc(pb, "stsc");
193 avio_wb32(pb, 0); // version & flags
194 entryPos = avio_tell(pb);
195 avio_wb32(pb, track->chunkCount); // entry count
196 for (i = 0; i < track->entry; i++) {
197 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
198 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
199 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
200 avio_wb32(pb, 0x1); // sample description index
201 oldval = track->cluster[i].samples_in_chunk;
205 curpos = avio_tell(pb);
206 avio_seek(pb, entryPos, SEEK_SET);
207 avio_wb32(pb, index); // rewrite size
208 avio_seek(pb, curpos, SEEK_SET);
210 return update_size(pb, pos);
213 /* Sync sample atom */
214 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
216 int64_t curpos, entryPos;
218 int64_t pos = avio_tell(pb);
219 avio_wb32(pb, 0); // size
220 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
221 avio_wb32(pb, 0); // version & flags
222 entryPos = avio_tell(pb);
223 avio_wb32(pb, track->entry); // entry count
224 for (i = 0; i < track->entry; i++) {
225 if (track->cluster[i].flags & flag) {
226 avio_wb32(pb, i + 1);
230 curpos = avio_tell(pb);
231 avio_seek(pb, entryPos, SEEK_SET);
232 avio_wb32(pb, index); // rewrite size
233 avio_seek(pb, curpos, SEEK_SET);
234 return update_size(pb, pos);
237 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
239 avio_wb32(pb, 0x11); /* size */
240 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
241 else ffio_wfourcc(pb, "damr");
242 ffio_wfourcc(pb, "FFMP");
243 avio_w8(pb, 0); /* decoder version */
245 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
246 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
247 avio_w8(pb, 0x01); /* Frames per sample */
251 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
256 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
258 if (track->vos_len < 7)
262 ffio_wfourcc(pb, "dac3");
264 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
265 fscod = get_bits(&gbc, 2);
266 frmsizecod = get_bits(&gbc, 6);
267 bsid = get_bits(&gbc, 5);
268 bsmod = get_bits(&gbc, 3);
269 acmod = get_bits(&gbc, 3);
271 skip_bits(&gbc, 2); // dsurmod
273 if ((acmod & 1) && acmod != 1)
274 skip_bits(&gbc, 2); // cmixlev
276 skip_bits(&gbc, 2); // surmixlev
278 lfeon = get_bits1(&gbc);
280 init_put_bits(&pbc, buf, sizeof(buf));
281 put_bits(&pbc, 2, fscod);
282 put_bits(&pbc, 5, bsid);
283 put_bits(&pbc, 3, bsmod);
284 put_bits(&pbc, 3, acmod);
285 put_bits(&pbc, 1, lfeon);
286 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
287 put_bits(&pbc, 5, 0); // reserved
289 flush_put_bits(&pbc);
290 avio_write(pb, buf, sizeof(buf));
300 /* Layout of the EC3SpecificBox */
301 /* maximum bitrate */
303 /* number of independent substreams */
306 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
308 /* bit stream identification 5 bits */
310 /* one bit reserved */
311 /* audio service mixing (not supported yet) 1 bit */
312 /* bit stream mode 3 bits */
314 /* audio coding mode 3 bits */
316 /* sub woofer on 1 bit */
318 /* 3 bits reserved */
319 /* number of dependent substreams associated with this substream 4 bits */
321 /* channel locations of the dependent substream(s), if any, 9 bits */
323 /* if there is no dependent substream, then one bit reserved instead */
324 } substream[1]; /* TODO: support 8 independent substreams */
327 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
330 AC3HeaderInfo tmp, *hdr = &tmp;
331 struct eac3_info *info;
334 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
335 return AVERROR(ENOMEM);
336 info = track->eac3_priv;
338 init_get_bits(&gbc, pkt->data, pkt->size * 8);
339 if (avpriv_ac3_parse_header2(&gbc, &hdr) < 0) {
340 /* drop the packets until we see a good one */
342 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
345 return AVERROR_INVALIDDATA;
348 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
349 num_blocks = hdr->num_blocks;
351 if (!info->ec3_done) {
352 /* AC-3 substream must be the first one */
353 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
354 return AVERROR(EINVAL);
356 /* this should always be the case, given that our AC-3 parser
357 * concatenates dependent frames to their independent parent */
358 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
359 /* substream ids must be incremental */
360 if (hdr->substreamid > info->num_ind_sub + 1)
361 return AVERROR(EINVAL);
363 if (hdr->substreamid == info->num_ind_sub + 1) {
364 //info->num_ind_sub++;
365 avpriv_request_sample(track->enc, "Multiple independent substreams");
366 return AVERROR_PATCHWELCOME;
367 } else if (hdr->substreamid < info->num_ind_sub ||
368 hdr->substreamid == 0 && info->substream[0].bsid) {
374 /* fill the info needed for the "dec3" atom */
375 info->substream[hdr->substreamid].fscod = hdr->sr_code;
376 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
377 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
378 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
379 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
381 /* Parse dependent substream(s), if any */
382 if (pkt->size != hdr->frame_size) {
383 int cumul_size = hdr->frame_size;
384 int parent = hdr->substreamid;
386 while (cumul_size != pkt->size) {
388 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
389 if (avpriv_ac3_parse_header2(&gbc, &hdr) < 0)
390 return AVERROR_INVALIDDATA;
391 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
392 return AVERROR(EINVAL);
393 cumul_size += hdr->frame_size;
394 info->substream[parent].num_dep_sub++;
396 /* header is parsed up to lfeon, but custom channel map may be needed */
399 /* skip volume control params */
400 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
401 skip_bits(&gbc, 5); // skip dialog normalization
402 if (get_bits1(&gbc)) {
403 skip_bits(&gbc, 8); // skip compression gain word
406 /* get the dependent stream channel map, if exists */
408 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
410 info->substream[parent].chan_loc |= hdr->channel_mode;
416 if (!info->num_blocks && num_blocks == 6)
418 else if (info->num_blocks + num_blocks > 6)
419 return AVERROR_INVALIDDATA;
421 if (!info->num_blocks) {
423 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
425 info->num_blocks = num_blocks;
429 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
431 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
432 info->num_blocks += num_blocks;
433 info->pkt.duration += pkt->duration;
434 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
436 if (info->num_blocks != 6)
439 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
441 av_free_packet(&info->pkt);
442 info->num_blocks = 0;
448 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
452 struct eac3_info *info;
455 if (!track->eac3_priv)
456 return AVERROR(EINVAL);
458 info = track->eac3_priv;
459 size = 2 + 4 * (info->num_ind_sub + 1);
460 buf = av_malloc(size);
462 size = AVERROR(ENOMEM);
466 init_put_bits(&pbc, buf, size);
467 put_bits(&pbc, 13, info->data_rate);
468 put_bits(&pbc, 3, info->num_ind_sub);
469 for (i = 0; i <= info->num_ind_sub; i++) {
470 put_bits(&pbc, 2, info->substream[i].fscod);
471 put_bits(&pbc, 5, info->substream[i].bsid);
472 put_bits(&pbc, 1, 0); /* reserved */
473 put_bits(&pbc, 1, 0); /* asvc */
474 put_bits(&pbc, 3, info->substream[i].bsmod);
475 put_bits(&pbc, 3, info->substream[i].acmod);
476 put_bits(&pbc, 1, info->substream[i].lfeon);
477 put_bits(&pbc, 5, 0); /* reserved */
478 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
479 if (!info->substream[i].num_dep_sub) {
480 put_bits(&pbc, 1, 0); /* reserved */
483 put_bits(&pbc, 9, info->substream[i].chan_loc);
486 flush_put_bits(&pbc);
488 avio_wb32(pb, size + 8);
489 ffio_wfourcc(pb, "dec3");
490 avio_write(pb, buf, size);
495 av_free_packet(&info->pkt);
496 av_freep(&track->eac3_priv);
502 * This function writes extradata "as is".
503 * Extradata must be formatted like a valid atom (with size and tag).
505 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
507 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
508 return track->enc->extradata_size;
511 static int mov_write_enda_tag(AVIOContext *pb)
514 ffio_wfourcc(pb, "enda");
515 avio_wb16(pb, 1); /* little endian */
519 static int mov_write_enda_tag_be(AVIOContext *pb)
522 ffio_wfourcc(pb, "enda");
523 avio_wb16(pb, 0); /* big endian */
527 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
532 avio_w8(pb, (size >> (7 * i)) | 0x80);
533 avio_w8(pb, size & 0x7F);
536 static unsigned compute_avg_bitrate(MOVTrack *track)
540 if (!track->track_duration)
542 for (i = 0; i < track->entry; i++)
543 size += track->cluster[i].size;
544 return size * 8 * track->timescale / track->track_duration;
547 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
549 int64_t pos = avio_tell(pb);
550 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
551 unsigned avg_bitrate;
553 avio_wb32(pb, 0); // size
554 ffio_wfourcc(pb, "esds");
555 avio_wb32(pb, 0); // Version
558 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
559 avio_wb16(pb, track->track_id);
560 avio_w8(pb, 0x00); // flags (= no flags)
562 // DecoderConfig descriptor
563 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
565 // Object type indication
566 if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
567 track->enc->codec_id == AV_CODEC_ID_MP3) &&
568 track->enc->sample_rate > 24000)
569 avio_w8(pb, 0x6B); // 11172-3
571 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
573 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
574 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
575 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
576 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
577 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
578 avio_w8(pb, 0x15); // flags (= Audiostream)
580 avio_w8(pb, 0x11); // flags (= Visualstream)
582 avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
584 avg_bitrate = compute_avg_bitrate(track);
585 // maxbitrate (FIXME should be max rate in any 1 sec window)
586 avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
587 avio_wb32(pb, avg_bitrate);
589 if (track->vos_len) {
590 // DecoderSpecific info descriptor
591 put_descr(pb, 0x05, track->vos_len);
592 avio_write(pb, track->vos_data, track->vos_len);
596 put_descr(pb, 0x06, 1);
598 return update_size(pb, pos);
601 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
603 return codec_id == AV_CODEC_ID_PCM_S24LE ||
604 codec_id == AV_CODEC_ID_PCM_S32LE ||
605 codec_id == AV_CODEC_ID_PCM_F32LE ||
606 codec_id == AV_CODEC_ID_PCM_F64LE;
609 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
611 return codec_id == AV_CODEC_ID_PCM_S24BE ||
612 codec_id == AV_CODEC_ID_PCM_S32BE ||
613 codec_id == AV_CODEC_ID_PCM_F32BE ||
614 codec_id == AV_CODEC_ID_PCM_F64BE;
617 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
620 int64_t pos = avio_tell(pb);
622 avio_wl32(pb, track->tag); // store it byteswapped
623 track->enc->codec_tag = av_bswap16(track->tag >> 16);
624 if ((ret = ff_put_wav_header(pb, track->enc, 0)) < 0)
626 return update_size(pb, pos);
629 static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
632 int64_t pos = avio_tell(pb);
634 ffio_wfourcc(pb, "wfex");
635 if ((ret = ff_put_wav_header(pb, track->enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
637 return update_size(pb, pos);
640 static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
642 uint32_t layout_tag, bitmap;
643 int64_t pos = avio_tell(pb);
645 layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
646 track->enc->channel_layout,
649 av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
650 "lack of channel information\n");
654 if (track->multichannel_as_mono)
657 avio_wb32(pb, 0); // Size
658 ffio_wfourcc(pb, "chan"); // Type
659 avio_w8(pb, 0); // Version
660 avio_wb24(pb, 0); // Flags
661 avio_wb32(pb, layout_tag); // mChannelLayoutTag
662 avio_wb32(pb, bitmap); // mChannelBitmap
663 avio_wb32(pb, 0); // mNumberChannelDescriptions
665 return update_size(pb, pos);
668 static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
670 int64_t pos = avio_tell(pb);
672 avio_wb32(pb, 0); /* size */
673 ffio_wfourcc(pb, "wave");
675 if (track->enc->codec_id != AV_CODEC_ID_QDM2) {
676 avio_wb32(pb, 12); /* size */
677 ffio_wfourcc(pb, "frma");
678 avio_wl32(pb, track->tag);
681 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
682 /* useless atom needed by mplayer, ipod, not needed by quicktime */
683 avio_wb32(pb, 12); /* size */
684 ffio_wfourcc(pb, "mp4a");
686 mov_write_esds_tag(pb, track);
687 } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
688 mov_write_enda_tag(pb);
689 } else if (mov_pcm_be_gt16(track->enc->codec_id)) {
690 mov_write_enda_tag_be(pb);
691 } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
692 mov_write_amr_tag(pb, track);
693 } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
694 mov_write_ac3_tag(pb, track);
695 } else if (track->enc->codec_id == AV_CODEC_ID_EAC3) {
696 mov_write_eac3_tag(pb, track);
697 } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||
698 track->enc->codec_id == AV_CODEC_ID_QDM2) {
699 mov_write_extradata_tag(pb, track);
700 } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
701 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
702 mov_write_ms_tag(pb, track);
705 avio_wb32(pb, 8); /* size */
706 avio_wb32(pb, 0); /* null tag */
708 return update_size(pb, pos);
711 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
714 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
715 int unescaped_size, seq_found = 0;
716 int level = 0, interlace = 0;
717 int packet_seq = track->vc1_info.packet_seq;
718 int packet_entry = track->vc1_info.packet_entry;
719 int slices = track->vc1_info.slices;
722 if (track->start_dts == AV_NOPTS_VALUE) {
723 /* No packets written yet, vc1_info isn't authoritative yet. */
724 /* Assume inline sequence and entry headers. */
725 packet_seq = packet_entry = 1;
726 av_log(NULL, AV_LOG_WARNING,
727 "moov atom written before any packets, unable to write correct "
728 "dvc1 atom. Set the delay_moov flag to fix this.\n");
731 unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
733 return AVERROR(ENOMEM);
734 start = find_next_marker(track->vos_data, end);
735 for (next = start; next < end; start = next) {
738 next = find_next_marker(start + 4, end);
739 size = next - start - 4;
742 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
743 init_get_bits(&gb, unescaped, 8 * unescaped_size);
744 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
745 int profile = get_bits(&gb, 2);
746 if (profile != PROFILE_ADVANCED) {
748 return AVERROR(ENOSYS);
751 level = get_bits(&gb, 3);
752 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
754 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
755 skip_bits(&gb, 1); /* broadcast */
756 interlace = get_bits1(&gb);
757 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
762 return AVERROR(ENOSYS);
765 init_put_bits(&pbc, buf, 7);
766 /* VC1DecSpecStruc */
767 put_bits(&pbc, 4, 12); /* profile - advanced */
768 put_bits(&pbc, 3, level);
769 put_bits(&pbc, 1, 0); /* reserved */
770 /* VC1AdvDecSpecStruc */
771 put_bits(&pbc, 3, level);
772 put_bits(&pbc, 1, 0); /* cbr */
773 put_bits(&pbc, 6, 0); /* reserved */
774 put_bits(&pbc, 1, !interlace); /* no interlace */
775 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
776 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
777 put_bits(&pbc, 1, !slices); /* no slice code */
778 put_bits(&pbc, 1, 0); /* no bframe */
779 put_bits(&pbc, 1, 0); /* reserved */
782 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
783 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
785 put_bits32(&pbc, 0xffffffff);
787 flush_put_bits(&pbc);
794 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
796 uint8_t buf[7] = { 0 };
799 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
802 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
803 ffio_wfourcc(pb, "dvc1");
804 avio_write(pb, buf, sizeof(buf));
805 avio_write(pb, track->vos_data, track->vos_len);
810 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
812 avio_wb32(pb, track->vos_len + 8);
813 ffio_wfourcc(pb, "glbl");
814 avio_write(pb, track->vos_data, track->vos_len);
815 return 8 + track->vos_len;
819 * Compute flags for 'lpcm' tag.
820 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
822 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
825 case AV_CODEC_ID_PCM_F32BE:
826 case AV_CODEC_ID_PCM_F64BE:
828 case AV_CODEC_ID_PCM_F32LE:
829 case AV_CODEC_ID_PCM_F64LE:
831 case AV_CODEC_ID_PCM_U8:
833 case AV_CODEC_ID_PCM_S16BE:
834 case AV_CODEC_ID_PCM_S24BE:
835 case AV_CODEC_ID_PCM_S32BE:
837 case AV_CODEC_ID_PCM_S8:
838 case AV_CODEC_ID_PCM_S16LE:
839 case AV_CODEC_ID_PCM_S24LE:
840 case AV_CODEC_ID_PCM_S32LE:
847 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
851 if (cluster_idx >= track->entry)
854 if (cluster_idx + 1 == track->entry)
855 next_dts = track->track_duration + track->start_dts;
857 next_dts = track->cluster[cluster_idx + 1].dts;
859 next_dts -= track->cluster[cluster_idx].dts;
861 av_assert0(next_dts >= 0);
862 av_assert0(next_dts <= INT_MAX);
867 static int get_samples_per_packet(MOVTrack *track)
869 int i, first_duration;
871 // return track->enc->frame_size;
873 /* use 1 for raw PCM */
874 if (!track->audio_vbr)
877 /* check to see if duration is constant for all clusters */
880 first_duration = get_cluster_duration(track, 0);
881 for (i = 1; i < track->entry; i++) {
882 if (get_cluster_duration(track, i) != first_duration)
885 return first_duration;
888 static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
890 int64_t pos = avio_tell(pb);
892 uint32_t tag = track->tag;
894 if (track->mode == MODE_MOV) {
895 if (track->timescale > UINT16_MAX) {
896 if (mov_get_lpcm_flags(track->enc->codec_id))
897 tag = AV_RL32("lpcm");
899 } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
900 mov_pcm_be_gt16(track->enc->codec_id) ||
901 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
902 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
903 track->enc->codec_id == AV_CODEC_ID_QDM2) {
908 avio_wb32(pb, 0); /* size */
909 avio_wl32(pb, tag); // store it byteswapped
910 avio_wb32(pb, 0); /* Reserved */
911 avio_wb16(pb, 0); /* Reserved */
912 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
914 /* SoundDescription */
915 avio_wb16(pb, version); /* Version */
916 avio_wb16(pb, 0); /* Revision level */
917 avio_wb32(pb, 0); /* Reserved */
922 avio_wb16(pb, 0xfffe);
924 avio_wb32(pb, 0x00010000);
926 avio_wb64(pb, av_double2int(track->enc->sample_rate));
927 avio_wb32(pb, track->enc->channels);
928 avio_wb32(pb, 0x7F000000);
929 avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
930 avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
931 avio_wb32(pb, track->sample_size);
932 avio_wb32(pb, get_samples_per_packet(track));
934 if (track->mode == MODE_MOV) {
935 avio_wb16(pb, track->enc->channels);
936 if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||
937 track->enc->codec_id == AV_CODEC_ID_PCM_S8)
938 avio_wb16(pb, 8); /* bits per sample */
939 else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_G726)
940 avio_wb16(pb, track->enc->bits_per_coded_sample);
943 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
944 } else { /* reserved for mp4/3gp */
950 avio_wb16(pb, 0); /* packet size (= 0) */
951 avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
952 track->enc->sample_rate : 0);
953 avio_wb16(pb, 0); /* Reserved */
956 if (version == 1) { /* SoundDescription V1 extended info */
957 if (mov_pcm_le_gt16(track->enc->codec_id) ||
958 mov_pcm_be_gt16(track->enc->codec_id))
959 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
961 avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
962 avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
963 avio_wb32(pb, track->sample_size); /* Bytes per frame */
964 avio_wb32(pb, 2); /* Bytes per sample */
967 if (track->mode == MODE_MOV &&
968 (track->enc->codec_id == AV_CODEC_ID_AAC ||
969 track->enc->codec_id == AV_CODEC_ID_AC3 ||
970 track->enc->codec_id == AV_CODEC_ID_EAC3 ||
971 track->enc->codec_id == AV_CODEC_ID_AMR_NB ||
972 track->enc->codec_id == AV_CODEC_ID_ALAC ||
973 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
974 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
975 track->enc->codec_id == AV_CODEC_ID_QDM2 ||
976 (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
977 (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
978 mov_write_wave_tag(pb, track);
979 else if (track->tag == MKTAG('m','p','4','a'))
980 mov_write_esds_tag(pb, track);
981 else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
982 mov_write_amr_tag(pb, track);
983 else if (track->enc->codec_id == AV_CODEC_ID_AC3)
984 mov_write_ac3_tag(pb, track);
985 else if (track->enc->codec_id == AV_CODEC_ID_EAC3)
986 mov_write_eac3_tag(pb, track);
987 else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
988 mov_write_extradata_tag(pb, track);
989 else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
990 mov_write_wfex_tag(pb, track);
991 else if (track->vos_len > 0)
992 mov_write_glbl_tag(pb, track);
994 if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
995 mov_write_chan_tag(pb, track);
997 return update_size(pb, pos);
1000 static int mov_write_d263_tag(AVIOContext *pb)
1002 avio_wb32(pb, 0xf); /* size */
1003 ffio_wfourcc(pb, "d263");
1004 ffio_wfourcc(pb, "FFMP");
1005 avio_w8(pb, 0); /* decoder version */
1006 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1007 avio_w8(pb, 0xa); /* level */
1008 avio_w8(pb, 0); /* profile */
1012 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1014 int64_t pos = avio_tell(pb);
1017 ffio_wfourcc(pb, "avcC");
1018 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1019 return update_size(pb, pos);
1022 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1024 int64_t pos = avio_tell(pb);
1027 ffio_wfourcc(pb, "hvcC");
1028 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1029 return update_size(pb, pos);
1032 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1033 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1036 avio_wb32(pb, 24); /* size */
1037 ffio_wfourcc(pb, "ACLR");
1038 ffio_wfourcc(pb, "ACLR");
1039 ffio_wfourcc(pb, "0001");
1040 if (track->enc->color_range == AVCOL_RANGE_MPEG) { /* Legal range (16-235) */
1041 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1042 } else { /* Full range (0-255) */
1043 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1045 avio_wb32(pb, 0); /* unknown */
1047 avio_wb32(pb, 24); /* size */
1048 ffio_wfourcc(pb, "APRG");
1049 ffio_wfourcc(pb, "APRG");
1050 ffio_wfourcc(pb, "0001");
1051 avio_wb32(pb, 1); /* unknown */
1052 avio_wb32(pb, 0); /* unknown */
1054 avio_wb32(pb, 120); /* size */
1055 ffio_wfourcc(pb, "ARES");
1056 ffio_wfourcc(pb, "ARES");
1057 ffio_wfourcc(pb, "0001");
1058 avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
1059 avio_wb32(pb, track->enc->width);
1060 /* values below are based on samples created with quicktime and avid codecs */
1061 if (track->vos_data[5] & 2) { // interlaced
1062 avio_wb32(pb, track->enc->height / 2);
1063 avio_wb32(pb, 2); /* unknown */
1064 avio_wb32(pb, 0); /* unknown */
1065 avio_wb32(pb, 4); /* unknown */
1067 avio_wb32(pb, track->enc->height);
1068 avio_wb32(pb, 1); /* unknown */
1069 avio_wb32(pb, 0); /* unknown */
1070 if (track->enc->height == 1080)
1071 avio_wb32(pb, 5); /* unknown */
1073 avio_wb32(pb, 6); /* unknown */
1076 for (i = 0; i < 10; i++)
1079 /* extra padding for stsd needed */
1084 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1086 int tag = track->enc->codec_tag;
1088 if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
1091 if (track->enc->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1092 else if (track->enc->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1093 else if (track->enc->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1094 else if (track->enc->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1095 else if (track->enc->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1096 else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1097 else if (track->enc->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1098 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1099 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1100 else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1105 static const AVCodecTag codec_ipod_tags[] = {
1106 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1107 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1108 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1109 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1110 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1111 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1112 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1113 { AV_CODEC_ID_NONE, 0 },
1116 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1118 int tag = track->enc->codec_tag;
1120 // keep original tag for subs, ipod supports both formats
1121 if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1122 (tag == MKTAG('t', 'x', '3', 'g') ||
1123 tag == MKTAG('t', 'e', 'x', 't'))))
1124 tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
1126 if (!av_match_ext(s->filename, "m4a") &&
1127 !av_match_ext(s->filename, "m4b") &&
1128 !av_match_ext(s->filename, "m4v"))
1129 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1130 "Quicktime/Ipod might not play the file\n");
1135 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1139 if (track->enc->width == 720) { /* SD */
1140 if (track->enc->height == 480) { /* NTSC */
1141 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1142 else tag = MKTAG('d','v','c',' ');
1143 }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1144 else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1145 else tag = MKTAG('d','v','p','p');
1146 } else if (track->enc->height == 720) { /* HD 720 line */
1147 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1148 else tag = MKTAG('d','v','h','p');
1149 } else if (track->enc->height == 1080) { /* HD 1080 line */
1150 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1151 else tag = MKTAG('d','v','h','6');
1153 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1160 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1162 AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
1163 /* if the codec time base makes no sense, try to fallback on stream frame rate */
1164 if (av_timecode_check_frame_rate(rate) < 0) {
1165 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1166 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1167 rate = st->avg_frame_rate;
1173 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1175 int tag = track->enc->codec_tag;
1176 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1177 AVStream *st = track->st;
1178 int rate = av_q2d(find_fps(s, st));
1181 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1183 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
1184 if (track->enc->width == 1280 && track->enc->height == 720) {
1186 if (rate == 24) tag = MKTAG('x','d','v','4');
1187 else if (rate == 25) tag = MKTAG('x','d','v','5');
1188 else if (rate == 30) tag = MKTAG('x','d','v','1');
1189 else if (rate == 50) tag = MKTAG('x','d','v','a');
1190 else if (rate == 60) tag = MKTAG('x','d','v','9');
1192 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
1194 if (rate == 24) tag = MKTAG('x','d','v','6');
1195 else if (rate == 25) tag = MKTAG('x','d','v','7');
1196 else if (rate == 30) tag = MKTAG('x','d','v','8');
1198 if (rate == 25) tag = MKTAG('x','d','v','3');
1199 else if (rate == 30) tag = MKTAG('x','d','v','2');
1201 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1203 if (rate == 24) tag = MKTAG('x','d','v','d');
1204 else if (rate == 25) tag = MKTAG('x','d','v','e');
1205 else if (rate == 30) tag = MKTAG('x','d','v','f');
1207 if (rate == 25) tag = MKTAG('x','d','v','c');
1208 else if (rate == 30) tag = MKTAG('x','d','v','b');
1211 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1212 if (track->enc->width == 1280 && track->enc->height == 720) {
1214 if (rate == 24) tag = MKTAG('x','d','5','4');
1215 else if (rate == 25) tag = MKTAG('x','d','5','5');
1216 else if (rate == 30) tag = MKTAG('x','d','5','1');
1217 else if (rate == 50) tag = MKTAG('x','d','5','a');
1218 else if (rate == 60) tag = MKTAG('x','d','5','9');
1220 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1222 if (rate == 24) tag = MKTAG('x','d','5','d');
1223 else if (rate == 25) tag = MKTAG('x','d','5','e');
1224 else if (rate == 30) tag = MKTAG('x','d','5','f');
1226 if (rate == 25) tag = MKTAG('x','d','5','c');
1227 else if (rate == 30) tag = MKTAG('x','d','5','b');
1235 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1237 int tag = track->enc->codec_tag;
1238 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1239 AVStream *st = track->st;
1240 int rate = av_q2d(find_fps(s, st));
1243 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1245 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P10) {
1246 if (track->enc->width == 960 && track->enc->height == 720) {
1248 if (rate == 24) tag = MKTAG('a','i','5','p');
1249 else if (rate == 25) tag = MKTAG('a','i','5','q');
1250 else if (rate == 30) tag = MKTAG('a','i','5','p');
1251 else if (rate == 50) tag = MKTAG('a','i','5','q');
1252 else if (rate == 60) tag = MKTAG('a','i','5','p');
1254 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
1256 if (rate == 24) tag = MKTAG('a','i','5','3');
1257 else if (rate == 25) tag = MKTAG('a','i','5','2');
1258 else if (rate == 30) tag = MKTAG('a','i','5','3');
1260 if (rate == 50) tag = MKTAG('a','i','5','5');
1261 else if (rate == 60) tag = MKTAG('a','i','5','6');
1264 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P10) {
1265 if (track->enc->width == 1280 && track->enc->height == 720) {
1267 if (rate == 24) tag = MKTAG('a','i','1','p');
1268 else if (rate == 25) tag = MKTAG('a','i','1','q');
1269 else if (rate == 30) tag = MKTAG('a','i','1','p');
1270 else if (rate == 50) tag = MKTAG('a','i','1','q');
1271 else if (rate == 60) tag = MKTAG('a','i','1','p');
1273 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1275 if (rate == 24) tag = MKTAG('a','i','1','3');
1276 else if (rate == 25) tag = MKTAG('a','i','1','2');
1277 else if (rate == 30) tag = MKTAG('a','i','1','3');
1279 if (rate == 25) tag = MKTAG('a','i','1','5');
1280 else if (rate == 50) tag = MKTAG('a','i','1','5');
1281 else if (rate == 60) tag = MKTAG('a','i','1','6');
1283 } else if ( track->enc->width == 4096 && track->enc->height == 2160
1284 || track->enc->width == 3840 && track->enc->height == 2160
1285 || track->enc->width == 2048 && track->enc->height == 1080) {
1286 tag = MKTAG('a','i','v','x');
1293 static const struct {
1294 enum AVPixelFormat pix_fmt;
1297 } mov_pix_fmt_tags[] = {
1298 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1299 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1300 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1301 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1302 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1303 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1304 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1305 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1306 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1307 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1308 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1309 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1310 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1311 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1312 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1315 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1317 int tag = track->enc->codec_tag;
1319 enum AVPixelFormat pix_fmt;
1321 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1322 if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
1323 tag = mov_pix_fmt_tags[i].tag;
1324 track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1325 if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
1330 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1331 track->enc->bits_per_coded_sample);
1332 if (tag == MKTAG('r','a','w',' ') &&
1333 track->enc->pix_fmt != pix_fmt &&
1334 track->enc->pix_fmt != AV_PIX_FMT_NONE)
1335 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1336 av_get_pix_fmt_name(track->enc->pix_fmt));
1340 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1342 int tag = track->enc->codec_tag;
1344 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1345 (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
1346 track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
1347 track->enc->codec_id == AV_CODEC_ID_H263 ||
1348 track->enc->codec_id == AV_CODEC_ID_H264 ||
1349 track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1350 av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
1351 if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
1352 tag = mov_get_dv_codec_tag(s, track);
1353 else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
1354 tag = mov_get_rawvideo_codec_tag(s, track);
1355 else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1356 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1357 else if (track->enc->codec_id == AV_CODEC_ID_H264)
1358 tag = mov_get_h264_codec_tag(s, track);
1359 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1360 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
1361 if (!tag) { // if no mac fcc found, try with Microsoft tags
1362 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
1364 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1365 "the file may be unplayable!\n");
1367 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1368 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
1369 if (!tag) { // if no mac fcc found, try with Microsoft tags
1370 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
1372 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1373 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1374 "the file may be unplayable!\n");
1377 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1378 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
1384 static const AVCodecTag codec_3gp_tags[] = {
1385 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1386 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1387 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1388 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1389 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1390 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1391 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1392 { AV_CODEC_ID_NONE, 0 },
1395 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1396 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1397 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1398 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1399 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1400 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1401 { AV_CODEC_ID_NONE, 0 },
1404 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1408 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1409 tag = mp4_get_codec_tag(s, track);
1410 else if (track->mode == MODE_ISM) {
1411 tag = mp4_get_codec_tag(s, track);
1412 if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
1413 tag = MKTAG('w', 'm', 'a', ' ');
1414 } else if (track->mode == MODE_IPOD)
1415 tag = ipod_get_codec_tag(s, track);
1416 else if (track->mode & MODE_3GP)
1417 tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
1418 else if (track->mode == MODE_F4V)
1419 tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
1421 tag = mov_get_codec_tag(s, track);
1426 /** Write uuid atom.
1427 * Needed to make file play in iPods running newest firmware
1428 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1430 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1433 ffio_wfourcc(pb, "uuid");
1434 avio_wb32(pb, 0x6b6840f2);
1435 avio_wb32(pb, 0x5f244fc5);
1436 avio_wb32(pb, 0xba39a51b);
1437 avio_wb32(pb, 0xcf0323f3);
1442 static const uint16_t fiel_data[] = {
1443 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1446 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
1448 unsigned mov_field_order = 0;
1449 if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
1450 mov_field_order = fiel_data[track->enc->field_order];
1454 ffio_wfourcc(pb, "fiel");
1455 avio_wb16(pb, mov_field_order);
1459 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1461 int64_t pos = avio_tell(pb);
1462 avio_wb32(pb, 0); /* size */
1463 avio_wl32(pb, track->tag); // store it byteswapped
1464 avio_wb32(pb, 0); /* Reserved */
1465 avio_wb16(pb, 0); /* Reserved */
1466 avio_wb16(pb, 1); /* Data-reference index */
1468 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1469 mov_write_esds_tag(pb, track);
1470 else if (track->enc->extradata_size)
1471 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1473 return update_size(pb, pos);
1476 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1479 av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
1480 track->enc->sample_aspect_ratio.den, INT_MAX);
1483 ffio_wfourcc(pb, "pasp");
1484 avio_wb32(pb, sar.num);
1485 avio_wb32(pb, sar.den);
1489 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1491 AVDictionaryEntry *encoder;
1492 int xdcam_res = (track->enc->width == 1280 && track->enc->height == 720)
1493 || (track->enc->width == 1440 && track->enc->height == 1080)
1494 || (track->enc->width == 1920 && track->enc->height == 1080);
1496 if (track->mode == MODE_MOV &&
1497 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1498 av_strlcpy(compressor_name, encoder->value, 32);
1499 } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1500 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1501 AVStream *st = track->st;
1502 int rate = av_q2d(find_fps(NULL, st));
1503 av_strlcatf(compressor_name, len, "XDCAM");
1504 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1505 av_strlcatf(compressor_name, len, " HD422");
1506 } else if(track->enc->width == 1440) {
1507 av_strlcatf(compressor_name, len, " HD");
1509 av_strlcatf(compressor_name, len, " EX");
1511 av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
1513 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1517 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1519 int64_t pos = avio_tell(pb);
1520 char compressor_name[32] = { 0 };
1522 avio_wb32(pb, 0); /* size */
1523 avio_wl32(pb, track->tag); // store it byteswapped
1524 avio_wb32(pb, 0); /* Reserved */
1525 avio_wb16(pb, 0); /* Reserved */
1526 avio_wb16(pb, 1); /* Data-reference index */
1528 avio_wb16(pb, 0); /* Codec stream version */
1529 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1530 if (track->mode == MODE_MOV) {
1531 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1532 if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
1533 avio_wb32(pb, 0); /* Temporal Quality */
1534 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1536 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1537 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1540 avio_wb32(pb, 0); /* Reserved */
1541 avio_wb32(pb, 0); /* Reserved */
1542 avio_wb32(pb, 0); /* Reserved */
1544 avio_wb16(pb, track->enc->width); /* Video width */
1545 avio_wb16(pb, track->height); /* Video height */
1546 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1547 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1548 avio_wb32(pb, 0); /* Data size (= 0) */
1549 avio_wb16(pb, 1); /* Frame count (= 1) */
1551 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1552 find_compressor(compressor_name, 32, track);
1553 avio_w8(pb, strlen(compressor_name));
1554 avio_write(pb, compressor_name, 31);
1556 if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1557 avio_wb16(pb, track->enc->bits_per_coded_sample);
1559 avio_wb16(pb, 0x18); /* Reserved */
1560 avio_wb16(pb, 0xffff); /* Reserved */
1561 if (track->tag == MKTAG('m','p','4','v'))
1562 mov_write_esds_tag(pb, track);
1563 else if (track->enc->codec_id == AV_CODEC_ID_H263)
1564 mov_write_d263_tag(pb);
1565 else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
1566 track->enc->codec_id == AV_CODEC_ID_SVQ3) {
1567 mov_write_extradata_tag(pb, track);
1569 } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
1570 mov_write_avid_tag(pb, track);
1571 else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
1572 mov_write_hvcc_tag(pb, track);
1573 else if (track->enc->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1574 mov_write_avcc_tag(pb, track);
1575 if (track->mode == MODE_IPOD)
1576 mov_write_uuid_tag_ipod(pb);
1577 } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1578 mov_write_dvc1_tag(pb, track);
1579 else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
1580 track->enc->codec_id == AV_CODEC_ID_VP6A) {
1581 /* Don't write any potential extradata here - the cropping
1582 * is signalled via the normal width/height fields. */
1583 } else if (track->vos_len > 0)
1584 mov_write_glbl_tag(pb, track);
1586 if (track->enc->codec_id != AV_CODEC_ID_H264 &&
1587 track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
1588 track->enc->codec_id != AV_CODEC_ID_DNXHD)
1589 if (track->enc->field_order != AV_FIELD_UNKNOWN)
1590 mov_write_fiel_tag(pb, track);
1592 if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1593 track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1594 mov_write_pasp_tag(pb, track);
1597 return update_size(pb, pos);
1600 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1602 int64_t pos = avio_tell(pb);
1603 avio_wb32(pb, 0); /* size */
1604 ffio_wfourcc(pb, "rtp ");
1605 avio_wb32(pb, 0); /* Reserved */
1606 avio_wb16(pb, 0); /* Reserved */
1607 avio_wb16(pb, 1); /* Data-reference index */
1609 avio_wb16(pb, 1); /* Hint track version */
1610 avio_wb16(pb, 1); /* Highest compatible version */
1611 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1613 avio_wb32(pb, 12); /* size */
1614 ffio_wfourcc(pb, "tims");
1615 avio_wb32(pb, track->timescale);
1617 return update_size(pb, pos);
1620 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1622 uint64_t str_size =strlen(reel_name);
1623 int64_t pos = avio_tell(pb);
1625 if (str_size >= UINT16_MAX){
1626 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1628 return AVERROR(EINVAL);
1631 avio_wb32(pb, 0); /* size */
1632 ffio_wfourcc(pb, "name"); /* Data format */
1633 avio_wb16(pb, str_size); /* string size */
1634 avio_wb16(pb, track->language); /* langcode */
1635 avio_write(pb, reel_name, str_size); /* reel name */
1636 return update_size(pb,pos);
1639 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1641 int64_t pos = avio_tell(pb);
1643 int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
1644 int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
1645 AVDictionaryEntry *t = NULL;
1647 if (nb_frames > 255) {
1648 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1649 return AVERROR(EINVAL);
1652 avio_wb32(pb, 0); /* size */
1653 ffio_wfourcc(pb, "tmcd"); /* Data format */
1654 avio_wb32(pb, 0); /* Reserved */
1655 avio_wb32(pb, 1); /* Data reference index */
1656 avio_wb32(pb, 0); /* Flags */
1657 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1658 avio_wb32(pb, track->timescale); /* Timescale */
1659 avio_wb32(pb, frame_duration); /* Frame duration */
1660 avio_w8(pb, nb_frames); /* Number of frames */
1661 avio_w8(pb, 0); /* Reserved */
1664 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1666 if (t && utf8len(t->value))
1667 mov_write_source_reference_tag(pb, track, t->value);
1669 avio_wb16(pb, 0); /* zero size */
1672 avio_wb32(pb, 0); /* size */
1673 ffio_wfourcc(pb, "tmcd"); /* Data format */
1674 avio_wb32(pb, 0); /* Reserved */
1675 avio_wb32(pb, 1); /* Data reference index */
1676 if (track->enc->extradata_size)
1677 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1679 return update_size(pb, pos);
1682 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
1684 int64_t pos = avio_tell(pb);
1685 avio_wb32(pb, 0); /* size */
1686 ffio_wfourcc(pb, "stsd");
1687 avio_wb32(pb, 0); /* version & flags */
1688 avio_wb32(pb, 1); /* entry count */
1689 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1690 mov_write_video_tag(pb, track);
1691 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1692 mov_write_audio_tag(pb, track);
1693 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1694 mov_write_subtitle_tag(pb, track);
1695 else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1696 mov_write_rtp_tag(pb, track);
1697 else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1698 mov_write_tmcd_tag(pb, track);
1699 return update_size(pb, pos);
1702 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1704 MOVStts *ctts_entries;
1705 uint32_t entries = 0;
1709 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1710 ctts_entries[0].count = 1;
1711 ctts_entries[0].duration = track->cluster[0].cts;
1712 for (i = 1; i < track->entry; i++) {
1713 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1714 ctts_entries[entries].count++; /* compress */
1717 ctts_entries[entries].duration = track->cluster[i].cts;
1718 ctts_entries[entries].count = 1;
1721 entries++; /* last one */
1722 atom_size = 16 + (entries * 8);
1723 avio_wb32(pb, atom_size); /* size */
1724 ffio_wfourcc(pb, "ctts");
1725 avio_wb32(pb, 0); /* version & flags */
1726 avio_wb32(pb, entries); /* entry count */
1727 for (i = 0; i < entries; i++) {
1728 avio_wb32(pb, ctts_entries[i].count);
1729 avio_wb32(pb, ctts_entries[i].duration);
1731 av_free(ctts_entries);
1735 /* Time to sample atom */
1736 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1738 MOVStts *stts_entries;
1739 uint32_t entries = -1;
1743 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1744 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1745 stts_entries[0].count = track->sample_count;
1746 stts_entries[0].duration = 1;
1749 stts_entries = track->entry ?
1750 av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */
1752 for (i = 0; i < track->entry; i++) {
1753 int duration = get_cluster_duration(track, i);
1754 if (i && duration == stts_entries[entries].duration) {
1755 stts_entries[entries].count++; /* compress */
1758 stts_entries[entries].duration = duration;
1759 stts_entries[entries].count = 1;
1762 entries++; /* last one */
1764 atom_size = 16 + (entries * 8);
1765 avio_wb32(pb, atom_size); /* size */
1766 ffio_wfourcc(pb, "stts");
1767 avio_wb32(pb, 0); /* version & flags */
1768 avio_wb32(pb, entries); /* entry count */
1769 for (i = 0; i < entries; i++) {
1770 avio_wb32(pb, stts_entries[i].count);
1771 avio_wb32(pb, stts_entries[i].duration);
1773 av_free(stts_entries);
1777 static int mov_write_dref_tag(AVIOContext *pb)
1779 avio_wb32(pb, 28); /* size */
1780 ffio_wfourcc(pb, "dref");
1781 avio_wb32(pb, 0); /* version & flags */
1782 avio_wb32(pb, 1); /* entry count */
1784 avio_wb32(pb, 0xc); /* size */
1785 //FIXME add the alis and rsrc atom
1786 ffio_wfourcc(pb, "url ");
1787 avio_wb32(pb, 1); /* version & flags */
1792 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1794 int64_t pos = avio_tell(pb);
1795 avio_wb32(pb, 0); /* size */
1796 ffio_wfourcc(pb, "stbl");
1797 mov_write_stsd_tag(pb, track);
1798 mov_write_stts_tag(pb, track);
1799 if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1800 track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1801 track->has_keyframes && track->has_keyframes < track->entry)
1802 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1803 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1804 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1805 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1806 track->flags & MOV_TRACK_CTTS && track->entry)
1807 mov_write_ctts_tag(pb, track);
1808 mov_write_stsc_tag(pb, track);
1809 mov_write_stsz_tag(pb, track);
1810 mov_write_stco_tag(pb, track);
1811 return update_size(pb, pos);
1814 static int mov_write_dinf_tag(AVIOContext *pb)
1816 int64_t pos = avio_tell(pb);
1817 avio_wb32(pb, 0); /* size */
1818 ffio_wfourcc(pb, "dinf");
1819 mov_write_dref_tag(pb);
1820 return update_size(pb, pos);
1823 static int mov_write_nmhd_tag(AVIOContext *pb)
1826 ffio_wfourcc(pb, "nmhd");
1831 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
1833 int64_t pos = avio_tell(pb);
1834 const char *font = "Lucida Grande";
1835 avio_wb32(pb, 0); /* size */
1836 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
1837 avio_wb32(pb, 0); /* version & flags */
1838 avio_wb16(pb, 0); /* text font */
1839 avio_wb16(pb, 0); /* text face */
1840 avio_wb16(pb, 12); /* text size */
1841 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
1842 avio_wb16(pb, 0x0000); /* text color (red) */
1843 avio_wb16(pb, 0x0000); /* text color (green) */
1844 avio_wb16(pb, 0x0000); /* text color (blue) */
1845 avio_wb16(pb, 0xffff); /* background color (red) */
1846 avio_wb16(pb, 0xffff); /* background color (green) */
1847 avio_wb16(pb, 0xffff); /* background color (blue) */
1848 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
1849 avio_write(pb, font, strlen(font)); /* font name */
1850 return update_size(pb, pos);
1853 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
1855 int64_t pos = avio_tell(pb);
1856 avio_wb32(pb, 0); /* size */
1857 ffio_wfourcc(pb, "gmhd");
1858 avio_wb32(pb, 0x18); /* gmin size */
1859 ffio_wfourcc(pb, "gmin");/* generic media info */
1860 avio_wb32(pb, 0); /* version & flags */
1861 avio_wb16(pb, 0x40); /* graphics mode = */
1862 avio_wb16(pb, 0x8000); /* opColor (r?) */
1863 avio_wb16(pb, 0x8000); /* opColor (g?) */
1864 avio_wb16(pb, 0x8000); /* opColor (b?) */
1865 avio_wb16(pb, 0); /* balance */
1866 avio_wb16(pb, 0); /* reserved */
1869 * This special text atom is required for
1870 * Apple Quicktime chapters. The contents
1871 * don't appear to be documented, so the
1872 * bytes are copied verbatim.
1874 if (track->tag != MKTAG('c','6','0','8')) {
1875 avio_wb32(pb, 0x2C); /* size */
1876 ffio_wfourcc(pb, "text");
1877 avio_wb16(pb, 0x01);
1878 avio_wb32(pb, 0x00);
1879 avio_wb32(pb, 0x00);
1880 avio_wb32(pb, 0x00);
1881 avio_wb32(pb, 0x01);
1882 avio_wb32(pb, 0x00);
1883 avio_wb32(pb, 0x00);
1884 avio_wb32(pb, 0x00);
1885 avio_wb32(pb, 0x00004000);
1886 avio_wb16(pb, 0x0000);
1889 if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1890 int64_t tmcd_pos = avio_tell(pb);
1891 avio_wb32(pb, 0); /* size */
1892 ffio_wfourcc(pb, "tmcd");
1893 mov_write_tcmi_tag(pb, track);
1894 update_size(pb, tmcd_pos);
1896 return update_size(pb, pos);
1899 static int mov_write_smhd_tag(AVIOContext *pb)
1901 avio_wb32(pb, 16); /* size */
1902 ffio_wfourcc(pb, "smhd");
1903 avio_wb32(pb, 0); /* version & flags */
1904 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1905 avio_wb16(pb, 0); /* reserved */
1909 static int mov_write_vmhd_tag(AVIOContext *pb)
1911 avio_wb32(pb, 0x14); /* size (always 0x14) */
1912 ffio_wfourcc(pb, "vmhd");
1913 avio_wb32(pb, 0x01); /* version & flags */
1914 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1918 static int is_clcp_track(MOVTrack *track)
1920 return track->tag == MKTAG('c','7','0','8') ||
1921 track->tag == MKTAG('c','6','0','8');
1924 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1926 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1927 int64_t pos = avio_tell(pb);
1931 descr = "DataHandler";
1934 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1935 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1937 descr = "VideoHandler";
1938 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1940 descr = "SoundHandler";
1941 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1942 if (is_clcp_track(track)) {
1944 descr = "ClosedCaptionHandler";
1946 if (track->tag == MKTAG('t','x','3','g')) {
1948 } else if (track->tag == MKTAG('m','p','4','s')) {
1953 descr = "SubtitleHandler";
1955 } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1957 descr = "HintHandler";
1958 } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1960 descr = "TimeCodeHandler";
1963 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
1964 track->enc->codec_tag);
1966 av_log(track->enc, AV_LOG_WARNING,
1967 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
1968 tag_buf, track->enc->codec_tag);
1971 // hdlr.name is used by some players to identify the content title
1972 // of the track. So if an alternate handler description is
1973 // specified, use it.
1974 AVDictionaryEntry *t;
1975 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
1976 if (t && utf8len(t->value))
1981 avio_wb32(pb, 0); /* size */
1982 ffio_wfourcc(pb, "hdlr");
1983 avio_wb32(pb, 0); /* Version & flags */
1984 avio_write(pb, hdlr, 4); /* handler */
1985 ffio_wfourcc(pb, hdlr_type); /* handler type */
1986 avio_wb32(pb, 0); /* reserved */
1987 avio_wb32(pb, 0); /* reserved */
1988 avio_wb32(pb, 0); /* reserved */
1989 if (!track || track->mode == MODE_MOV)
1990 avio_w8(pb, strlen(descr)); /* pascal string */
1991 avio_write(pb, descr, strlen(descr)); /* handler description */
1992 if (track && track->mode != MODE_MOV)
1993 avio_w8(pb, 0); /* c string */
1994 return update_size(pb, pos);
1997 static int mov_write_hmhd_tag(AVIOContext *pb)
1999 /* This atom must be present, but leaving the values at zero
2000 * seems harmless. */
2001 avio_wb32(pb, 28); /* size */
2002 ffio_wfourcc(pb, "hmhd");
2003 avio_wb32(pb, 0); /* version, flags */
2004 avio_wb16(pb, 0); /* maxPDUsize */
2005 avio_wb16(pb, 0); /* avgPDUsize */
2006 avio_wb32(pb, 0); /* maxbitrate */
2007 avio_wb32(pb, 0); /* avgbitrate */
2008 avio_wb32(pb, 0); /* reserved */
2012 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
2014 int64_t pos = avio_tell(pb);
2015 avio_wb32(pb, 0); /* size */
2016 ffio_wfourcc(pb, "minf");
2017 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
2018 mov_write_vmhd_tag(pb);
2019 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2020 mov_write_smhd_tag(pb);
2021 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2022 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2023 mov_write_gmhd_tag(pb, track);
2025 mov_write_nmhd_tag(pb);
2027 } else if (track->tag == MKTAG('r','t','p',' ')) {
2028 mov_write_hmhd_tag(pb);
2029 } else if (track->tag == MKTAG('t','m','c','d')) {
2030 mov_write_gmhd_tag(pb, track);
2032 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2033 mov_write_hdlr_tag(pb, NULL);
2034 mov_write_dinf_tag(pb);
2035 mov_write_stbl_tag(pb, track);
2036 return update_size(pb, pos);
2039 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2042 int version = track->track_duration < INT32_MAX ? 0 : 1;
2044 if (track->mode == MODE_ISM)
2047 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2048 ffio_wfourcc(pb, "mdhd");
2049 avio_w8(pb, version);
2050 avio_wb24(pb, 0); /* flags */
2052 avio_wb64(pb, track->time);
2053 avio_wb64(pb, track->time);
2055 avio_wb32(pb, track->time); /* creation time */
2056 avio_wb32(pb, track->time); /* modification time */
2058 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2059 if (!track->entry && mov->mode == MODE_ISM)
2060 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2061 else if (!track->entry)
2062 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2064 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2065 avio_wb16(pb, track->language); /* language */
2066 avio_wb16(pb, 0); /* reserved (quality) */
2068 if (version != 0 && track->mode == MODE_MOV) {
2069 av_log(NULL, AV_LOG_ERROR,
2070 "FATAL error, file duration too long for timebase, this file will not be\n"
2071 "playable with quicktime. Choose a different timebase or a different\n"
2072 "container format\n");
2078 static int mov_write_mdia_tag(AVIOContext *pb, MOVMuxContext *mov,
2081 int64_t pos = avio_tell(pb);
2082 avio_wb32(pb, 0); /* size */
2083 ffio_wfourcc(pb, "mdia");
2084 mov_write_mdhd_tag(pb, mov, track);
2085 mov_write_hdlr_tag(pb, track);
2086 mov_write_minf_tag(pb, track);
2087 return update_size(pb, pos);
2090 /* transformation matrix
2094 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2095 int16_t d, int16_t tx, int16_t ty)
2097 avio_wb32(pb, a << 16); /* 16.16 format */
2098 avio_wb32(pb, b << 16); /* 16.16 format */
2099 avio_wb32(pb, 0); /* u in 2.30 format */
2100 avio_wb32(pb, c << 16); /* 16.16 format */
2101 avio_wb32(pb, d << 16); /* 16.16 format */
2102 avio_wb32(pb, 0); /* v in 2.30 format */
2103 avio_wb32(pb, tx << 16); /* 16.16 format */
2104 avio_wb32(pb, ty << 16); /* 16.16 format */
2105 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2108 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2109 MOVTrack *track, AVStream *st)
2111 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2112 track->timescale, AV_ROUND_UP);
2113 int version = duration < INT32_MAX ? 0 : 1;
2114 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2120 if (mov->per_stream_grouping)
2123 group = st->codec->codec_type;
2126 if (track->flags & MOV_TRACK_ENABLED)
2127 flags |= MOV_TKHD_FLAG_ENABLED;
2129 if (track->mode == MODE_ISM)
2132 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2133 ffio_wfourcc(pb, "tkhd");
2134 avio_w8(pb, version);
2135 avio_wb24(pb, flags);
2137 avio_wb64(pb, track->time);
2138 avio_wb64(pb, track->time);
2140 avio_wb32(pb, track->time); /* creation time */
2141 avio_wb32(pb, track->time); /* modification time */
2143 avio_wb32(pb, track->track_id); /* track-id */
2144 avio_wb32(pb, 0); /* reserved */
2145 if (!track->entry && mov->mode == MODE_ISM)
2146 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2147 else if (!track->entry)
2148 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2150 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2152 avio_wb32(pb, 0); /* reserved */
2153 avio_wb32(pb, 0); /* reserved */
2154 avio_wb16(pb, 0); /* layer */
2155 avio_wb16(pb, group); /* alternate group) */
2156 /* Volume, only for audio */
2157 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2158 avio_wb16(pb, 0x0100);
2161 avio_wb16(pb, 0); /* reserved */
2163 /* Matrix structure */
2164 if (st && st->metadata) {
2165 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2166 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2168 if (rotation == 90) {
2169 write_matrix(pb, 0, 1, -1, 0, track->enc->height, 0);
2170 } else if (rotation == 180) {
2171 write_matrix(pb, -1, 0, 0, -1, track->enc->width, track->enc->height);
2172 } else if (rotation == 270) {
2173 write_matrix(pb, 0, -1, 1, 0, 0, track->enc->width);
2175 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2177 /* Track width and height, for visual only */
2178 if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
2179 track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2180 if (track->mode == MODE_MOV) {
2181 avio_wb32(pb, track->enc->width << 16);
2182 avio_wb32(pb, track->height << 16);
2184 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2185 if (!sample_aspect_ratio || track->height != track->enc->height)
2186 sample_aspect_ratio = 1;
2187 avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
2188 avio_wb32(pb, track->height * 0x10000);
2197 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2199 int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
2200 track->enc->sample_aspect_ratio.den);
2202 int64_t pos = avio_tell(pb);
2204 avio_wb32(pb, 0); /* size */
2205 ffio_wfourcc(pb, "tapt");
2208 ffio_wfourcc(pb, "clef");
2210 avio_wb32(pb, width << 16);
2211 avio_wb32(pb, track->enc->height << 16);
2214 ffio_wfourcc(pb, "prof");
2216 avio_wb32(pb, width << 16);
2217 avio_wb32(pb, track->enc->height << 16);
2220 ffio_wfourcc(pb, "enof");
2222 avio_wb32(pb, track->enc->width << 16);
2223 avio_wb32(pb, track->enc->height << 16);
2225 return update_size(pb, pos);
2228 // This box seems important for the psp playback ... without it the movie seems to hang
2229 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2232 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2233 track->timescale, AV_ROUND_UP);
2234 int version = duration < INT32_MAX ? 0 : 1;
2235 int entry_size, entry_count, size;
2236 int64_t delay, start_ct = track->start_cts;
2237 int64_t start_dts = track->start_dts;
2240 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2242 av_log(mov->fc, AV_LOG_DEBUG,
2243 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2244 track->cluster[0].dts, track->cluster[0].cts,
2245 start_dts, start_ct, track->track_id);
2246 start_dts = track->cluster[0].dts;
2247 start_ct = track->cluster[0].cts;
2251 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2252 track->timescale, AV_ROUND_DOWN);
2253 version |= delay < INT32_MAX ? 0 : 1;
2255 entry_size = (version == 1) ? 20 : 12;
2256 entry_count = 1 + (delay > 0);
2257 size = 24 + entry_count * entry_size;
2259 /* write the atom data */
2260 avio_wb32(pb, size);
2261 ffio_wfourcc(pb, "edts");
2262 avio_wb32(pb, size - 8);
2263 ffio_wfourcc(pb, "elst");
2264 avio_w8(pb, version);
2265 avio_wb24(pb, 0); /* flags */
2267 avio_wb32(pb, entry_count);
2268 if (delay > 0) { /* add an empty edit to delay presentation */
2269 /* In the positive delay case, the delay includes the cts
2270 * offset, and the second edit list entry below trims out
2271 * the same amount from the actual content. This makes sure
2272 * that the offsetted last sample is included in the edit
2273 * list duration as well. */
2275 avio_wb64(pb, delay);
2278 avio_wb32(pb, delay);
2281 avio_wb32(pb, 0x00010000);
2283 /* Avoid accidentally ending up with start_ct = -1 which has got a
2284 * special meaning. Normally start_ct should end up positive or zero
2285 * here, but use FFMIN in case dts is a a small positive integer
2286 * rounded to 0 when represented in MOV_TIMESCALE units. */
2287 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2288 start_ct = -FFMIN(start_dts, 0);
2289 /* Note, this delay is calculated from the pts of the first sample,
2290 * ensuring that we don't reduce the duration for cases with
2295 /* For fragmented files, we don't know the full length yet. Setting
2296 * duration to 0 allows us to only specify the offset, including
2297 * the rest of the content (from all future fragments) without specifying
2298 * an explicit duration. */
2299 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2304 avio_wb64(pb, duration);
2305 avio_wb64(pb, start_ct);
2307 avio_wb32(pb, duration);
2308 avio_wb32(pb, start_ct);
2310 avio_wb32(pb, 0x00010000);
2314 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2316 avio_wb32(pb, 20); // size
2317 ffio_wfourcc(pb, "tref");
2318 avio_wb32(pb, 12); // size (subatom)
2319 avio_wl32(pb, track->tref_tag);
2320 avio_wb32(pb, track->tref_id);
2324 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2325 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2327 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2328 ffio_wfourcc(pb, "uuid");
2329 ffio_wfourcc(pb, "USMT");
2330 avio_wb32(pb, 0x21d24fce);
2331 avio_wb32(pb, 0xbb88695c);
2332 avio_wb32(pb, 0xfac9c740);
2333 avio_wb32(pb, 0x1c); // another size here!
2334 ffio_wfourcc(pb, "MTDT");
2335 avio_wb32(pb, 0x00010012);
2336 avio_wb32(pb, 0x0a);
2337 avio_wb32(pb, 0x55c40000);
2343 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2345 AVFormatContext *ctx = track->rtp_ctx;
2346 char buf[1000] = "";
2349 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2350 NULL, NULL, 0, 0, ctx);
2351 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2354 avio_wb32(pb, len + 24);
2355 ffio_wfourcc(pb, "udta");
2356 avio_wb32(pb, len + 16);
2357 ffio_wfourcc(pb, "hnti");
2358 avio_wb32(pb, len + 8);
2359 ffio_wfourcc(pb, "sdp ");
2360 avio_write(pb, buf, len);
2364 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2365 const char *tag, const char *str)
2367 int64_t pos = avio_tell(pb);
2368 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2369 if (!t || !utf8len(t->value))
2372 avio_wb32(pb, 0); /* size */
2373 ffio_wfourcc(pb, tag); /* type */
2374 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2375 return update_size(pb, pos);
2378 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2381 AVIOContext *pb_buf;
2385 if (!st || mov->fc->flags & AVFMT_FLAG_BITEXACT)
2388 ret = avio_open_dyn_buf(&pb_buf);
2392 if (mov->mode & MODE_MP4)
2393 mov_write_track_metadata(pb_buf, st, "name", "title");
2395 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2396 avio_wb32(pb, size + 8);
2397 ffio_wfourcc(pb, "udta");
2398 avio_write(pb, buf, size);
2405 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
2406 MOVTrack *track, AVStream *st)
2408 int64_t pos = avio_tell(pb);
2409 int entry_backup = track->entry;
2410 int chunk_backup = track->chunkCount;
2411 /* If we want to have an empty moov, but some samples already have been
2412 * buffered (delay_moov), pretend that no samples have been written yet. */
2413 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2414 track->chunkCount = track->entry = 0;
2416 avio_wb32(pb, 0); /* size */
2417 ffio_wfourcc(pb, "trak");
2418 mov_write_tkhd_tag(pb, mov, track, st);
2420 av_assert2(mov->use_editlist >= 0);
2422 if (track->start_dts != AV_NOPTS_VALUE) {
2423 if (mov->use_editlist)
2424 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2425 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2426 av_log(mov->fc, AV_LOG_WARNING,
2427 "Not writing any edit list even though one would have been required\n");
2430 if (track->tref_tag)
2431 mov_write_tref_tag(pb, track);
2432 mov_write_mdia_tag(pb, mov, track);
2433 if (track->mode == MODE_PSP)
2434 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2435 if (track->tag == MKTAG('r','t','p',' '))
2436 mov_write_udta_sdp(pb, track);
2437 if (track->mode == MODE_MOV) {
2438 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2439 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2440 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2441 mov_write_tapt_tag(pb, track);
2444 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2445 mov_write_tapt_tag(pb, track);
2448 mov_write_track_udta_tag(pb, mov, st);
2449 track->entry = entry_backup;
2450 track->chunkCount = chunk_backup;
2451 return update_size(pb, pos);
2454 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2456 int i, has_audio = 0, has_video = 0;
2457 int64_t pos = avio_tell(pb);
2458 int audio_profile = mov->iods_audio_profile;
2459 int video_profile = mov->iods_video_profile;
2460 for (i = 0; i < mov->nb_streams; i++) {
2461 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2462 has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
2463 has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
2466 if (audio_profile < 0)
2467 audio_profile = 0xFF - has_audio;
2468 if (video_profile < 0)
2469 video_profile = 0xFF - has_video;
2470 avio_wb32(pb, 0x0); /* size */
2471 ffio_wfourcc(pb, "iods");
2472 avio_wb32(pb, 0); /* version & flags */
2473 put_descr(pb, 0x10, 7);
2474 avio_wb16(pb, 0x004f);
2477 avio_w8(pb, audio_profile);
2478 avio_w8(pb, video_profile);
2480 return update_size(pb, pos);
2483 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2485 avio_wb32(pb, 0x20); /* size */
2486 ffio_wfourcc(pb, "trex");
2487 avio_wb32(pb, 0); /* version & flags */
2488 avio_wb32(pb, track->track_id); /* track ID */
2489 avio_wb32(pb, 1); /* default sample description index */
2490 avio_wb32(pb, 0); /* default sample duration */
2491 avio_wb32(pb, 0); /* default sample size */
2492 avio_wb32(pb, 0); /* default sample flags */
2496 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2498 int64_t pos = avio_tell(pb);
2500 avio_wb32(pb, 0x0); /* size */
2501 ffio_wfourcc(pb, "mvex");
2502 for (i = 0; i < mov->nb_streams; i++)
2503 mov_write_trex_tag(pb, &mov->tracks[i]);
2504 return update_size(pb, pos);
2507 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2509 int max_track_id = 1, i;
2510 int64_t max_track_len_temp, max_track_len = 0;
2513 for (i = 0; i < mov->nb_streams; i++) {
2514 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2515 max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2517 mov->tracks[i].timescale,
2519 if (max_track_len < max_track_len_temp)
2520 max_track_len = max_track_len_temp;
2521 if (max_track_id < mov->tracks[i].track_id)
2522 max_track_id = mov->tracks[i].track_id;
2525 /* If using delay_moov, make sure the output is the same as if no
2526 * samples had been written yet. */
2527 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2532 version = max_track_len < UINT32_MAX ? 0 : 1;
2533 (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
2534 ffio_wfourcc(pb, "mvhd");
2535 avio_w8(pb, version);
2536 avio_wb24(pb, 0); /* flags */
2538 avio_wb64(pb, mov->time);
2539 avio_wb64(pb, mov->time);
2541 avio_wb32(pb, mov->time); /* creation time */
2542 avio_wb32(pb, mov->time); /* modification time */
2544 avio_wb32(pb, MOV_TIMESCALE);
2545 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2547 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2548 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2549 avio_wb16(pb, 0); /* reserved */
2550 avio_wb32(pb, 0); /* reserved */
2551 avio_wb32(pb, 0); /* reserved */
2553 /* Matrix structure */
2554 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2556 avio_wb32(pb, 0); /* reserved (preview time) */
2557 avio_wb32(pb, 0); /* reserved (preview duration) */
2558 avio_wb32(pb, 0); /* reserved (poster time) */
2559 avio_wb32(pb, 0); /* reserved (selection time) */
2560 avio_wb32(pb, 0); /* reserved (selection duration) */
2561 avio_wb32(pb, 0); /* reserved (current time) */
2562 avio_wb32(pb, max_track_id + 1); /* Next track id */
2566 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2569 avio_wb32(pb, 33); /* size */
2570 ffio_wfourcc(pb, "hdlr");
2573 ffio_wfourcc(pb, "mdir");
2574 ffio_wfourcc(pb, "appl");
2581 /* helper function to write a data tag with the specified string as data */
2582 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2585 int size = 16 + strlen(data);
2586 avio_wb32(pb, size); /* size */
2587 ffio_wfourcc(pb, "data");
2590 avio_write(pb, data, strlen(data));
2594 lang = ff_mov_iso639_to_lang("und", 1);
2595 avio_wb16(pb, strlen(data)); /* string length */
2596 avio_wb16(pb, lang);
2597 avio_write(pb, data, strlen(data));
2598 return strlen(data) + 4;
2602 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2603 const char *value, int lang, int long_style)
2606 if (value && value[0]) {
2607 int64_t pos = avio_tell(pb);
2608 avio_wb32(pb, 0); /* size */
2609 ffio_wfourcc(pb, name);
2610 mov_write_string_data_tag(pb, value, lang, long_style);
2611 size = update_size(pb, pos);
2616 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2617 const char *name, const char *tag,
2620 int l, lang = 0, len, len2;
2621 AVDictionaryEntry *t, *t2 = NULL;
2624 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2627 len = strlen(t->key);
2628 snprintf(tag2, sizeof(tag2), "%s-", tag);
2629 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2630 len2 = strlen(t2->key);
2631 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2632 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2637 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2640 /* iTunes bpm number */
2641 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2643 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2644 int size = 0, tmpo = t ? atoi(t->value) : 0;
2647 avio_wb32(pb, size);
2648 ffio_wfourcc(pb, "tmpo");
2649 avio_wb32(pb, size-8); /* size */
2650 ffio_wfourcc(pb, "data");
2651 avio_wb32(pb, 0x15); //type specifier
2653 avio_wb16(pb, tmpo); // data
2658 /* iTunes track or disc number */
2659 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2660 AVFormatContext *s, int disc)
2662 AVDictionaryEntry *t = av_dict_get(s->metadata,
2663 disc ? "disc" : "track",
2665 int size = 0, track = t ? atoi(t->value) : 0;
2668 char *slash = strchr(t->value, '/');
2670 tracks = atoi(slash + 1);
2671 avio_wb32(pb, 32); /* size */
2672 ffio_wfourcc(pb, disc ? "disk" : "trkn");
2673 avio_wb32(pb, 24); /* size */
2674 ffio_wfourcc(pb, "data");
2675 avio_wb32(pb, 0); // 8 bytes empty
2677 avio_wb16(pb, 0); // empty
2678 avio_wb16(pb, track); // track / disc number
2679 avio_wb16(pb, tracks); // total track / disc number
2680 avio_wb16(pb, 0); // empty
2686 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2687 const char *name, const char *tag,
2690 AVDictionaryEntry *t = NULL;
2692 int size = 24 + len;
2694 if (len != 1 && len != 4)
2697 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2699 num = atoi(t->value);
2701 avio_wb32(pb, size);
2702 ffio_wfourcc(pb, name);
2703 avio_wb32(pb, size - 8);
2704 ffio_wfourcc(pb, "data");
2705 avio_wb32(pb, 0x15);
2707 if (len==4) avio_wb32(pb, num);
2708 else avio_w8 (pb, num);
2713 /* iTunes meta data list */
2714 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2717 int64_t pos = avio_tell(pb);
2718 avio_wb32(pb, 0); /* size */
2719 ffio_wfourcc(pb, "ilst");
2720 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
2721 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
2722 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2723 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2724 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
2725 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
2727 !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2728 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2729 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
2730 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
2731 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2732 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2733 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
2734 mov_write_string_metadata(s, pb, "desc", "description",1);
2735 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
2736 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
2737 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
2738 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
2739 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
2740 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
2741 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
2742 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
2743 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
2744 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
2745 mov_write_trkn_tag(pb, mov, s, 0); // track number
2746 mov_write_trkn_tag(pb, mov, s, 1); // disc number
2747 mov_write_tmpo_tag(pb, s);
2748 return update_size(pb, pos);
2751 /* iTunes meta data tag */
2752 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2756 int64_t pos = avio_tell(pb);
2757 avio_wb32(pb, 0); /* size */
2758 ffio_wfourcc(pb, "meta");
2760 mov_write_itunes_hdlr_tag(pb, mov, s);
2761 mov_write_ilst_tag(pb, mov, s);
2762 size = update_size(pb, pos);
2766 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
2767 const char *name, const char *key)
2770 AVDictionaryEntry *t;
2772 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
2775 len = strlen(t->value);
2778 avio_wb32(pb, size);
2779 ffio_wfourcc(pb, name);
2780 avio_write(pb, t->value, len);
2786 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2790 GET_UTF8(val, *b++, return -1;)
2793 avio_wb16(pb, 0x00);
2797 static uint16_t language_code(const char *str)
2799 return (((str[0] - 0x60) & 0x1F) << 10) +
2800 (((str[1] - 0x60) & 0x1F) << 5) +
2801 (( str[2] - 0x60) & 0x1F);
2804 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2805 const char *tag, const char *str)
2807 int64_t pos = avio_tell(pb);
2808 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2809 if (!t || !utf8len(t->value))
2811 avio_wb32(pb, 0); /* size */
2812 ffio_wfourcc(pb, tag); /* type */
2813 avio_wb32(pb, 0); /* version + flags */
2814 if (!strcmp(tag, "yrrc"))
2815 avio_wb16(pb, atoi(t->value));
2817 avio_wb16(pb, language_code("eng")); /* language */
2818 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2819 if (!strcmp(tag, "albm") &&
2820 (t = av_dict_get(s->metadata, "track", NULL, 0)))
2821 avio_w8(pb, atoi(t->value));
2823 return update_size(pb, pos);
2826 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2828 int64_t pos = avio_tell(pb);
2829 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2831 avio_wb32(pb, 0); // size
2832 ffio_wfourcc(pb, "chpl");
2833 avio_wb32(pb, 0x01000000); // version + flags
2834 avio_wb32(pb, 0); // unknown
2835 avio_w8(pb, nb_chapters);
2837 for (i = 0; i < nb_chapters; i++) {
2838 AVChapter *c = s->chapters[i];
2839 AVDictionaryEntry *t;
2840 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2842 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2843 int len = FFMIN(strlen(t->value), 255);
2845 avio_write(pb, t->value, len);
2849 return update_size(pb, pos);
2852 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2855 AVIOContext *pb_buf;
2859 ret = avio_open_dyn_buf(&pb_buf);
2863 if (mov->mode & MODE_3GP) {
2864 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2865 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2866 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2867 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2868 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2869 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2870 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2871 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2872 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2873 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
2874 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
2875 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
2876 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
2877 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
2878 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
2879 // currently ignored by mov.c
2880 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
2881 // add support for libquicktime, this atom is also actually read by mov.c
2882 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
2883 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
2884 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
2885 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
2887 /* iTunes meta data */
2888 mov_write_meta_tag(pb_buf, mov, s);
2891 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
2892 mov_write_chpl_tag(pb_buf, s);
2894 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2895 avio_wb32(pb, size + 8);
2896 ffio_wfourcc(pb, "udta");
2897 avio_write(pb, buf, size);
2904 static void mov_write_psp_udta_tag(AVIOContext *pb,
2905 const char *str, const char *lang, int type)
2907 int len = utf8len(str) + 1;
2910 avio_wb16(pb, len * 2 + 10); /* size */
2911 avio_wb32(pb, type); /* type */
2912 avio_wb16(pb, language_code(lang)); /* language */
2913 avio_wb16(pb, 0x01); /* ? */
2914 ascii_to_wc(pb, str);
2917 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2919 MOVMuxContext *mov = s->priv_data;
2920 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2924 pos = avio_tell(pb);
2925 avio_wb32(pb, 0); /* size placeholder*/
2926 ffio_wfourcc(pb, "uuid");
2927 ffio_wfourcc(pb, "USMT");
2928 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2929 avio_wb32(pb, 0xbb88695c);
2930 avio_wb32(pb, 0xfac9c740);
2932 pos2 = avio_tell(pb);
2933 avio_wb32(pb, 0); /* size placeholder*/
2934 ffio_wfourcc(pb, "MTDT");
2938 avio_wb16(pb, 0x0C); /* size */
2939 avio_wb32(pb, 0x0B); /* type */
2940 avio_wb16(pb, language_code("und")); /* language */
2941 avio_wb16(pb, 0x0); /* ? */
2942 avio_wb16(pb, 0x021C); /* data */
2945 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
2946 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
2947 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2949 update_size(pb, pos2);
2950 return update_size(pb, pos);
2956 static void build_chunks(MOVTrack *trk)
2959 MOVIentry *chunk = &trk->cluster[0];
2960 uint64_t chunkSize = chunk->size;
2961 chunk->chunkNum = 1;
2962 if (trk->chunkCount)
2964 trk->chunkCount = 1;
2965 for (i = 1; i<trk->entry; i++){
2966 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
2967 chunkSize + trk->cluster[i].size < (1<<20)){
2968 chunkSize += trk->cluster[i].size;
2969 chunk->samples_in_chunk += trk->cluster[i].entries;
2971 trk->cluster[i].chunkNum = chunk->chunkNum+1;
2972 chunk=&trk->cluster[i];
2973 chunkSize = chunk->size;
2979 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2983 int64_t pos = avio_tell(pb);
2984 avio_wb32(pb, 0); /* size placeholder*/
2985 ffio_wfourcc(pb, "moov");
2987 for (i = 0; i < mov->nb_streams; i++) {
2988 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2991 mov->tracks[i].time = mov->time;
2992 mov->tracks[i].track_id = i + 1;
2994 if (mov->tracks[i].entry)
2995 build_chunks(&mov->tracks[i]);
2998 if (mov->chapter_track)
2999 for (i = 0; i < s->nb_streams; i++) {
3000 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3001 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3003 for (i = 0; i < mov->nb_streams; i++) {
3004 if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
3005 mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
3006 mov->tracks[i].tref_id =
3007 mov->tracks[mov->tracks[i].src_track].track_id;
3010 for (i = 0; i < mov->nb_streams; i++) {
3011 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3012 int src_trk = mov->tracks[i].src_track;
3013 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3014 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3015 //src_trk may have a different timescale than the tmcd track
3016 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3017 mov->tracks[i].timescale,
3018 mov->tracks[src_trk].timescale);
3022 mov_write_mvhd_tag(pb, mov);
3023 if (mov->mode != MODE_MOV && !mov->iods_skip)
3024 mov_write_iods_tag(pb, mov);
3025 for (i = 0; i < mov->nb_streams; i++) {
3026 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3027 mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3030 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3031 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3033 if (mov->mode == MODE_PSP)
3034 mov_write_uuidusmt_tag(pb, s);
3036 mov_write_udta_tag(pb, mov, s);
3038 return update_size(pb, pos);
3041 static void param_write_int(AVIOContext *pb, const char *name, int value)
3043 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3046 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3048 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3051 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3054 len = FFMIN(sizeof(buf) / 2 - 1, len);
3055 ff_data_to_hex(buf, value, len, 0);
3056 buf[2 * len] = '\0';
3057 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3060 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
3062 int64_t pos = avio_tell(pb);
3064 static const uint8_t uuid[] = {
3065 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3066 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3070 ffio_wfourcc(pb, "uuid");
3071 avio_write(pb, uuid, sizeof(uuid));
3074 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3075 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3076 avio_printf(pb, "<head>\n");
3078 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3080 avio_printf(pb, "</head>\n");
3081 avio_printf(pb, "<body>\n");
3082 avio_printf(pb, "<switch>\n");
3083 for (i = 0; i < mov->nb_streams; i++) {
3084 MOVTrack *track = &mov->tracks[i];
3086 /* track->track_id is initialized in write_moov, and thus isn't known
3088 int track_id = i + 1;
3090 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3092 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
3097 avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
3098 track->enc->bit_rate);
3099 param_write_int(pb, "systemBitrate", track->enc->bit_rate);
3100 param_write_int(pb, "trackID", track_id);
3101 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3102 if (track->enc->codec_id == AV_CODEC_ID_H264) {
3104 int size = track->enc->extradata_size;
3105 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
3107 param_write_hex(pb, "CodecPrivateData",
3108 ptr ? ptr : track->enc->extradata,
3112 param_write_string(pb, "FourCC", "H264");
3113 } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
3114 param_write_string(pb, "FourCC", "WVC1");
3115 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3116 track->enc->extradata_size);
3118 param_write_int(pb, "MaxWidth", track->enc->width);
3119 param_write_int(pb, "MaxHeight", track->enc->height);
3120 param_write_int(pb, "DisplayWidth", track->enc->width);
3121 param_write_int(pb, "DisplayHeight", track->enc->height);
3123 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
3124 param_write_string(pb, "FourCC", "AACL");
3125 } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
3126 param_write_string(pb, "FourCC", "WMAP");
3128 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3129 track->enc->extradata_size);
3130 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3131 track->enc->codec_id));
3132 param_write_int(pb, "Channels", track->enc->channels);
3133 param_write_int(pb, "SamplingRate", track->enc->sample_rate);
3134 param_write_int(pb, "BitsPerSample", 16);
3135 param_write_int(pb, "PacketSize", track->enc->block_align ?
3136 track->enc->block_align : 4);
3138 avio_printf(pb, "</%s>\n", type);
3140 avio_printf(pb, "</switch>\n");
3141 avio_printf(pb, "</body>\n");
3142 avio_printf(pb, "</smil>\n");
3144 return update_size(pb, pos);
3147 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3150 ffio_wfourcc(pb, "mfhd");
3152 avio_wb32(pb, mov->fragments);
3156 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3157 MOVTrack *track, int64_t moof_offset)
3159 int64_t pos = avio_tell(pb);
3160 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3161 MOV_TFHD_BASE_DATA_OFFSET;
3162 if (!track->entry) {
3163 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3165 flags |= MOV_TFHD_DEFAULT_FLAGS;
3167 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3168 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3169 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3170 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3171 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3174 /* Don't set a default sample size, the silverlight player refuses
3175 * to play files with that set. Don't set a default sample duration,
3176 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3177 * file format says it MUST NOT be set. */
3178 if (track->mode == MODE_ISM)
3179 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3180 MOV_TFHD_BASE_DATA_OFFSET);
3182 avio_wb32(pb, 0); /* size placeholder */
3183 ffio_wfourcc(pb, "tfhd");
3184 avio_w8(pb, 0); /* version */
3185 avio_wb24(pb, flags);
3187 avio_wb32(pb, track->track_id); /* track-id */
3188 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3189 avio_wb64(pb, moof_offset);
3190 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3191 track->default_duration = get_cluster_duration(track, 0);
3192 avio_wb32(pb, track->default_duration);
3194 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3195 track->default_size = track->entry ? track->cluster[0].size : 1;
3196 avio_wb32(pb, track->default_size);
3198 track->default_size = -1;
3200 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3201 track->default_sample_flags =
3202 track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
3203 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3204 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3205 avio_wb32(pb, track->default_sample_flags);
3208 return update_size(pb, pos);
3211 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3213 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3214 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3217 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3218 MOVTrack *track, int moof_size)
3220 int64_t pos = avio_tell(pb);
3221 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3224 for (i = 0; i < track->entry; i++) {
3225 if (get_cluster_duration(track, i) != track->default_duration)
3226 flags |= MOV_TRUN_SAMPLE_DURATION;
3227 if (track->cluster[i].size != track->default_size)
3228 flags |= MOV_TRUN_SAMPLE_SIZE;
3229 if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3230 flags |= MOV_TRUN_SAMPLE_FLAGS;
3232 if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
3233 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3234 if (track->flags & MOV_TRACK_CTTS)
3235 flags |= MOV_TRUN_SAMPLE_CTS;
3237 avio_wb32(pb, 0); /* size placeholder */
3238 ffio_wfourcc(pb, "trun");
3239 avio_w8(pb, 0); /* version */
3240 avio_wb24(pb, flags);
3242 avio_wb32(pb, track->entry); /* sample count */
3243 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3244 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3246 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3248 avio_wb32(pb, moof_size + 8 + track->data_offset +
3249 track->cluster[0].pos); /* data offset */
3250 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3251 avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
3253 for (i = 0; i < track->entry; i++) {
3254 if (flags & MOV_TRUN_SAMPLE_DURATION)
3255 avio_wb32(pb, get_cluster_duration(track, i));
3256 if (flags & MOV_TRUN_SAMPLE_SIZE)
3257 avio_wb32(pb, track->cluster[i].size);
3258 if (flags & MOV_TRUN_SAMPLE_FLAGS)
3259 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3260 if (flags & MOV_TRUN_SAMPLE_CTS)
3261 avio_wb32(pb, track->cluster[i].cts);
3264 mov->first_trun = 0;
3265 return update_size(pb, pos);
3268 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3270 int64_t pos = avio_tell(pb);
3271 static const uint8_t uuid[] = {
3272 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3273 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3276 avio_wb32(pb, 0); /* size placeholder */
3277 ffio_wfourcc(pb, "uuid");
3278 avio_write(pb, uuid, sizeof(uuid));
3281 avio_wb64(pb, track->frag_start);
3282 avio_wb64(pb, track->start_dts + track->track_duration -
3283 track->cluster[0].dts);
3285 return update_size(pb, pos);
3288 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3289 MOVTrack *track, int entry)
3291 int n = track->nb_frag_info - 1 - entry, i;
3292 int size = 8 + 16 + 4 + 1 + 16*n;
3293 static const uint8_t uuid[] = {
3294 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3295 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3301 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3302 avio_wb32(pb, size);
3303 ffio_wfourcc(pb, "uuid");
3304 avio_write(pb, uuid, sizeof(uuid));
3308 for (i = 0; i < n; i++) {
3309 int index = entry + 1 + i;
3310 avio_wb64(pb, track->frag_info[index].time);
3311 avio_wb64(pb, track->frag_info[index].duration);
3313 if (n < mov->ism_lookahead) {
3314 int free_size = 16 * (mov->ism_lookahead - n);
3315 avio_wb32(pb, free_size);
3316 ffio_wfourcc(pb, "free");
3317 ffio_fill(pb, 0, free_size - 8);
3323 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3326 int64_t pos = avio_tell(pb);
3328 for (i = 0; i < mov->ism_lookahead; i++) {
3329 /* Update the tfrf tag for the last ism_lookahead fragments,
3330 * nb_frag_info - 1 is the next fragment to be written. */
3331 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3333 avio_seek(pb, pos, SEEK_SET);
3337 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3341 for (i = 0; i < mov->nb_streams; i++) {
3342 MOVTrack *track = &mov->tracks[i];
3343 MOVFragmentInfo *info;
3344 if ((tracks >= 0 && i != tracks) || !track->entry)
3346 track->nb_frag_info++;
3347 if (track->nb_frag_info >= track->frag_info_capacity) {
3348 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3349 if (av_reallocp_array(&track->frag_info,
3351 sizeof(*track->frag_info)))
3352 return AVERROR(ENOMEM);
3353 track->frag_info_capacity = new_capacity;
3355 info = &track->frag_info[track->nb_frag_info - 1];
3356 info->offset = avio_tell(pb);
3358 // Try to recreate the original pts for the first packet
3359 // from the fields we have stored
3360 info->time = track->start_dts + track->frag_start +
3361 track->cluster[0].cts;
3362 // If the pts is less than zero, we will have trimmed
3363 // away parts of the media track using an edit list,
3364 // and the corresponding start presentation time is zero.
3367 info->duration = track->start_dts + track->track_duration -
3368 track->cluster[0].dts;
3369 info->tfrf_offset = 0;
3370 mov_write_tfrf_tags(pb, mov, track);
3375 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3377 int64_t pos = avio_tell(pb);
3379 avio_wb32(pb, 0); /* size */
3380 ffio_wfourcc(pb, "tfdt");
3381 avio_w8(pb, 1); /* version */
3383 avio_wb64(pb, track->frag_start);
3384 return update_size(pb, pos);
3387 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3388 MOVTrack *track, int64_t moof_offset,
3391 int64_t pos = avio_tell(pb);
3392 avio_wb32(pb, 0); /* size placeholder */
3393 ffio_wfourcc(pb, "traf");
3395 mov_write_tfhd_tag(pb, mov, track, moof_offset);
3396 if (mov->mode != MODE_ISM)
3397 mov_write_tfdt_tag(pb, track);
3398 mov_write_trun_tag(pb, mov, track, moof_size);
3399 if (mov->mode == MODE_ISM) {
3400 mov_write_tfxd_tag(pb, track);
3402 if (mov->ism_lookahead) {
3403 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3405 if (track->nb_frag_info > 0) {
3406 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3407 if (!info->tfrf_offset)
3408 info->tfrf_offset = avio_tell(pb);
3410 avio_wb32(pb, 8 + size);
3411 ffio_wfourcc(pb, "free");
3412 for (i = 0; i < size; i++)
3417 return update_size(pb, pos);
3420 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3421 int tracks, int moof_size)
3423 int64_t pos = avio_tell(pb);
3426 avio_wb32(pb, 0); /* size placeholder */
3427 ffio_wfourcc(pb, "moof");
3428 mov->first_trun = 1;
3430 mov_write_mfhd_tag(pb, mov);
3431 for (i = 0; i < mov->nb_streams; i++) {
3432 MOVTrack *track = &mov->tracks[i];
3433 if (tracks >= 0 && i != tracks)
3437 mov_write_traf_tag(pb, mov, track, pos, moof_size);
3440 return update_size(pb, pos);
3443 static int mov_write_sidx_tag(AVIOContext *pb,
3444 MOVTrack *track, int ref_size, int total_sidx_size)
3446 int64_t pos = avio_tell(pb), offset_pos, end_pos;
3447 int64_t presentation_time, duration, offset;
3448 int starts_with_SAP, i, entries;
3452 presentation_time = track->start_dts + track->frag_start +
3453 track->cluster[0].cts;
3454 duration = track->start_dts + track->track_duration -
3455 track->cluster[0].dts;
3456 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
3458 entries = track->nb_frag_info;
3459 presentation_time = track->frag_info[0].time;
3462 // pts<0 should be cut away using edts
3463 if (presentation_time < 0)
3464 presentation_time = 0;
3466 avio_wb32(pb, 0); /* size */
3467 ffio_wfourcc(pb, "sidx");
3468 avio_w8(pb, 1); /* version */
3470 avio_wb32(pb, track->track_id); /* reference_ID */
3471 avio_wb32(pb, track->timescale); /* timescale */
3472 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
3473 offset_pos = avio_tell(pb);
3474 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
3475 avio_wb16(pb, 0); /* reserved */
3477 avio_wb16(pb, entries); /* reference_count */
3478 for (i = 0; i < entries; i++) {
3479 if (!track->entry) {
3480 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
3481 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
3483 duration = track->frag_info[i].duration;
3484 ref_size = track->frag_info[i].size;
3485 starts_with_SAP = 1;
3487 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
3488 avio_wb32(pb, duration); /* subsegment_duration */
3489 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
3492 end_pos = avio_tell(pb);
3493 offset = pos + total_sidx_size - end_pos;
3494 avio_seek(pb, offset_pos, SEEK_SET);
3495 avio_wb64(pb, offset);
3496 avio_seek(pb, end_pos, SEEK_SET);
3497 return update_size(pb, pos);
3500 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
3501 int tracks, int ref_size)
3504 AVIOContext *avio_buf;
3506 for (round = 0; round < 2; round++) {
3507 // First run one round to calculate the total size of all
3509 // This would be much simpler if we'd only write one sidx
3510 // atom, for the first track in the moof.
3512 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3517 for (i = 0; i < mov->nb_streams; i++) {
3518 MOVTrack *track = &mov->tracks[i];
3519 if (tracks >= 0 && i != tracks)
3521 // When writing a sidx for the full file, entry is 0, but
3522 // we want to include all tracks. ref_size is 0 in this case,
3523 // since we read it from frag_info instead.
3524 if (!track->entry && ref_size > 0)
3526 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
3530 total_size = ffio_close_null_buf(avio_buf);
3535 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3538 AVIOContext *avio_buf;
3541 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3543 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
3544 moof_size = ffio_close_null_buf(avio_buf);
3546 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_FASTSTART))
3547 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
3549 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
3552 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
3555 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
3557 int64_t pos = avio_tell(pb);
3560 avio_wb32(pb, 0); /* size placeholder */
3561 ffio_wfourcc(pb, "tfra");
3562 avio_w8(pb, 1); /* version */
3565 avio_wb32(pb, track->track_id);
3566 avio_wb32(pb, 0); /* length of traf/trun/sample num */
3567 avio_wb32(pb, track->nb_frag_info);
3568 for (i = 0; i < track->nb_frag_info; i++) {
3569 avio_wb64(pb, track->frag_info[i].time);
3570 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
3571 avio_w8(pb, 1); /* traf number */
3572 avio_w8(pb, 1); /* trun number */
3573 avio_w8(pb, 1); /* sample number */
3576 return update_size(pb, pos);
3579 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
3581 int64_t pos = avio_tell(pb);
3584 avio_wb32(pb, 0); /* size placeholder */
3585 ffio_wfourcc(pb, "mfra");
3586 /* An empty mfra atom is enough to indicate to the publishing point that
3587 * the stream has ended. */
3588 if (mov->flags & FF_MOV_FLAG_ISML)
3589 return update_size(pb, pos);
3591 for (i = 0; i < mov->nb_streams; i++) {
3592 MOVTrack *track = &mov->tracks[i];
3593 if (track->nb_frag_info)
3594 mov_write_tfra_tag(pb, track);
3598 ffio_wfourcc(pb, "mfro");
3599 avio_wb32(pb, 0); /* version + flags */
3600 avio_wb32(pb, avio_tell(pb) + 4 - pos);
3602 return update_size(pb, pos);
3605 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
3607 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
3608 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
3610 mov->mdat_pos = avio_tell(pb);
3611 avio_wb32(pb, 0); /* size placeholder*/
3612 ffio_wfourcc(pb, "mdat");
3616 /* TODO: This needs to be more general */
3617 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
3619 MOVMuxContext *mov = s->priv_data;
3620 int64_t pos = avio_tell(pb);
3621 int has_h264 = 0, has_video = 0;
3625 for (i = 0; i < s->nb_streams; i++) {
3626 AVStream *st = s->streams[i];
3627 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3629 if (st->codec->codec_id == AV_CODEC_ID_H264)
3633 avio_wb32(pb, 0); /* size */
3634 ffio_wfourcc(pb, "ftyp");
3636 if (mov->major_brand && strlen(mov->major_brand) >= 4)
3637 ffio_wfourcc(pb, mov->major_brand);
3638 else if (mov->mode == MODE_3GP) {
3639 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
3640 minor = has_h264 ? 0x100 : 0x200;
3641 } else if (mov->mode & MODE_3G2) {
3642 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
3643 minor = has_h264 ? 0x20000 : 0x10000;
3644 } else if (mov->mode == MODE_PSP)
3645 ffio_wfourcc(pb, "MSNV");
3646 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
3647 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
3648 else if (mov->mode == MODE_MP4)
3649 ffio_wfourcc(pb, "isom");
3650 else if (mov->mode == MODE_IPOD)
3651 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3652 else if (mov->mode == MODE_ISM)
3653 ffio_wfourcc(pb, "isml");
3654 else if (mov->mode == MODE_F4V)
3655 ffio_wfourcc(pb, "f4v ");
3657 ffio_wfourcc(pb, "qt ");
3659 avio_wb32(pb, minor);
3661 if (mov->mode == MODE_MOV)
3662 ffio_wfourcc(pb, "qt ");
3663 else if (mov->mode == MODE_ISM) {
3664 ffio_wfourcc(pb, "piff");
3665 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
3666 ffio_wfourcc(pb, "isom");
3667 ffio_wfourcc(pb, "iso2");
3669 ffio_wfourcc(pb, "avc1");
3672 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
3673 // brand. This is compatible with users that don't understand tfdt.
3674 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
3675 ffio_wfourcc(pb, "iso6");
3677 if (mov->mode == MODE_3GP)
3678 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3679 else if (mov->mode & MODE_3G2)
3680 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3681 else if (mov->mode == MODE_PSP)
3682 ffio_wfourcc(pb, "MSNV");
3683 else if (mov->mode == MODE_MP4)
3684 ffio_wfourcc(pb, "mp41");
3686 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_FASTSTART)
3687 ffio_wfourcc(pb, "dash");
3689 return update_size(pb, pos);
3692 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3694 AVStream *video_st = s->streams[0];
3695 AVCodecContext *video_codec = s->streams[0]->codec;
3696 AVCodecContext *audio_codec = s->streams[1]->codec;
3697 int audio_rate = audio_codec->sample_rate;
3698 // TODO: should be avg_frame_rate
3699 int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
3700 int audio_kbitrate = audio_codec->bit_rate / 1000;
3701 int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3703 avio_wb32(pb, 0x94); /* size */
3704 ffio_wfourcc(pb, "uuid");
3705 ffio_wfourcc(pb, "PROF");
3707 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3708 avio_wb32(pb, 0xbb88695c);
3709 avio_wb32(pb, 0xfac9c740);
3711 avio_wb32(pb, 0x0); /* ? */
3712 avio_wb32(pb, 0x3); /* 3 sections ? */
3714 avio_wb32(pb, 0x14); /* size */
3715 ffio_wfourcc(pb, "FPRF");
3716 avio_wb32(pb, 0x0); /* ? */
3717 avio_wb32(pb, 0x0); /* ? */
3718 avio_wb32(pb, 0x0); /* ? */
3720 avio_wb32(pb, 0x2c); /* size */
3721 ffio_wfourcc(pb, "APRF"); /* audio */
3723 avio_wb32(pb, 0x2); /* TrackID */
3724 ffio_wfourcc(pb, "mp4a");
3725 avio_wb32(pb, 0x20f);
3727 avio_wb32(pb, audio_kbitrate);
3728 avio_wb32(pb, audio_kbitrate);
3729 avio_wb32(pb, audio_rate);
3730 avio_wb32(pb, audio_codec->channels);
3732 avio_wb32(pb, 0x34); /* size */
3733 ffio_wfourcc(pb, "VPRF"); /* video */
3735 avio_wb32(pb, 0x1); /* TrackID */
3736 if (video_codec->codec_id == AV_CODEC_ID_H264) {
3737 ffio_wfourcc(pb, "avc1");
3738 avio_wb16(pb, 0x014D);
3739 avio_wb16(pb, 0x0015);
3741 ffio_wfourcc(pb, "mp4v");
3742 avio_wb16(pb, 0x0000);
3743 avio_wb16(pb, 0x0103);
3746 avio_wb32(pb, video_kbitrate);
3747 avio_wb32(pb, video_kbitrate);
3748 avio_wb32(pb, frame_rate);
3749 avio_wb32(pb, frame_rate);
3750 avio_wb16(pb, video_codec->width);
3751 avio_wb16(pb, video_codec->height);
3752 avio_wb32(pb, 0x010001); /* ? */
3755 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
3757 MOVMuxContext *mov = s->priv_data;
3760 mov_write_ftyp_tag(pb,s);
3761 if (mov->mode == MODE_PSP) {
3762 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
3763 for (i = 0; i < s->nb_streams; i++) {
3764 AVStream *st = s->streams[i];
3765 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3767 else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3773 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
3774 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3775 return AVERROR(EINVAL);
3777 mov_write_uuidprof_tag(pb, s);
3782 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3785 int i, closed_gop = 0;
3787 for (i = 0; i < pkt->size - 4; i++) {
3788 c = (c << 8) + pkt->data[i];
3789 if (c == 0x1b8) { // gop
3790 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
3791 } else if (c == 0x100) { // pic
3792 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
3793 if (!temp_ref || closed_gop) // I picture is not reordered
3794 *flags = MOV_SYNC_SAMPLE;
3796 *flags = MOV_PARTIAL_SYNC_SAMPLE;
3803 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
3805 const uint8_t *start, *next, *end = pkt->data + pkt->size;
3806 int seq = 0, entry = 0;
3807 int key = pkt->flags & AV_PKT_FLAG_KEY;
3808 start = find_next_marker(pkt->data, end);
3809 for (next = start; next < end; start = next) {
3810 next = find_next_marker(start + 4, end);
3811 switch (AV_RB32(start)) {
3812 case VC1_CODE_SEQHDR:
3815 case VC1_CODE_ENTRYPOINT:
3818 case VC1_CODE_SLICE:
3819 trk->vc1_info.slices = 1;
3823 if (!trk->entry && !fragment) {
3824 /* First packet in first fragment */
3825 trk->vc1_info.first_packet_seq = seq;
3826 trk->vc1_info.first_packet_entry = entry;
3827 } else if ((seq && !trk->vc1_info.packet_seq) ||
3828 (entry && !trk->vc1_info.packet_entry)) {
3830 for (i = 0; i < trk->entry; i++)
3831 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
3832 trk->has_keyframes = 0;
3834 trk->vc1_info.packet_seq = 1;
3836 trk->vc1_info.packet_entry = 1;
3838 /* First fragment */
3839 if ((!seq || trk->vc1_info.first_packet_seq) &&
3840 (!entry || trk->vc1_info.first_packet_entry)) {
3841 /* First packet had the same headers as this one, readd the
3842 * sync sample flag. */
3843 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
3844 trk->has_keyframes = 1;
3848 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
3850 else if (trk->vc1_info.packet_seq)
3852 else if (trk->vc1_info.packet_entry)
3855 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
3856 trk->has_keyframes++;
3860 static int mov_flush_fragment(AVFormatContext *s)
3862 MOVMuxContext *mov = s->priv_data;
3863 int i, first_track = -1;
3864 int64_t mdat_size = 0;
3866 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3869 if (mov->fragments == 0) {
3870 int64_t pos = avio_tell(s->pb);
3872 int buf_size, moov_size;
3874 for (i = 0; i < mov->nb_streams; i++)
3875 if (!mov->tracks[i].entry)
3877 /* Don't write the initial moov unless all tracks have data */
3878 if (i < mov->nb_streams)
3881 moov_size = get_moov_size(s);
3882 for (i = 0; i < mov->nb_streams; i++)
3883 mov->tracks[i].data_offset = pos + moov_size + 8;
3885 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
3886 mov_write_identification(s->pb, s);
3887 mov_write_moov_tag(s->pb, mov, s);
3889 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
3890 if (mov->flags & FF_MOV_FLAG_FASTSTART)
3891 mov->reserved_moov_pos = avio_tell(s->pb);
3897 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
3898 mov->mdat_buf = NULL;
3899 avio_wb32(s->pb, buf_size + 8);
3900 ffio_wfourcc(s->pb, "mdat");
3901 avio_write(s->pb, buf, buf_size);
3906 for (i = 0; i < mov->nb_streams; i++) {
3907 if (mov->tracks[i].entry)
3908 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
3909 mov->tracks[i].track_duration -
3910 mov->tracks[i].cluster[0].dts;
3911 mov->tracks[i].entry = 0;
3917 for (i = 0; i < mov->nb_streams; i++) {
3918 MOVTrack *track = &mov->tracks[i];
3919 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
3920 track->data_offset = 0;
3922 track->data_offset = mdat_size;
3923 if (!track->mdat_buf)
3925 mdat_size += avio_tell(track->mdat_buf);
3926 if (first_track < 0)
3933 for (i = 0; i < mov->nb_streams; i++) {
3934 MOVTrack *track = &mov->tracks[i];
3935 int buf_size, write_moof = 1, moof_tracks = -1;
3937 int64_t duration = 0;
3940 duration = track->start_dts + track->track_duration -
3941 track->cluster[0].dts;
3942 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
3943 if (!track->mdat_buf)
3945 mdat_size = avio_tell(track->mdat_buf);
3948 write_moof = i == first_track;
3954 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
3957 avio_wb32(s->pb, mdat_size + 8);
3958 ffio_wfourcc(s->pb, "mdat");
3962 track->frag_start += duration;
3964 if (!track->mdat_buf)
3966 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
3967 track->mdat_buf = NULL;
3969 avio_write(s->pb, buf, buf_size);
3979 static int mov_auto_flush_fragment(AVFormatContext *s)
3981 MOVMuxContext *mov = s->priv_data;
3982 int ret = mov_flush_fragment(s);
3985 // If using delay_moov, the first flush only wrote the moov,
3986 // not the actual moof+mdat pair, thus flush once again.
3987 if (mov->fragments == 1 && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
3988 ret = mov_flush_fragment(s);
3992 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3994 MOVMuxContext *mov = s->priv_data;
3995 AVIOContext *pb = s->pb;
3996 MOVTrack *trk = &mov->tracks[pkt->stream_index];
3997 AVCodecContext *enc = trk->enc;
3998 unsigned int samples_in_chunk = 0;
3999 int size = pkt->size, ret = 0;
4000 uint8_t *reformatted_data = NULL;
4003 int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
4004 if (duration < 0 || duration > INT_MAX) {
4005 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4009 pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
4010 pkt->pts = AV_NOPTS_VALUE;
4012 if (pkt->duration < 0) {
4013 av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
4014 return AVERROR(EINVAL);
4017 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4019 if (mov->fragments > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4020 if (!trk->mdat_buf) {
4021 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4026 if (!mov->mdat_buf) {
4027 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4034 if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
4035 /* We must find out how many AMR blocks there are in one packet */
4036 static uint16_t packed_size[16] =
4037 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4040 while (len < size && samples_in_chunk < 100) {
4041 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4044 if (samples_in_chunk > 1) {
4045 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4048 } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
4049 enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4050 samples_in_chunk = enc->frame_size;
4051 } else if (trk->sample_size)
4052 samples_in_chunk = size / trk->sample_size;
4054 samples_in_chunk = 1;
4056 /* copy extradata if it exists */
4057 if (trk->vos_len == 0 && enc->extradata_size > 0 && !TAG_IS_AVCI(trk->tag)) {
4058 trk->vos_len = enc->extradata_size;
4059 trk->vos_data = av_malloc(trk->vos_len);
4060 memcpy(trk->vos_data, enc->extradata, trk->vos_len);
4063 if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4064 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4065 if (!s->streams[pkt->stream_index]->nb_frames) {
4066 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4067 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4068 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4071 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4073 if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4074 /* from x264 or from bytestream h264 */
4075 /* nal reformating needed */
4076 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4077 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4079 avio_write(pb, reformatted_data, size);
4081 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4083 } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4084 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4085 /* extradata is Annex B, assume the bitstream is too and convert it */
4086 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4087 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4088 avio_write(pb, reformatted_data, size);
4090 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4092 } else if (CONFIG_AC3_PARSER && enc->codec_id == AV_CODEC_ID_EAC3) {
4093 size = handle_eac3(mov, pkt, trk);
4098 avio_write(pb, pkt->data, size);
4100 avio_write(pb, pkt->data, size);
4103 if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
4104 enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4105 /* copy frame to create needed atoms */
4106 trk->vos_len = size;
4107 trk->vos_data = av_malloc(size);
4108 if (!trk->vos_data) {
4109 ret = AVERROR(ENOMEM);
4112 memcpy(trk->vos_data, pkt->data, size);
4115 if (trk->entry >= trk->cluster_capacity) {
4116 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4117 if (av_reallocp_array(&trk->cluster, new_capacity,
4118 sizeof(*trk->cluster))) {
4119 ret = AVERROR(ENOMEM);
4122 trk->cluster_capacity = new_capacity;
4125 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
4126 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4127 trk->cluster[trk->entry].chunkNum = 0;
4128 trk->cluster[trk->entry].size = size;
4129 trk->cluster[trk->entry].entries = samples_in_chunk;
4130 trk->cluster[trk->entry].dts = pkt->dts;
4131 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4132 if (!trk->frag_discont) {
4133 /* First packet of a new fragment. We already wrote the duration
4134 * of the last packet of the previous fragment based on track_duration,
4135 * which might not exactly match our dts. Therefore adjust the dts
4136 * of this packet to be what the previous packets duration implies. */
4137 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4138 /* We also may have written the pts and the corresponding duration
4139 * in sidx tags; make sure the sidx pts and duration match up with
4140 * the next fragment. This means the cts of the first sample must
4141 * be the same in all fragments. */
4142 pkt->pts = pkt->dts + trk->start_cts;
4144 /* New fragment, but discontinuous from previous fragments.
4145 * Pretend the duration sum of the earlier fragments is
4146 * pkt->dts - trk->start_dts. */
4147 trk->frag_start = pkt->dts - trk->start_dts;
4148 trk->frag_discont = 0;
4152 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4153 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4154 /* Not using edit lists and shifting the first track to start from zero.
4155 * If the other streams start from a later timestamp, we won't be able
4156 * to signal the difference in starting time without an edit list.
4157 * Thus move the timestamp for this first sample to 0, increasing
4158 * its duration instead. */
4159 trk->cluster[trk->entry].dts = trk->start_dts = 0;
4161 if (trk->start_dts == AV_NOPTS_VALUE) {
4162 trk->start_dts = pkt->dts;
4163 if (trk->frag_discont) {
4164 /* Pretend the whole stream started at dts=0, with earlier framgents
4165 * already written, with a duration summing up to pkt->dts. */
4166 trk->frag_start = pkt->dts;
4168 trk->frag_discont = 0;
4169 } else if (mov->fragments >= 1)
4170 av_log(s, AV_LOG_WARNING,
4171 "Track %d starts with a nonzero dts %"PRId64", while the moov "
4172 "already has been written. Set the delay_moov flag to handle "
4174 pkt->stream_index, pkt->dts);
4176 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4177 trk->last_sample_is_subtitle_end = 0;
4179 if (pkt->pts == AV_NOPTS_VALUE) {
4180 av_log(s, AV_LOG_WARNING, "pts has no value\n");
4181 pkt->pts = pkt->dts;
4183 if (pkt->dts != pkt->pts)
4184 trk->flags |= MOV_TRACK_CTTS;
4185 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
4186 trk->cluster[trk->entry].flags = 0;
4187 if (trk->start_cts == AV_NOPTS_VALUE)
4188 trk->start_cts = pkt->pts - pkt->dts;
4190 if (enc->codec_id == AV_CODEC_ID_VC1) {
4191 mov_parse_vc1_frame(pkt, trk, mov->fragments);
4192 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4193 if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4194 trk->entry > 0) { // force sync sample for the first key frame
4195 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4196 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4197 trk->flags |= MOV_TRACK_STPS;
4199 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
4201 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
4202 trk->has_keyframes++;
4205 trk->sample_count += samples_in_chunk;
4206 mov->mdat_size += size;
4208 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
4209 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
4210 reformatted_data, size);
4215 av_free(reformatted_data);
4219 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
4221 MOVMuxContext *mov = s->priv_data;
4222 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4223 AVCodecContext *enc = trk->enc;
4224 int64_t frag_duration = 0;
4225 int size = pkt->size;
4228 return 0; /* Discard 0 sized packets */
4230 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
4232 for (i = 0; i < s->nb_streams; i++)
4233 mov->tracks[i].frag_discont = 1;
4234 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
4237 if (trk->entry && pkt->stream_index < s->nb_streams)
4238 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
4239 s->streams[pkt->stream_index]->time_base,
4241 if ((mov->max_fragment_duration &&
4242 frag_duration >= mov->max_fragment_duration) ||
4243 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
4244 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
4245 enc->codec_type == AVMEDIA_TYPE_VIDEO &&
4246 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
4247 if (frag_duration >= mov->min_fragment_duration)
4248 mov_auto_flush_fragment(s);
4251 return ff_mov_write_packet(s, pkt);
4254 static int mov_write_subtitle_end_packet(AVFormatContext *s,
4258 uint8_t data[2] = {0};
4261 av_init_packet(&end);
4262 end.size = sizeof(data);
4267 end.stream_index = stream_index;
4269 ret = mov_write_single_packet(s, &end);
4270 av_free_packet(&end);
4275 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4278 mov_flush_fragment(s);
4282 MOVMuxContext *mov = s->priv_data;
4284 if (!pkt->size) return 0; /* Discard 0 sized packets */
4287 * Subtitles require special handling.
4289 * 1) For full complaince, every track must have a sample at
4290 * dts == 0, which is rarely true for subtitles. So, as soon
4291 * as we see any packet with dts > 0, write an empty subtitle
4292 * at dts == 0 for any subtitle track with no samples in it.
4294 * 2) For each subtitle track, check if the current packet's
4295 * dts is past the duration of the last subtitle sample. If
4296 * so, we now need to write an end sample for that subtitle.
4298 * This must be done conditionally to allow for subtitles that
4299 * immediately replace each other, in which case an end sample
4300 * is not needed, and is, in fact, actively harmful.
4302 * 3) See mov_write_trailer for how the final end sample is
4305 for (i = 0; i < mov->nb_streams; i++) {
4306 MOVTrack *trk = &mov->tracks[i];
4309 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4310 trk->track_duration < pkt->dts &&
4311 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
4312 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
4313 if (ret < 0) return ret;
4314 trk->last_sample_is_subtitle_end = 1;
4318 return mov_write_single_packet(s, pkt);
4322 // QuickTime chapters involve an additional text track with the chapter names
4323 // as samples, and a tref pointing from the other tracks to the chapter one.
4324 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
4328 MOVMuxContext *mov = s->priv_data;
4329 MOVTrack *track = &mov->tracks[tracknum];
4330 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
4333 track->mode = mov->mode;
4334 track->tag = MKTAG('t','e','x','t');
4335 track->timescale = MOV_TIMESCALE;
4336 track->enc = avcodec_alloc_context3(NULL);
4338 return AVERROR(ENOMEM);
4339 track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4341 // These properties are required to make QT recognize the chapter track
4342 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
4343 if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
4344 return AVERROR(ENOMEM);
4345 memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
4347 if (avio_open_dyn_buf(&pb) >= 0) {
4351 /* Stub header (usually for Quicktime chapter track) */
4353 avio_wb32(pb, 0x01); // displayFlags
4354 avio_w8(pb, 0x00); // horizontal justification
4355 avio_w8(pb, 0x00); // vertical justification
4356 avio_w8(pb, 0x00); // bgColourRed
4357 avio_w8(pb, 0x00); // bgColourGreen
4358 avio_w8(pb, 0x00); // bgColourBlue
4359 avio_w8(pb, 0x00); // bgColourAlpha
4361 avio_wb16(pb, 0x00); // defTextBoxTop
4362 avio_wb16(pb, 0x00); // defTextBoxLeft
4363 avio_wb16(pb, 0x00); // defTextBoxBottom
4364 avio_wb16(pb, 0x00); // defTextBoxRight
4366 avio_wb16(pb, 0x00); // startChar
4367 avio_wb16(pb, 0x00); // endChar
4368 avio_wb16(pb, 0x01); // fontID
4369 avio_w8(pb, 0x00); // fontStyleFlags
4370 avio_w8(pb, 0x00); // fontSize
4371 avio_w8(pb, 0x00); // fgColourRed
4372 avio_w8(pb, 0x00); // fgColourGreen
4373 avio_w8(pb, 0x00); // fgColourBlue
4374 avio_w8(pb, 0x00); // fgColourAlpha
4376 avio_wb32(pb, 0x0D); // box size
4377 ffio_wfourcc(pb, "ftab"); // box atom name
4378 avio_wb16(pb, 0x01); // entry count
4380 avio_wb16(pb, 0x01); // font ID
4381 avio_w8(pb, 0x00); // font name length
4383 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
4384 track->enc->extradata = buf;
4385 track->enc->extradata_size = size;
4392 for (i = 0; i < s->nb_chapters; i++) {
4393 AVChapter *c = s->chapters[i];
4394 AVDictionaryEntry *t;
4396 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
4397 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
4398 pkt.duration = end - pkt.dts;
4400 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
4401 const char encd[12] = {
4402 0x00, 0x00, 0x00, 0x0C,
4404 0x00, 0x00, 0x01, 0x00 };
4405 len = strlen(t->value);
4406 pkt.size = len + 2 + 12;
4407 pkt.data = av_malloc(pkt.size);
4409 return AVERROR(ENOMEM);
4410 AV_WB16(pkt.data, len);
4411 memcpy(pkt.data + 2, t->value, len);
4412 memcpy(pkt.data + len + 2, encd, sizeof(encd));
4413 ff_mov_write_packet(s, &pkt);
4414 av_freep(&pkt.data);
4421 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
4424 MOVMuxContext *mov = s->priv_data;
4425 MOVTrack *track = &mov->tracks[index];
4426 AVStream *src_st = s->streams[src_index];
4428 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
4429 AVRational rate = find_fps(s, src_st);
4431 /* compute the frame number */
4432 ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
4436 /* tmcd track based on video stream */
4437 track->mode = mov->mode;
4438 track->tag = MKTAG('t','m','c','d');
4439 track->src_track = src_index;
4440 track->timescale = mov->tracks[src_index].timescale;
4441 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
4442 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
4444 /* set st to src_st for metadata access*/
4447 /* encode context: tmcd data stream */
4448 track->enc = avcodec_alloc_context3(NULL);
4449 track->enc->codec_type = AVMEDIA_TYPE_DATA;
4450 track->enc->codec_tag = track->tag;
4451 track->enc->time_base = av_inv_q(rate);
4453 /* the tmcd track just contains one packet with the frame number */
4454 pkt.data = av_malloc(pkt.size);
4455 AV_WB32(pkt.data, tc.start);
4456 ret = ff_mov_write_packet(s, &pkt);
4462 * st->disposition controls the "enabled" flag in the tkhd tag.
4463 * QuickTime will not play a track if it is not enabled. So make sure
4464 * that one track of each type (audio, video, subtitle) is enabled.
4466 * Subtitles are special. For audio and video, setting "enabled" also
4467 * makes the track "default" (i.e. it is rendered when played). For
4468 * subtitles, an "enabled" subtitle is not rendered by default, but
4469 * if no subtitle is enabled, the subtitle menu in QuickTime will be
4472 static void enable_tracks(AVFormatContext *s)
4474 MOVMuxContext *mov = s->priv_data;
4476 int enabled[AVMEDIA_TYPE_NB];
4477 int first[AVMEDIA_TYPE_NB];
4479 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4484 for (i = 0; i < s->nb_streams; i++) {
4485 AVStream *st = s->streams[i];
4487 if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
4488 st->codec->codec_type >= AVMEDIA_TYPE_NB)
4491 if (first[st->codec->codec_type] < 0)
4492 first[st->codec->codec_type] = i;
4493 if (st->disposition & AV_DISPOSITION_DEFAULT) {
4494 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
4495 enabled[st->codec->codec_type]++;
4499 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4501 case AVMEDIA_TYPE_VIDEO:
4502 case AVMEDIA_TYPE_AUDIO:
4503 case AVMEDIA_TYPE_SUBTITLE:
4505 mov->per_stream_grouping = 1;
4506 if (!enabled[i] && first[i] >= 0)
4507 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
4513 static void mov_free(AVFormatContext *s)
4515 MOVMuxContext *mov = s->priv_data;
4518 if (mov->chapter_track) {
4519 if (mov->tracks[mov->chapter_track].enc)
4520 av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
4521 av_freep(&mov->tracks[mov->chapter_track].enc);
4524 for (i = 0; i < mov->nb_streams; i++) {
4525 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
4526 ff_mov_close_hinting(&mov->tracks[i]);
4527 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
4528 av_freep(&mov->tracks[i].enc);
4529 av_freep(&mov->tracks[i].cluster);
4530 av_freep(&mov->tracks[i].frag_info);
4532 if (mov->tracks[i].vos_len)
4533 av_freep(&mov->tracks[i].vos_data);
4536 av_freep(&mov->tracks);
4539 static uint32_t rgb_to_yuv(uint32_t rgb)
4544 r = (rgb >> 16) & 0xFF;
4545 g = (rgb >> 8) & 0xFF;
4548 y = av_clip_uint8( 16. + 0.257 * r + 0.504 * g + 0.098 * b);
4549 cb = av_clip_uint8(128. - 0.148 * r - 0.291 * g + 0.439 * b);
4550 cr = av_clip_uint8(128. + 0.439 * r - 0.368 * g - 0.071 * b);
4552 return (y << 16) | (cr << 8) | cb;
4555 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
4558 int i, width = 720, height = 480;
4559 int have_palette = 0, have_size = 0;
4560 uint32_t palette[16];
4561 char *cur = st->codec->extradata;
4563 while (cur && *cur) {
4564 if (strncmp("palette:", cur, 8) == 0) {
4566 count = sscanf(cur + 8,
4567 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4568 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4569 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4570 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
4571 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
4572 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
4573 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
4574 &palette[12], &palette[13], &palette[14], &palette[15]);
4576 for (i = 0; i < count; i++) {
4577 palette[i] = rgb_to_yuv(palette[i]);
4580 } else if (!strncmp("size:", cur, 5)) {
4581 sscanf(cur + 5, "%dx%d", &width, &height);
4584 if (have_palette && have_size)
4586 cur += strcspn(cur, "\n\r");
4587 cur += strspn(cur, "\n\r");
4590 track->vos_data = av_malloc(16*4);
4591 if (!track->vos_data)
4592 return AVERROR(ENOMEM);
4593 for (i = 0; i < 16; i++) {
4594 AV_WB32(track->vos_data + i * 4, palette[i]);
4596 track->vos_len = 16 * 4;
4598 st->codec->width = width;
4599 st->codec->height = track->height = height;
4604 static int mov_write_header(AVFormatContext *s)
4606 AVIOContext *pb = s->pb;
4607 MOVMuxContext *mov = s->priv_data;
4608 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
4609 int i, ret, hint_track = 0, tmcd_track = 0;
4613 /* Default mode == MP4 */
4614 mov->mode = MODE_MP4;
4617 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
4618 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
4619 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
4620 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
4621 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
4622 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
4623 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
4626 if (s->flags & AVFMT_FLAG_BITEXACT)
4629 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4630 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
4632 /* Set the FRAGMENT flag if any of the fragmentation methods are
4634 if (mov->max_fragment_duration || mov->max_fragment_size ||
4635 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
4636 FF_MOV_FLAG_FRAG_KEYFRAME |
4637 FF_MOV_FLAG_FRAG_CUSTOM))
4638 mov->flags |= FF_MOV_FLAG_FRAGMENT;
4640 /* Set other implicit flags immediately */
4641 if (mov->mode == MODE_ISM)
4642 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
4643 FF_MOV_FLAG_FRAGMENT;
4644 if (mov->flags & FF_MOV_FLAG_DASH)
4645 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
4646 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
4648 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4649 mov->reserved_moov_size = -1;
4652 if (mov->use_editlist < 0) {
4653 mov->use_editlist = 1;
4654 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
4655 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
4656 // If we can avoid needing an edit list by shifting the
4657 // tracks, prefer that over (trying to) write edit lists
4658 // in fragmented output.
4659 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
4660 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
4661 mov->use_editlist = 0;
4664 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
4665 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
4666 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
4668 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
4669 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
4671 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
4672 * is enabled, we don't support non-seekable output at all. */
4673 if (!s->pb->seekable &&
4674 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
4675 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
4676 return AVERROR(EINVAL);
4679 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
4680 if ((ret = mov_write_identification(pb, s)) < 0)
4684 mov->nb_streams = s->nb_streams;
4685 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
4686 mov->chapter_track = mov->nb_streams++;
4688 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4689 /* Add hint tracks for each audio and video stream */
4690 hint_track = mov->nb_streams;
4691 for (i = 0; i < s->nb_streams; i++) {
4692 AVStream *st = s->streams[i];
4693 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4694 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4700 if (mov->mode == MODE_MOV) {
4701 tmcd_track = mov->nb_streams;
4703 /* +1 tmcd track for each video stream with a timecode */
4704 for (i = 0; i < s->nb_streams; i++) {
4705 AVStream *st = s->streams[i];
4706 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4707 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
4708 mov->nb_meta_tmcd++;
4711 /* check if there is already a tmcd track to remux */
4712 if (mov->nb_meta_tmcd) {
4713 for (i = 0; i < s->nb_streams; i++) {
4714 AVStream *st = s->streams[i];
4715 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
4716 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
4717 "so timecode metadata are now ignored\n");
4718 mov->nb_meta_tmcd = 0;
4723 mov->nb_streams += mov->nb_meta_tmcd;
4726 // Reserve an extra stream for chapters for the case where chapters
4727 // are written in the trailer
4728 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
4730 return AVERROR(ENOMEM);
4732 for (i = 0; i < s->nb_streams; i++) {
4733 AVStream *st= s->streams[i];
4734 MOVTrack *track= &mov->tracks[i];
4735 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4738 track->enc = st->codec;
4739 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
4740 if (track->language < 0)
4741 track->language = 0;
4742 track->mode = mov->mode;
4743 track->tag = mov_find_codec_tag(s, track);
4745 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
4746 "codec not currently supported in container\n",
4747 avcodec_get_name(st->codec->codec_id), i);
4748 ret = AVERROR(EINVAL);
4751 /* If hinting of this track is enabled by a later hint track,
4752 * this is updated. */
4753 track->hint_track = -1;
4754 track->start_dts = AV_NOPTS_VALUE;
4755 track->start_cts = AV_NOPTS_VALUE;
4756 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4757 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
4758 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
4759 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
4760 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
4761 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
4762 ret = AVERROR(EINVAL);
4765 track->height = track->tag >> 24 == 'n' ? 486 : 576;
4767 if (mov->video_track_timescale) {
4768 track->timescale = mov->video_track_timescale;
4770 track->timescale = st->time_base.den;
4771 while(track->timescale < 10000)
4772 track->timescale *= 2;
4774 if (st->codec->width > 65535 || st->codec->height > 65535) {
4775 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
4776 ret = AVERROR(EINVAL);
4779 if (track->mode == MODE_MOV && track->timescale > 100000)
4780 av_log(s, AV_LOG_WARNING,
4781 "WARNING codec timebase is very high. If duration is too long,\n"
4782 "file may not be playable by quicktime. Specify a shorter timebase\n"
4783 "or choose different container.\n");
4784 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4785 track->timescale = st->codec->sample_rate;
4786 if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
4787 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
4788 track->audio_vbr = 1;
4789 }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
4790 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
4791 st->codec->codec_id == AV_CODEC_ID_ILBC){
4792 if (!st->codec->block_align) {
4793 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
4794 ret = AVERROR(EINVAL);
4797 track->sample_size = st->codec->block_align;
4798 }else if (st->codec->frame_size > 1){ /* assume compressed audio */
4799 track->audio_vbr = 1;
4801 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
4803 if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
4804 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
4805 track->audio_vbr = 1;
4807 if (track->mode != MODE_MOV &&
4808 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
4809 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
4810 i, track->enc->sample_rate);
4811 ret = AVERROR(EINVAL);
4814 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4815 track->timescale = st->time_base.den;
4816 } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
4817 track->timescale = st->time_base.den;
4819 track->timescale = MOV_TIMESCALE;
4822 track->height = st->codec->height;
4823 /* The ism specific timescale isn't mandatory, but is assumed by
4824 * some tools, such as mp4split. */
4825 if (mov->mode == MODE_ISM)
4826 track->timescale = 10000000;
4828 avpriv_set_pts_info(st, 64, 1, track->timescale);
4830 /* copy extradata if it exists */
4831 if (st->codec->extradata_size) {
4832 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
4833 mov_create_dvd_sub_decoder_specific_info(track, st);
4834 else if (!TAG_IS_AVCI(track->tag)){
4835 track->vos_len = st->codec->extradata_size;
4836 track->vos_data = av_malloc(track->vos_len);
4837 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
4842 for (i = 0; i < s->nb_streams; i++) {
4844 AVStream *st= s->streams[i];
4845 MOVTrack *track= &mov->tracks[i];
4847 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4848 track->enc->channel_layout != AV_CH_LAYOUT_MONO)
4851 for (j = 0; j < s->nb_streams; j++) {
4852 AVStream *stj= s->streams[j];
4853 MOVTrack *trackj= &mov->tracks[j];
4857 if (stj->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4858 trackj->enc->channel_layout != AV_CH_LAYOUT_MONO ||
4859 trackj->language != track->language ||
4860 trackj->tag != track->tag
4863 track->multichannel_as_mono++;
4870 if (mov->reserved_moov_size){
4871 mov->reserved_moov_pos= avio_tell(pb);
4872 if (mov->reserved_moov_size > 0)
4873 avio_skip(pb, mov->reserved_moov_size);
4876 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4877 /* If no fragmentation options have been set, set a default. */
4878 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
4879 FF_MOV_FLAG_FRAG_CUSTOM)) &&
4880 !mov->max_fragment_duration && !mov->max_fragment_size)
4881 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
4883 if (mov->flags & FF_MOV_FLAG_FASTSTART)
4884 mov->reserved_moov_pos = avio_tell(pb);
4885 mov_write_mdat_tag(pb, mov);
4888 if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
4889 mov->time = ff_iso8601_to_unix_time(t->value);
4891 mov->time += 0x7C25B080; // 1970 based -> 1904 based
4893 if (mov->chapter_track)
4894 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4897 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4898 /* Initialize the hint tracks for each audio and video stream */
4899 for (i = 0; i < s->nb_streams; i++) {
4900 AVStream *st = s->streams[i];
4901 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4902 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4903 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
4910 if (mov->nb_meta_tmcd) {
4911 /* Initialize the tmcd tracks */
4912 for (i = 0; i < s->nb_streams; i++) {
4913 AVStream *st = s->streams[i];
4916 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4918 t = av_dict_get(st->metadata, "timecode", NULL, 0);
4921 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
4930 if (mov->flags & FF_MOV_FLAG_ISML)
4931 mov_write_isml_manifest(pb, mov);
4933 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
4934 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
4935 mov_write_moov_tag(pb, mov, s);
4937 if (mov->flags & FF_MOV_FLAG_FASTSTART)
4938 mov->reserved_moov_pos = avio_tell(pb);
4947 static int get_moov_size(AVFormatContext *s)
4950 AVIOContext *moov_buf;
4951 MOVMuxContext *mov = s->priv_data;
4953 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
4955 mov_write_moov_tag(moov_buf, mov, s);
4956 return ffio_close_null_buf(moov_buf);
4959 static int get_sidx_size(AVFormatContext *s)
4963 MOVMuxContext *mov = s->priv_data;
4965 if ((ret = ffio_open_null_buf(&buf)) < 0)
4967 mov_write_sidx_tags(buf, mov, -1, 0);
4968 return ffio_close_null_buf(buf);
4972 * This function gets the moov size if moved to the top of the file: the chunk
4973 * offset table can switch between stco (32-bit entries) to co64 (64-bit
4974 * entries) when the moov is moved to the beginning, so the size of the moov
4975 * would change. It also updates the chunk offset tables.
4977 static int compute_moov_size(AVFormatContext *s)
4979 int i, moov_size, moov_size2;
4980 MOVMuxContext *mov = s->priv_data;
4982 moov_size = get_moov_size(s);
4986 for (i = 0; i < mov->nb_streams; i++)
4987 mov->tracks[i].data_offset += moov_size;
4989 moov_size2 = get_moov_size(s);
4993 /* if the size changed, we just switched from stco to co64 and need to
4994 * update the offsets */
4995 if (moov_size2 != moov_size)
4996 for (i = 0; i < mov->nb_streams; i++)
4997 mov->tracks[i].data_offset += moov_size2 - moov_size;
5002 static int compute_sidx_size(AVFormatContext *s)
5005 MOVMuxContext *mov = s->priv_data;
5007 sidx_size = get_sidx_size(s);
5011 for (i = 0; i < mov->nb_streams; i++)
5012 mov->tracks[i].data_offset += sidx_size;
5017 static int shift_data(AVFormatContext *s)
5019 int ret = 0, moov_size;
5020 MOVMuxContext *mov = s->priv_data;
5021 int64_t pos, pos_end = avio_tell(s->pb);
5022 uint8_t *buf, *read_buf[2];
5023 int read_buf_id = 0;
5025 AVIOContext *read_pb;
5027 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
5028 moov_size = compute_sidx_size(s);
5030 moov_size = compute_moov_size(s);
5034 buf = av_malloc(moov_size * 2);
5036 return AVERROR(ENOMEM);
5038 read_buf[1] = buf + moov_size;
5040 /* Shift the data: the AVIO context of the output can only be used for
5041 * writing, so we re-open the same output, but for reading. It also avoids
5042 * a read/seek/write/seek back and forth. */
5044 ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
5046 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
5047 "the second pass (faststart)\n", s->filename);
5051 /* mark the end of the shift to up to the last data we wrote, and get ready
5053 pos_end = avio_tell(s->pb);
5054 avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
5056 /* start reading at where the new moov will be placed */
5057 avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
5058 pos = avio_tell(read_pb);
5060 #define READ_BLOCK do { \
5061 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
5065 /* shift data by chunk of at most moov_size */
5070 n = read_size[read_buf_id];
5073 avio_write(s->pb, read_buf[read_buf_id], n);
5075 } while (pos < pos_end);
5076 avio_close(read_pb);
5083 static int mov_write_trailer(AVFormatContext *s)
5085 MOVMuxContext *mov = s->priv_data;
5086 AVIOContext *pb = s->pb;
5092 * Before actually writing the trailer, make sure that there are no
5093 * dangling subtitles, that need a terminating sample.
5095 for (i = 0; i < mov->nb_streams; i++) {
5096 MOVTrack *trk = &mov->tracks[i];
5097 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
5098 !trk->last_sample_is_subtitle_end) {
5099 mov_write_subtitle_end_packet(s, i, trk->track_duration);
5100 trk->last_sample_is_subtitle_end = 1;
5104 // If there were no chapters when the header was written, but there
5105 // are chapters now, write them in the trailer. This only works
5106 // when we are not doing fragments.
5107 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5108 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
5109 mov->chapter_track = mov->nb_streams++;
5110 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5115 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5116 moov_pos = avio_tell(pb);
5118 /* Write size of mdat tag */
5119 if (mov->mdat_size + 8 <= UINT32_MAX) {
5120 avio_seek(pb, mov->mdat_pos, SEEK_SET);
5121 avio_wb32(pb, mov->mdat_size + 8);
5123 /* overwrite 'wide' placeholder atom */
5124 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
5125 /* special value: real atom size will be 64 bit value after
5128 ffio_wfourcc(pb, "mdat");
5129 avio_wb64(pb, mov->mdat_size + 16);
5131 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
5133 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5134 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
5135 res = shift_data(s);
5137 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5138 mov_write_moov_tag(pb, mov, s);
5140 } else if (mov->reserved_moov_size > 0) {
5142 mov_write_moov_tag(pb, mov, s);
5143 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
5145 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
5148 avio_wb32(pb, size);
5149 ffio_wfourcc(pb, "free");
5150 ffio_fill(pb, 0, size - 8);
5151 avio_seek(pb, moov_pos, SEEK_SET);
5153 mov_write_moov_tag(pb, mov, s);
5156 mov_auto_flush_fragment(s);
5157 for (i = 0; i < mov->nb_streams; i++)
5158 mov->tracks[i].data_offset = 0;
5159 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5160 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
5161 res = shift_data(s);
5163 int64_t end = avio_tell(pb);
5164 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5165 mov_write_sidx_tags(pb, mov, -1, 0);
5166 avio_seek(pb, end, SEEK_SET);
5167 mov_write_mfra_tag(pb, mov);
5170 mov_write_mfra_tag(pb, mov);
5180 #if CONFIG_MOV_MUXER
5182 AVOutputFormat ff_mov_muxer = {
5184 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5185 .extensions = "mov",
5186 .priv_data_size = sizeof(MOVMuxContext),
5187 .audio_codec = AV_CODEC_ID_AAC,
5188 .video_codec = CONFIG_LIBX264_ENCODER ?
5189 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5190 .write_header = mov_write_header,
5191 .write_packet = mov_write_packet,
5192 .write_trailer = mov_write_trailer,
5193 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5194 .codec_tag = (const AVCodecTag* const []){
5195 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
5197 .priv_class = &mov_muxer_class,
5200 #if CONFIG_TGP_MUXER
5202 AVOutputFormat ff_tgp_muxer = {
5204 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
5205 .extensions = "3gp",
5206 .priv_data_size = sizeof(MOVMuxContext),
5207 .audio_codec = AV_CODEC_ID_AMR_NB,
5208 .video_codec = AV_CODEC_ID_H263,
5209 .write_header = mov_write_header,
5210 .write_packet = mov_write_packet,
5211 .write_trailer = mov_write_trailer,
5212 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5213 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5214 .priv_class = &tgp_muxer_class,
5217 #if CONFIG_MP4_MUXER
5219 AVOutputFormat ff_mp4_muxer = {
5221 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
5222 .mime_type = "application/mp4",
5223 .extensions = "mp4",
5224 .priv_data_size = sizeof(MOVMuxContext),
5225 .audio_codec = AV_CODEC_ID_AAC,
5226 .video_codec = CONFIG_LIBX264_ENCODER ?
5227 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5228 .write_header = mov_write_header,
5229 .write_packet = mov_write_packet,
5230 .write_trailer = mov_write_trailer,
5231 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5232 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5233 .priv_class = &mp4_muxer_class,
5236 #if CONFIG_PSP_MUXER
5238 AVOutputFormat ff_psp_muxer = {
5240 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
5241 .extensions = "mp4,psp",
5242 .priv_data_size = sizeof(MOVMuxContext),
5243 .audio_codec = AV_CODEC_ID_AAC,
5244 .video_codec = CONFIG_LIBX264_ENCODER ?
5245 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5246 .write_header = mov_write_header,
5247 .write_packet = mov_write_packet,
5248 .write_trailer = mov_write_trailer,
5249 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5250 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5251 .priv_class = &psp_muxer_class,
5254 #if CONFIG_TG2_MUXER
5256 AVOutputFormat ff_tg2_muxer = {
5258 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
5259 .extensions = "3g2",
5260 .priv_data_size = sizeof(MOVMuxContext),
5261 .audio_codec = AV_CODEC_ID_AMR_NB,
5262 .video_codec = AV_CODEC_ID_H263,
5263 .write_header = mov_write_header,
5264 .write_packet = mov_write_packet,
5265 .write_trailer = mov_write_trailer,
5266 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5267 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5268 .priv_class = &tg2_muxer_class,
5271 #if CONFIG_IPOD_MUXER
5273 AVOutputFormat ff_ipod_muxer = {
5275 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
5276 .mime_type = "application/mp4",
5277 .extensions = "m4v,m4a",
5278 .priv_data_size = sizeof(MOVMuxContext),
5279 .audio_codec = AV_CODEC_ID_AAC,
5280 .video_codec = AV_CODEC_ID_H264,
5281 .write_header = mov_write_header,
5282 .write_packet = mov_write_packet,
5283 .write_trailer = mov_write_trailer,
5284 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5285 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
5286 .priv_class = &ipod_muxer_class,
5289 #if CONFIG_ISMV_MUXER
5291 AVOutputFormat ff_ismv_muxer = {
5293 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
5294 .mime_type = "application/mp4",
5295 .extensions = "ismv,isma",
5296 .priv_data_size = sizeof(MOVMuxContext),
5297 .audio_codec = AV_CODEC_ID_AAC,
5298 .video_codec = AV_CODEC_ID_H264,
5299 .write_header = mov_write_header,
5300 .write_packet = mov_write_packet,
5301 .write_trailer = mov_write_trailer,
5302 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5303 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5304 .priv_class = &ismv_muxer_class,
5307 #if CONFIG_F4V_MUXER
5309 AVOutputFormat ff_f4v_muxer = {
5311 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
5312 .mime_type = "application/f4v",
5313 .extensions = "f4v",
5314 .priv_data_size = sizeof(MOVMuxContext),
5315 .audio_codec = AV_CODEC_ID_AAC,
5316 .video_codec = AV_CODEC_ID_H264,
5317 .write_header = mov_write_header,
5318 .write_packet = mov_write_packet,
5319 .write_trailer = mov_write_trailer,
5320 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
5321 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
5322 .priv_class = &f4v_muxer_class,