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 mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1087 ffio_wfourcc(pb, "DpxE");
1088 if (track->enc->extradata_size >= 12 &&
1089 !memcmp(&track->enc->extradata[4], "DpxE", 4)) {
1090 avio_wb32(pb, track->enc->extradata[11]);
1097 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1099 int tag = track->enc->codec_tag;
1101 if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
1104 if (track->enc->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1105 else if (track->enc->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1106 else if (track->enc->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1107 else if (track->enc->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1108 else if (track->enc->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1109 else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1110 else if (track->enc->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1111 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1112 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1113 else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1118 static const AVCodecTag codec_ipod_tags[] = {
1119 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1120 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1121 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1122 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1123 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1124 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1125 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1126 { AV_CODEC_ID_NONE, 0 },
1129 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1131 int tag = track->enc->codec_tag;
1133 // keep original tag for subs, ipod supports both formats
1134 if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1135 (tag == MKTAG('t', 'x', '3', 'g') ||
1136 tag == MKTAG('t', 'e', 'x', 't'))))
1137 tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
1139 if (!av_match_ext(s->filename, "m4a") &&
1140 !av_match_ext(s->filename, "m4b") &&
1141 !av_match_ext(s->filename, "m4v"))
1142 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1143 "Quicktime/Ipod might not play the file\n");
1148 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1152 if (track->enc->width == 720) { /* SD */
1153 if (track->enc->height == 480) { /* NTSC */
1154 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1155 else tag = MKTAG('d','v','c',' ');
1156 }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1157 else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1158 else tag = MKTAG('d','v','p','p');
1159 } else if (track->enc->height == 720) { /* HD 720 line */
1160 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1161 else tag = MKTAG('d','v','h','p');
1162 } else if (track->enc->height == 1080) { /* HD 1080 line */
1163 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1164 else tag = MKTAG('d','v','h','6');
1166 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1173 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1175 AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
1176 /* if the codec time base makes no sense, try to fallback on stream frame rate */
1177 if (av_timecode_check_frame_rate(rate) < 0) {
1178 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1179 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1180 rate = st->avg_frame_rate;
1186 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1188 int tag = track->enc->codec_tag;
1189 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1190 AVStream *st = track->st;
1191 int rate = av_q2d(find_fps(s, st));
1194 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1196 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
1197 if (track->enc->width == 1280 && track->enc->height == 720) {
1199 if (rate == 24) tag = MKTAG('x','d','v','4');
1200 else if (rate == 25) tag = MKTAG('x','d','v','5');
1201 else if (rate == 30) tag = MKTAG('x','d','v','1');
1202 else if (rate == 50) tag = MKTAG('x','d','v','a');
1203 else if (rate == 60) tag = MKTAG('x','d','v','9');
1205 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
1207 if (rate == 24) tag = MKTAG('x','d','v','6');
1208 else if (rate == 25) tag = MKTAG('x','d','v','7');
1209 else if (rate == 30) tag = MKTAG('x','d','v','8');
1211 if (rate == 25) tag = MKTAG('x','d','v','3');
1212 else if (rate == 30) tag = MKTAG('x','d','v','2');
1214 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1216 if (rate == 24) tag = MKTAG('x','d','v','d');
1217 else if (rate == 25) tag = MKTAG('x','d','v','e');
1218 else if (rate == 30) tag = MKTAG('x','d','v','f');
1220 if (rate == 25) tag = MKTAG('x','d','v','c');
1221 else if (rate == 30) tag = MKTAG('x','d','v','b');
1224 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1225 if (track->enc->width == 1280 && track->enc->height == 720) {
1227 if (rate == 24) tag = MKTAG('x','d','5','4');
1228 else if (rate == 25) tag = MKTAG('x','d','5','5');
1229 else if (rate == 30) tag = MKTAG('x','d','5','1');
1230 else if (rate == 50) tag = MKTAG('x','d','5','a');
1231 else if (rate == 60) tag = MKTAG('x','d','5','9');
1233 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1235 if (rate == 24) tag = MKTAG('x','d','5','d');
1236 else if (rate == 25) tag = MKTAG('x','d','5','e');
1237 else if (rate == 30) tag = MKTAG('x','d','5','f');
1239 if (rate == 25) tag = MKTAG('x','d','5','c');
1240 else if (rate == 30) tag = MKTAG('x','d','5','b');
1248 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1250 int tag = track->enc->codec_tag;
1251 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1252 AVStream *st = track->st;
1253 int rate = av_q2d(find_fps(s, st));
1256 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1258 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P10) {
1259 if (track->enc->width == 960 && track->enc->height == 720) {
1261 if (rate == 24) tag = MKTAG('a','i','5','p');
1262 else if (rate == 25) tag = MKTAG('a','i','5','q');
1263 else if (rate == 30) tag = MKTAG('a','i','5','p');
1264 else if (rate == 50) tag = MKTAG('a','i','5','q');
1265 else if (rate == 60) tag = MKTAG('a','i','5','p');
1267 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
1269 if (rate == 24) tag = MKTAG('a','i','5','3');
1270 else if (rate == 25) tag = MKTAG('a','i','5','2');
1271 else if (rate == 30) tag = MKTAG('a','i','5','3');
1273 if (rate == 50) tag = MKTAG('a','i','5','5');
1274 else if (rate == 60) tag = MKTAG('a','i','5','6');
1277 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P10) {
1278 if (track->enc->width == 1280 && track->enc->height == 720) {
1280 if (rate == 24) tag = MKTAG('a','i','1','p');
1281 else if (rate == 25) tag = MKTAG('a','i','1','q');
1282 else if (rate == 30) tag = MKTAG('a','i','1','p');
1283 else if (rate == 50) tag = MKTAG('a','i','1','q');
1284 else if (rate == 60) tag = MKTAG('a','i','1','p');
1286 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1288 if (rate == 24) tag = MKTAG('a','i','1','3');
1289 else if (rate == 25) tag = MKTAG('a','i','1','2');
1290 else if (rate == 30) tag = MKTAG('a','i','1','3');
1292 if (rate == 25) tag = MKTAG('a','i','1','5');
1293 else if (rate == 50) tag = MKTAG('a','i','1','5');
1294 else if (rate == 60) tag = MKTAG('a','i','1','6');
1296 } else if ( track->enc->width == 4096 && track->enc->height == 2160
1297 || track->enc->width == 3840 && track->enc->height == 2160
1298 || track->enc->width == 2048 && track->enc->height == 1080) {
1299 tag = MKTAG('a','i','v','x');
1306 static const struct {
1307 enum AVPixelFormat pix_fmt;
1310 } mov_pix_fmt_tags[] = {
1311 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1312 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1313 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1314 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1315 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1316 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1317 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1318 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1319 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1320 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1321 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1322 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1323 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1324 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1325 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1328 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1330 int tag = track->enc->codec_tag;
1332 enum AVPixelFormat pix_fmt;
1334 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1335 if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
1336 tag = mov_pix_fmt_tags[i].tag;
1337 track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1338 if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
1343 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1344 track->enc->bits_per_coded_sample);
1345 if (tag == MKTAG('r','a','w',' ') &&
1346 track->enc->pix_fmt != pix_fmt &&
1347 track->enc->pix_fmt != AV_PIX_FMT_NONE)
1348 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1349 av_get_pix_fmt_name(track->enc->pix_fmt));
1353 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1355 int tag = track->enc->codec_tag;
1357 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1358 (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
1359 track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
1360 track->enc->codec_id == AV_CODEC_ID_H263 ||
1361 track->enc->codec_id == AV_CODEC_ID_H264 ||
1362 track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1363 av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
1364 if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
1365 tag = mov_get_dv_codec_tag(s, track);
1366 else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
1367 tag = mov_get_rawvideo_codec_tag(s, track);
1368 else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1369 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1370 else if (track->enc->codec_id == AV_CODEC_ID_H264)
1371 tag = mov_get_h264_codec_tag(s, track);
1372 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1373 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
1374 if (!tag) { // if no mac fcc found, try with Microsoft tags
1375 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
1377 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1378 "the file may be unplayable!\n");
1380 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1381 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
1382 if (!tag) { // if no mac fcc found, try with Microsoft tags
1383 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
1385 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1386 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1387 "the file may be unplayable!\n");
1390 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1391 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
1397 static const AVCodecTag codec_3gp_tags[] = {
1398 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1399 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1400 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1401 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1402 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1403 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1404 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1405 { AV_CODEC_ID_NONE, 0 },
1408 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1409 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1410 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1411 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1412 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1413 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1414 { AV_CODEC_ID_NONE, 0 },
1417 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1421 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1422 tag = mp4_get_codec_tag(s, track);
1423 else if (track->mode == MODE_ISM) {
1424 tag = mp4_get_codec_tag(s, track);
1425 if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
1426 tag = MKTAG('w', 'm', 'a', ' ');
1427 } else if (track->mode == MODE_IPOD)
1428 tag = ipod_get_codec_tag(s, track);
1429 else if (track->mode & MODE_3GP)
1430 tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
1431 else if (track->mode == MODE_F4V)
1432 tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
1434 tag = mov_get_codec_tag(s, track);
1439 /** Write uuid atom.
1440 * Needed to make file play in iPods running newest firmware
1441 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1443 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1446 ffio_wfourcc(pb, "uuid");
1447 avio_wb32(pb, 0x6b6840f2);
1448 avio_wb32(pb, 0x5f244fc5);
1449 avio_wb32(pb, 0xba39a51b);
1450 avio_wb32(pb, 0xcf0323f3);
1455 static const uint16_t fiel_data[] = {
1456 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1459 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
1461 unsigned mov_field_order = 0;
1462 if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
1463 mov_field_order = fiel_data[track->enc->field_order];
1467 ffio_wfourcc(pb, "fiel");
1468 avio_wb16(pb, mov_field_order);
1472 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1474 int64_t pos = avio_tell(pb);
1475 avio_wb32(pb, 0); /* size */
1476 avio_wl32(pb, track->tag); // store it byteswapped
1477 avio_wb32(pb, 0); /* Reserved */
1478 avio_wb16(pb, 0); /* Reserved */
1479 avio_wb16(pb, 1); /* Data-reference index */
1481 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1482 mov_write_esds_tag(pb, track);
1483 else if (track->enc->extradata_size)
1484 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1486 return update_size(pb, pos);
1489 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1492 av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
1493 track->enc->sample_aspect_ratio.den, INT_MAX);
1496 ffio_wfourcc(pb, "pasp");
1497 avio_wb32(pb, sar.num);
1498 avio_wb32(pb, sar.den);
1502 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1504 AVDictionaryEntry *encoder;
1505 int xdcam_res = (track->enc->width == 1280 && track->enc->height == 720)
1506 || (track->enc->width == 1440 && track->enc->height == 1080)
1507 || (track->enc->width == 1920 && track->enc->height == 1080);
1509 if (track->mode == MODE_MOV &&
1510 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1511 av_strlcpy(compressor_name, encoder->value, 32);
1512 } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1513 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1514 AVStream *st = track->st;
1515 int rate = av_q2d(find_fps(NULL, st));
1516 av_strlcatf(compressor_name, len, "XDCAM");
1517 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1518 av_strlcatf(compressor_name, len, " HD422");
1519 } else if(track->enc->width == 1440) {
1520 av_strlcatf(compressor_name, len, " HD");
1522 av_strlcatf(compressor_name, len, " EX");
1524 av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
1526 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1530 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1532 int64_t pos = avio_tell(pb);
1533 char compressor_name[32] = { 0 };
1535 avio_wb32(pb, 0); /* size */
1536 avio_wl32(pb, track->tag); // store it byteswapped
1537 avio_wb32(pb, 0); /* Reserved */
1538 avio_wb16(pb, 0); /* Reserved */
1539 avio_wb16(pb, 1); /* Data-reference index */
1541 avio_wb16(pb, 0); /* Codec stream version */
1542 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1543 if (track->mode == MODE_MOV) {
1544 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1545 if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
1546 avio_wb32(pb, 0); /* Temporal Quality */
1547 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1549 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1550 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1553 avio_wb32(pb, 0); /* Reserved */
1554 avio_wb32(pb, 0); /* Reserved */
1555 avio_wb32(pb, 0); /* Reserved */
1557 avio_wb16(pb, track->enc->width); /* Video width */
1558 avio_wb16(pb, track->height); /* Video height */
1559 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1560 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1561 avio_wb32(pb, 0); /* Data size (= 0) */
1562 avio_wb16(pb, 1); /* Frame count (= 1) */
1564 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1565 find_compressor(compressor_name, 32, track);
1566 avio_w8(pb, strlen(compressor_name));
1567 avio_write(pb, compressor_name, 31);
1569 if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1570 avio_wb16(pb, track->enc->bits_per_coded_sample);
1572 avio_wb16(pb, 0x18); /* Reserved */
1573 avio_wb16(pb, 0xffff); /* Reserved */
1574 if (track->tag == MKTAG('m','p','4','v'))
1575 mov_write_esds_tag(pb, track);
1576 else if (track->enc->codec_id == AV_CODEC_ID_H263)
1577 mov_write_d263_tag(pb);
1578 else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
1579 track->enc->codec_id == AV_CODEC_ID_SVQ3) {
1580 mov_write_extradata_tag(pb, track);
1582 } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
1583 mov_write_avid_tag(pb, track);
1584 else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
1585 mov_write_hvcc_tag(pb, track);
1586 else if (track->enc->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1587 mov_write_avcc_tag(pb, track);
1588 if (track->mode == MODE_IPOD)
1589 mov_write_uuid_tag_ipod(pb);
1590 } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1591 mov_write_dvc1_tag(pb, track);
1592 else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
1593 track->enc->codec_id == AV_CODEC_ID_VP6A) {
1594 /* Don't write any potential extradata here - the cropping
1595 * is signalled via the normal width/height fields. */
1596 } else if (track->enc->codec_id == AV_CODEC_ID_R10K) {
1597 if (track->enc->codec_tag == MKTAG('R','1','0','k'))
1598 mov_write_dpxe_tag(pb, track);
1599 } else if (track->vos_len > 0)
1600 mov_write_glbl_tag(pb, track);
1602 if (track->enc->codec_id != AV_CODEC_ID_H264 &&
1603 track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
1604 track->enc->codec_id != AV_CODEC_ID_DNXHD)
1605 if (track->enc->field_order != AV_FIELD_UNKNOWN)
1606 mov_write_fiel_tag(pb, track);
1608 if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1609 track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1610 mov_write_pasp_tag(pb, track);
1613 return update_size(pb, pos);
1616 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1618 int64_t pos = avio_tell(pb);
1619 avio_wb32(pb, 0); /* size */
1620 ffio_wfourcc(pb, "rtp ");
1621 avio_wb32(pb, 0); /* Reserved */
1622 avio_wb16(pb, 0); /* Reserved */
1623 avio_wb16(pb, 1); /* Data-reference index */
1625 avio_wb16(pb, 1); /* Hint track version */
1626 avio_wb16(pb, 1); /* Highest compatible version */
1627 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1629 avio_wb32(pb, 12); /* size */
1630 ffio_wfourcc(pb, "tims");
1631 avio_wb32(pb, track->timescale);
1633 return update_size(pb, pos);
1636 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1638 uint64_t str_size =strlen(reel_name);
1639 int64_t pos = avio_tell(pb);
1641 if (str_size >= UINT16_MAX){
1642 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1644 return AVERROR(EINVAL);
1647 avio_wb32(pb, 0); /* size */
1648 ffio_wfourcc(pb, "name"); /* Data format */
1649 avio_wb16(pb, str_size); /* string size */
1650 avio_wb16(pb, track->language); /* langcode */
1651 avio_write(pb, reel_name, str_size); /* reel name */
1652 return update_size(pb,pos);
1655 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1657 int64_t pos = avio_tell(pb);
1659 int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
1660 int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
1661 AVDictionaryEntry *t = NULL;
1663 if (nb_frames > 255) {
1664 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1665 return AVERROR(EINVAL);
1668 avio_wb32(pb, 0); /* size */
1669 ffio_wfourcc(pb, "tmcd"); /* Data format */
1670 avio_wb32(pb, 0); /* Reserved */
1671 avio_wb32(pb, 1); /* Data reference index */
1672 avio_wb32(pb, 0); /* Flags */
1673 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1674 avio_wb32(pb, track->timescale); /* Timescale */
1675 avio_wb32(pb, frame_duration); /* Frame duration */
1676 avio_w8(pb, nb_frames); /* Number of frames */
1677 avio_w8(pb, 0); /* Reserved */
1680 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1682 if (t && utf8len(t->value))
1683 mov_write_source_reference_tag(pb, track, t->value);
1685 avio_wb16(pb, 0); /* zero size */
1688 avio_wb32(pb, 0); /* size */
1689 ffio_wfourcc(pb, "tmcd"); /* Data format */
1690 avio_wb32(pb, 0); /* Reserved */
1691 avio_wb32(pb, 1); /* Data reference index */
1692 if (track->enc->extradata_size)
1693 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1695 return update_size(pb, pos);
1698 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
1700 int64_t pos = avio_tell(pb);
1701 avio_wb32(pb, 0); /* size */
1702 ffio_wfourcc(pb, "stsd");
1703 avio_wb32(pb, 0); /* version & flags */
1704 avio_wb32(pb, 1); /* entry count */
1705 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1706 mov_write_video_tag(pb, track);
1707 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1708 mov_write_audio_tag(pb, track);
1709 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1710 mov_write_subtitle_tag(pb, track);
1711 else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1712 mov_write_rtp_tag(pb, track);
1713 else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1714 mov_write_tmcd_tag(pb, track);
1715 return update_size(pb, pos);
1718 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1720 MOVStts *ctts_entries;
1721 uint32_t entries = 0;
1725 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1726 ctts_entries[0].count = 1;
1727 ctts_entries[0].duration = track->cluster[0].cts;
1728 for (i = 1; i < track->entry; i++) {
1729 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1730 ctts_entries[entries].count++; /* compress */
1733 ctts_entries[entries].duration = track->cluster[i].cts;
1734 ctts_entries[entries].count = 1;
1737 entries++; /* last one */
1738 atom_size = 16 + (entries * 8);
1739 avio_wb32(pb, atom_size); /* size */
1740 ffio_wfourcc(pb, "ctts");
1741 avio_wb32(pb, 0); /* version & flags */
1742 avio_wb32(pb, entries); /* entry count */
1743 for (i = 0; i < entries; i++) {
1744 avio_wb32(pb, ctts_entries[i].count);
1745 avio_wb32(pb, ctts_entries[i].duration);
1747 av_free(ctts_entries);
1751 /* Time to sample atom */
1752 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1754 MOVStts *stts_entries;
1755 uint32_t entries = -1;
1759 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1760 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1761 stts_entries[0].count = track->sample_count;
1762 stts_entries[0].duration = 1;
1765 stts_entries = track->entry ?
1766 av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */
1768 for (i = 0; i < track->entry; i++) {
1769 int duration = get_cluster_duration(track, i);
1770 if (i && duration == stts_entries[entries].duration) {
1771 stts_entries[entries].count++; /* compress */
1774 stts_entries[entries].duration = duration;
1775 stts_entries[entries].count = 1;
1778 entries++; /* last one */
1780 atom_size = 16 + (entries * 8);
1781 avio_wb32(pb, atom_size); /* size */
1782 ffio_wfourcc(pb, "stts");
1783 avio_wb32(pb, 0); /* version & flags */
1784 avio_wb32(pb, entries); /* entry count */
1785 for (i = 0; i < entries; i++) {
1786 avio_wb32(pb, stts_entries[i].count);
1787 avio_wb32(pb, stts_entries[i].duration);
1789 av_free(stts_entries);
1793 static int mov_write_dref_tag(AVIOContext *pb)
1795 avio_wb32(pb, 28); /* size */
1796 ffio_wfourcc(pb, "dref");
1797 avio_wb32(pb, 0); /* version & flags */
1798 avio_wb32(pb, 1); /* entry count */
1800 avio_wb32(pb, 0xc); /* size */
1801 //FIXME add the alis and rsrc atom
1802 ffio_wfourcc(pb, "url ");
1803 avio_wb32(pb, 1); /* version & flags */
1808 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1810 int64_t pos = avio_tell(pb);
1811 avio_wb32(pb, 0); /* size */
1812 ffio_wfourcc(pb, "stbl");
1813 mov_write_stsd_tag(pb, track);
1814 mov_write_stts_tag(pb, track);
1815 if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1816 track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1817 track->has_keyframes && track->has_keyframes < track->entry)
1818 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1819 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1820 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1821 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1822 track->flags & MOV_TRACK_CTTS && track->entry)
1823 mov_write_ctts_tag(pb, track);
1824 mov_write_stsc_tag(pb, track);
1825 mov_write_stsz_tag(pb, track);
1826 mov_write_stco_tag(pb, track);
1827 return update_size(pb, pos);
1830 static int mov_write_dinf_tag(AVIOContext *pb)
1832 int64_t pos = avio_tell(pb);
1833 avio_wb32(pb, 0); /* size */
1834 ffio_wfourcc(pb, "dinf");
1835 mov_write_dref_tag(pb);
1836 return update_size(pb, pos);
1839 static int mov_write_nmhd_tag(AVIOContext *pb)
1842 ffio_wfourcc(pb, "nmhd");
1847 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
1849 int64_t pos = avio_tell(pb);
1850 const char *font = "Lucida Grande";
1851 avio_wb32(pb, 0); /* size */
1852 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
1853 avio_wb32(pb, 0); /* version & flags */
1854 avio_wb16(pb, 0); /* text font */
1855 avio_wb16(pb, 0); /* text face */
1856 avio_wb16(pb, 12); /* text size */
1857 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
1858 avio_wb16(pb, 0x0000); /* text color (red) */
1859 avio_wb16(pb, 0x0000); /* text color (green) */
1860 avio_wb16(pb, 0x0000); /* text color (blue) */
1861 avio_wb16(pb, 0xffff); /* background color (red) */
1862 avio_wb16(pb, 0xffff); /* background color (green) */
1863 avio_wb16(pb, 0xffff); /* background color (blue) */
1864 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
1865 avio_write(pb, font, strlen(font)); /* font name */
1866 return update_size(pb, pos);
1869 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
1871 int64_t pos = avio_tell(pb);
1872 avio_wb32(pb, 0); /* size */
1873 ffio_wfourcc(pb, "gmhd");
1874 avio_wb32(pb, 0x18); /* gmin size */
1875 ffio_wfourcc(pb, "gmin");/* generic media info */
1876 avio_wb32(pb, 0); /* version & flags */
1877 avio_wb16(pb, 0x40); /* graphics mode = */
1878 avio_wb16(pb, 0x8000); /* opColor (r?) */
1879 avio_wb16(pb, 0x8000); /* opColor (g?) */
1880 avio_wb16(pb, 0x8000); /* opColor (b?) */
1881 avio_wb16(pb, 0); /* balance */
1882 avio_wb16(pb, 0); /* reserved */
1885 * This special text atom is required for
1886 * Apple Quicktime chapters. The contents
1887 * don't appear to be documented, so the
1888 * bytes are copied verbatim.
1890 if (track->tag != MKTAG('c','6','0','8')) {
1891 avio_wb32(pb, 0x2C); /* size */
1892 ffio_wfourcc(pb, "text");
1893 avio_wb16(pb, 0x01);
1894 avio_wb32(pb, 0x00);
1895 avio_wb32(pb, 0x00);
1896 avio_wb32(pb, 0x00);
1897 avio_wb32(pb, 0x01);
1898 avio_wb32(pb, 0x00);
1899 avio_wb32(pb, 0x00);
1900 avio_wb32(pb, 0x00);
1901 avio_wb32(pb, 0x00004000);
1902 avio_wb16(pb, 0x0000);
1905 if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1906 int64_t tmcd_pos = avio_tell(pb);
1907 avio_wb32(pb, 0); /* size */
1908 ffio_wfourcc(pb, "tmcd");
1909 mov_write_tcmi_tag(pb, track);
1910 update_size(pb, tmcd_pos);
1912 return update_size(pb, pos);
1915 static int mov_write_smhd_tag(AVIOContext *pb)
1917 avio_wb32(pb, 16); /* size */
1918 ffio_wfourcc(pb, "smhd");
1919 avio_wb32(pb, 0); /* version & flags */
1920 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1921 avio_wb16(pb, 0); /* reserved */
1925 static int mov_write_vmhd_tag(AVIOContext *pb)
1927 avio_wb32(pb, 0x14); /* size (always 0x14) */
1928 ffio_wfourcc(pb, "vmhd");
1929 avio_wb32(pb, 0x01); /* version & flags */
1930 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1934 static int is_clcp_track(MOVTrack *track)
1936 return track->tag == MKTAG('c','7','0','8') ||
1937 track->tag == MKTAG('c','6','0','8');
1940 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1942 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1943 int64_t pos = avio_tell(pb);
1947 descr = "DataHandler";
1950 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1951 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1953 descr = "VideoHandler";
1954 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1956 descr = "SoundHandler";
1957 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1958 if (is_clcp_track(track)) {
1960 descr = "ClosedCaptionHandler";
1962 if (track->tag == MKTAG('t','x','3','g')) {
1964 } else if (track->tag == MKTAG('m','p','4','s')) {
1969 descr = "SubtitleHandler";
1971 } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1973 descr = "HintHandler";
1974 } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1976 descr = "TimeCodeHandler";
1979 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
1980 track->enc->codec_tag);
1982 av_log(track->enc, AV_LOG_WARNING,
1983 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
1984 tag_buf, track->enc->codec_tag);
1987 // hdlr.name is used by some players to identify the content title
1988 // of the track. So if an alternate handler description is
1989 // specified, use it.
1990 AVDictionaryEntry *t;
1991 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
1992 if (t && utf8len(t->value))
1997 avio_wb32(pb, 0); /* size */
1998 ffio_wfourcc(pb, "hdlr");
1999 avio_wb32(pb, 0); /* Version & flags */
2000 avio_write(pb, hdlr, 4); /* handler */
2001 ffio_wfourcc(pb, hdlr_type); /* handler type */
2002 avio_wb32(pb, 0); /* reserved */
2003 avio_wb32(pb, 0); /* reserved */
2004 avio_wb32(pb, 0); /* reserved */
2005 if (!track || track->mode == MODE_MOV)
2006 avio_w8(pb, strlen(descr)); /* pascal string */
2007 avio_write(pb, descr, strlen(descr)); /* handler description */
2008 if (track && track->mode != MODE_MOV)
2009 avio_w8(pb, 0); /* c string */
2010 return update_size(pb, pos);
2013 static int mov_write_hmhd_tag(AVIOContext *pb)
2015 /* This atom must be present, but leaving the values at zero
2016 * seems harmless. */
2017 avio_wb32(pb, 28); /* size */
2018 ffio_wfourcc(pb, "hmhd");
2019 avio_wb32(pb, 0); /* version, flags */
2020 avio_wb16(pb, 0); /* maxPDUsize */
2021 avio_wb16(pb, 0); /* avgPDUsize */
2022 avio_wb32(pb, 0); /* maxbitrate */
2023 avio_wb32(pb, 0); /* avgbitrate */
2024 avio_wb32(pb, 0); /* reserved */
2028 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
2030 int64_t pos = avio_tell(pb);
2031 avio_wb32(pb, 0); /* size */
2032 ffio_wfourcc(pb, "minf");
2033 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
2034 mov_write_vmhd_tag(pb);
2035 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2036 mov_write_smhd_tag(pb);
2037 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2038 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2039 mov_write_gmhd_tag(pb, track);
2041 mov_write_nmhd_tag(pb);
2043 } else if (track->tag == MKTAG('r','t','p',' ')) {
2044 mov_write_hmhd_tag(pb);
2045 } else if (track->tag == MKTAG('t','m','c','d')) {
2046 mov_write_gmhd_tag(pb, track);
2048 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2049 mov_write_hdlr_tag(pb, NULL);
2050 mov_write_dinf_tag(pb);
2051 mov_write_stbl_tag(pb, track);
2052 return update_size(pb, pos);
2055 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2058 int version = track->track_duration < INT32_MAX ? 0 : 1;
2060 if (track->mode == MODE_ISM)
2063 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2064 ffio_wfourcc(pb, "mdhd");
2065 avio_w8(pb, version);
2066 avio_wb24(pb, 0); /* flags */
2068 avio_wb64(pb, track->time);
2069 avio_wb64(pb, track->time);
2071 avio_wb32(pb, track->time); /* creation time */
2072 avio_wb32(pb, track->time); /* modification time */
2074 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2075 if (!track->entry && mov->mode == MODE_ISM)
2076 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2077 else if (!track->entry)
2078 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2080 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2081 avio_wb16(pb, track->language); /* language */
2082 avio_wb16(pb, 0); /* reserved (quality) */
2084 if (version != 0 && track->mode == MODE_MOV) {
2085 av_log(NULL, AV_LOG_ERROR,
2086 "FATAL error, file duration too long for timebase, this file will not be\n"
2087 "playable with quicktime. Choose a different timebase or a different\n"
2088 "container format\n");
2094 static int mov_write_mdia_tag(AVIOContext *pb, MOVMuxContext *mov,
2097 int64_t pos = avio_tell(pb);
2098 avio_wb32(pb, 0); /* size */
2099 ffio_wfourcc(pb, "mdia");
2100 mov_write_mdhd_tag(pb, mov, track);
2101 mov_write_hdlr_tag(pb, track);
2102 mov_write_minf_tag(pb, track);
2103 return update_size(pb, pos);
2106 /* transformation matrix
2110 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2111 int16_t d, int16_t tx, int16_t ty)
2113 avio_wb32(pb, a << 16); /* 16.16 format */
2114 avio_wb32(pb, b << 16); /* 16.16 format */
2115 avio_wb32(pb, 0); /* u in 2.30 format */
2116 avio_wb32(pb, c << 16); /* 16.16 format */
2117 avio_wb32(pb, d << 16); /* 16.16 format */
2118 avio_wb32(pb, 0); /* v in 2.30 format */
2119 avio_wb32(pb, tx << 16); /* 16.16 format */
2120 avio_wb32(pb, ty << 16); /* 16.16 format */
2121 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2124 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2125 MOVTrack *track, AVStream *st)
2127 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2128 track->timescale, AV_ROUND_UP);
2129 int version = duration < INT32_MAX ? 0 : 1;
2130 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2136 if (mov->per_stream_grouping)
2139 group = st->codec->codec_type;
2142 if (track->flags & MOV_TRACK_ENABLED)
2143 flags |= MOV_TKHD_FLAG_ENABLED;
2145 if (track->mode == MODE_ISM)
2148 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2149 ffio_wfourcc(pb, "tkhd");
2150 avio_w8(pb, version);
2151 avio_wb24(pb, flags);
2153 avio_wb64(pb, track->time);
2154 avio_wb64(pb, track->time);
2156 avio_wb32(pb, track->time); /* creation time */
2157 avio_wb32(pb, track->time); /* modification time */
2159 avio_wb32(pb, track->track_id); /* track-id */
2160 avio_wb32(pb, 0); /* reserved */
2161 if (!track->entry && mov->mode == MODE_ISM)
2162 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2163 else if (!track->entry)
2164 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2166 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2168 avio_wb32(pb, 0); /* reserved */
2169 avio_wb32(pb, 0); /* reserved */
2170 avio_wb16(pb, 0); /* layer */
2171 avio_wb16(pb, group); /* alternate group) */
2172 /* Volume, only for audio */
2173 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2174 avio_wb16(pb, 0x0100);
2177 avio_wb16(pb, 0); /* reserved */
2179 /* Matrix structure */
2180 if (st && st->metadata) {
2181 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2182 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2184 if (rotation == 90) {
2185 write_matrix(pb, 0, 1, -1, 0, track->enc->height, 0);
2186 } else if (rotation == 180) {
2187 write_matrix(pb, -1, 0, 0, -1, track->enc->width, track->enc->height);
2188 } else if (rotation == 270) {
2189 write_matrix(pb, 0, -1, 1, 0, 0, track->enc->width);
2191 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2193 /* Track width and height, for visual only */
2194 if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
2195 track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2196 if (track->mode == MODE_MOV) {
2197 avio_wb32(pb, track->enc->width << 16);
2198 avio_wb32(pb, track->height << 16);
2200 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2201 if (!sample_aspect_ratio || track->height != track->enc->height)
2202 sample_aspect_ratio = 1;
2203 avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
2204 avio_wb32(pb, track->height * 0x10000);
2213 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2215 int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
2216 track->enc->sample_aspect_ratio.den);
2218 int64_t pos = avio_tell(pb);
2220 avio_wb32(pb, 0); /* size */
2221 ffio_wfourcc(pb, "tapt");
2224 ffio_wfourcc(pb, "clef");
2226 avio_wb32(pb, width << 16);
2227 avio_wb32(pb, track->enc->height << 16);
2230 ffio_wfourcc(pb, "prof");
2232 avio_wb32(pb, width << 16);
2233 avio_wb32(pb, track->enc->height << 16);
2236 ffio_wfourcc(pb, "enof");
2238 avio_wb32(pb, track->enc->width << 16);
2239 avio_wb32(pb, track->enc->height << 16);
2241 return update_size(pb, pos);
2244 // This box seems important for the psp playback ... without it the movie seems to hang
2245 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2248 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2249 track->timescale, AV_ROUND_UP);
2250 int version = duration < INT32_MAX ? 0 : 1;
2251 int entry_size, entry_count, size;
2252 int64_t delay, start_ct = track->start_cts;
2253 int64_t start_dts = track->start_dts;
2256 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2258 av_log(mov->fc, AV_LOG_DEBUG,
2259 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2260 track->cluster[0].dts, track->cluster[0].cts,
2261 start_dts, start_ct, track->track_id);
2262 start_dts = track->cluster[0].dts;
2263 start_ct = track->cluster[0].cts;
2267 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2268 track->timescale, AV_ROUND_DOWN);
2269 version |= delay < INT32_MAX ? 0 : 1;
2271 entry_size = (version == 1) ? 20 : 12;
2272 entry_count = 1 + (delay > 0);
2273 size = 24 + entry_count * entry_size;
2275 /* write the atom data */
2276 avio_wb32(pb, size);
2277 ffio_wfourcc(pb, "edts");
2278 avio_wb32(pb, size - 8);
2279 ffio_wfourcc(pb, "elst");
2280 avio_w8(pb, version);
2281 avio_wb24(pb, 0); /* flags */
2283 avio_wb32(pb, entry_count);
2284 if (delay > 0) { /* add an empty edit to delay presentation */
2285 /* In the positive delay case, the delay includes the cts
2286 * offset, and the second edit list entry below trims out
2287 * the same amount from the actual content. This makes sure
2288 * that the offsetted last sample is included in the edit
2289 * list duration as well. */
2291 avio_wb64(pb, delay);
2294 avio_wb32(pb, delay);
2297 avio_wb32(pb, 0x00010000);
2299 /* Avoid accidentally ending up with start_ct = -1 which has got a
2300 * special meaning. Normally start_ct should end up positive or zero
2301 * here, but use FFMIN in case dts is a a small positive integer
2302 * rounded to 0 when represented in MOV_TIMESCALE units. */
2303 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2304 start_ct = -FFMIN(start_dts, 0);
2305 /* Note, this delay is calculated from the pts of the first sample,
2306 * ensuring that we don't reduce the duration for cases with
2311 /* For fragmented files, we don't know the full length yet. Setting
2312 * duration to 0 allows us to only specify the offset, including
2313 * the rest of the content (from all future fragments) without specifying
2314 * an explicit duration. */
2315 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2320 avio_wb64(pb, duration);
2321 avio_wb64(pb, start_ct);
2323 avio_wb32(pb, duration);
2324 avio_wb32(pb, start_ct);
2326 avio_wb32(pb, 0x00010000);
2330 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2332 avio_wb32(pb, 20); // size
2333 ffio_wfourcc(pb, "tref");
2334 avio_wb32(pb, 12); // size (subatom)
2335 avio_wl32(pb, track->tref_tag);
2336 avio_wb32(pb, track->tref_id);
2340 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2341 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2343 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2344 ffio_wfourcc(pb, "uuid");
2345 ffio_wfourcc(pb, "USMT");
2346 avio_wb32(pb, 0x21d24fce);
2347 avio_wb32(pb, 0xbb88695c);
2348 avio_wb32(pb, 0xfac9c740);
2349 avio_wb32(pb, 0x1c); // another size here!
2350 ffio_wfourcc(pb, "MTDT");
2351 avio_wb32(pb, 0x00010012);
2352 avio_wb32(pb, 0x0a);
2353 avio_wb32(pb, 0x55c40000);
2359 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2361 AVFormatContext *ctx = track->rtp_ctx;
2362 char buf[1000] = "";
2365 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2366 NULL, NULL, 0, 0, ctx);
2367 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2370 avio_wb32(pb, len + 24);
2371 ffio_wfourcc(pb, "udta");
2372 avio_wb32(pb, len + 16);
2373 ffio_wfourcc(pb, "hnti");
2374 avio_wb32(pb, len + 8);
2375 ffio_wfourcc(pb, "sdp ");
2376 avio_write(pb, buf, len);
2380 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2381 const char *tag, const char *str)
2383 int64_t pos = avio_tell(pb);
2384 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2385 if (!t || !utf8len(t->value))
2388 avio_wb32(pb, 0); /* size */
2389 ffio_wfourcc(pb, tag); /* type */
2390 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2391 return update_size(pb, pos);
2394 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2397 AVIOContext *pb_buf;
2401 if (!st || mov->fc->flags & AVFMT_FLAG_BITEXACT)
2404 ret = avio_open_dyn_buf(&pb_buf);
2408 if (mov->mode & MODE_MP4)
2409 mov_write_track_metadata(pb_buf, st, "name", "title");
2411 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2412 avio_wb32(pb, size + 8);
2413 ffio_wfourcc(pb, "udta");
2414 avio_write(pb, buf, size);
2421 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
2422 MOVTrack *track, AVStream *st)
2424 int64_t pos = avio_tell(pb);
2425 int entry_backup = track->entry;
2426 int chunk_backup = track->chunkCount;
2427 /* If we want to have an empty moov, but some samples already have been
2428 * buffered (delay_moov), pretend that no samples have been written yet. */
2429 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2430 track->chunkCount = track->entry = 0;
2432 avio_wb32(pb, 0); /* size */
2433 ffio_wfourcc(pb, "trak");
2434 mov_write_tkhd_tag(pb, mov, track, st);
2436 av_assert2(mov->use_editlist >= 0);
2438 if (track->start_dts != AV_NOPTS_VALUE) {
2439 if (mov->use_editlist)
2440 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2441 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2442 av_log(mov->fc, AV_LOG_WARNING,
2443 "Not writing any edit list even though one would have been required\n");
2446 if (track->tref_tag)
2447 mov_write_tref_tag(pb, track);
2448 mov_write_mdia_tag(pb, mov, track);
2449 if (track->mode == MODE_PSP)
2450 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2451 if (track->tag == MKTAG('r','t','p',' '))
2452 mov_write_udta_sdp(pb, track);
2453 if (track->mode == MODE_MOV) {
2454 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2455 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2456 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2457 mov_write_tapt_tag(pb, track);
2460 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2461 mov_write_tapt_tag(pb, track);
2464 mov_write_track_udta_tag(pb, mov, st);
2465 track->entry = entry_backup;
2466 track->chunkCount = chunk_backup;
2467 return update_size(pb, pos);
2470 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2472 int i, has_audio = 0, has_video = 0;
2473 int64_t pos = avio_tell(pb);
2474 int audio_profile = mov->iods_audio_profile;
2475 int video_profile = mov->iods_video_profile;
2476 for (i = 0; i < mov->nb_streams; i++) {
2477 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2478 has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
2479 has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
2482 if (audio_profile < 0)
2483 audio_profile = 0xFF - has_audio;
2484 if (video_profile < 0)
2485 video_profile = 0xFF - has_video;
2486 avio_wb32(pb, 0x0); /* size */
2487 ffio_wfourcc(pb, "iods");
2488 avio_wb32(pb, 0); /* version & flags */
2489 put_descr(pb, 0x10, 7);
2490 avio_wb16(pb, 0x004f);
2493 avio_w8(pb, audio_profile);
2494 avio_w8(pb, video_profile);
2496 return update_size(pb, pos);
2499 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2501 avio_wb32(pb, 0x20); /* size */
2502 ffio_wfourcc(pb, "trex");
2503 avio_wb32(pb, 0); /* version & flags */
2504 avio_wb32(pb, track->track_id); /* track ID */
2505 avio_wb32(pb, 1); /* default sample description index */
2506 avio_wb32(pb, 0); /* default sample duration */
2507 avio_wb32(pb, 0); /* default sample size */
2508 avio_wb32(pb, 0); /* default sample flags */
2512 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2514 int64_t pos = avio_tell(pb);
2516 avio_wb32(pb, 0x0); /* size */
2517 ffio_wfourcc(pb, "mvex");
2518 for (i = 0; i < mov->nb_streams; i++)
2519 mov_write_trex_tag(pb, &mov->tracks[i]);
2520 return update_size(pb, pos);
2523 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2525 int max_track_id = 1, i;
2526 int64_t max_track_len = 0;
2529 for (i = 0; i < mov->nb_streams; i++) {
2530 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2531 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2533 mov->tracks[i].timescale,
2535 if (max_track_len < max_track_len_temp)
2536 max_track_len = max_track_len_temp;
2537 if (max_track_id < mov->tracks[i].track_id)
2538 max_track_id = mov->tracks[i].track_id;
2541 /* If using delay_moov, make sure the output is the same as if no
2542 * samples had been written yet. */
2543 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2548 version = max_track_len < UINT32_MAX ? 0 : 1;
2549 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
2551 ffio_wfourcc(pb, "mvhd");
2552 avio_w8(pb, version);
2553 avio_wb24(pb, 0); /* flags */
2555 avio_wb64(pb, mov->time);
2556 avio_wb64(pb, mov->time);
2558 avio_wb32(pb, mov->time); /* creation time */
2559 avio_wb32(pb, mov->time); /* modification time */
2561 avio_wb32(pb, MOV_TIMESCALE);
2562 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2564 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2565 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2566 avio_wb16(pb, 0); /* reserved */
2567 avio_wb32(pb, 0); /* reserved */
2568 avio_wb32(pb, 0); /* reserved */
2570 /* Matrix structure */
2571 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2573 avio_wb32(pb, 0); /* reserved (preview time) */
2574 avio_wb32(pb, 0); /* reserved (preview duration) */
2575 avio_wb32(pb, 0); /* reserved (poster time) */
2576 avio_wb32(pb, 0); /* reserved (selection time) */
2577 avio_wb32(pb, 0); /* reserved (selection duration) */
2578 avio_wb32(pb, 0); /* reserved (current time) */
2579 avio_wb32(pb, max_track_id + 1); /* Next track id */
2583 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2586 avio_wb32(pb, 33); /* size */
2587 ffio_wfourcc(pb, "hdlr");
2590 ffio_wfourcc(pb, "mdir");
2591 ffio_wfourcc(pb, "appl");
2598 /* helper function to write a data tag with the specified string as data */
2599 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2602 int size = 16 + strlen(data);
2603 avio_wb32(pb, size); /* size */
2604 ffio_wfourcc(pb, "data");
2607 avio_write(pb, data, strlen(data));
2611 lang = ff_mov_iso639_to_lang("und", 1);
2612 avio_wb16(pb, strlen(data)); /* string length */
2613 avio_wb16(pb, lang);
2614 avio_write(pb, data, strlen(data));
2615 return strlen(data) + 4;
2619 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2620 const char *value, int lang, int long_style)
2623 if (value && value[0]) {
2624 int64_t pos = avio_tell(pb);
2625 avio_wb32(pb, 0); /* size */
2626 ffio_wfourcc(pb, name);
2627 mov_write_string_data_tag(pb, value, lang, long_style);
2628 size = update_size(pb, pos);
2633 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2634 const char *name, const char *tag,
2637 int l, lang = 0, len, len2;
2638 AVDictionaryEntry *t, *t2 = NULL;
2641 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2644 len = strlen(t->key);
2645 snprintf(tag2, sizeof(tag2), "%s-", tag);
2646 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2647 len2 = strlen(t2->key);
2648 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2649 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2654 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2657 /* iTunes bpm number */
2658 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2660 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2661 int size = 0, tmpo = t ? atoi(t->value) : 0;
2664 avio_wb32(pb, size);
2665 ffio_wfourcc(pb, "tmpo");
2666 avio_wb32(pb, size-8); /* size */
2667 ffio_wfourcc(pb, "data");
2668 avio_wb32(pb, 0x15); //type specifier
2670 avio_wb16(pb, tmpo); // data
2675 /* iTunes track or disc number */
2676 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2677 AVFormatContext *s, int disc)
2679 AVDictionaryEntry *t = av_dict_get(s->metadata,
2680 disc ? "disc" : "track",
2682 int size = 0, track = t ? atoi(t->value) : 0;
2685 char *slash = strchr(t->value, '/');
2687 tracks = atoi(slash + 1);
2688 avio_wb32(pb, 32); /* size */
2689 ffio_wfourcc(pb, disc ? "disk" : "trkn");
2690 avio_wb32(pb, 24); /* size */
2691 ffio_wfourcc(pb, "data");
2692 avio_wb32(pb, 0); // 8 bytes empty
2694 avio_wb16(pb, 0); // empty
2695 avio_wb16(pb, track); // track / disc number
2696 avio_wb16(pb, tracks); // total track / disc number
2697 avio_wb16(pb, 0); // empty
2703 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2704 const char *name, const char *tag,
2707 AVDictionaryEntry *t = NULL;
2709 int size = 24 + len;
2711 if (len != 1 && len != 4)
2714 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2716 num = atoi(t->value);
2718 avio_wb32(pb, size);
2719 ffio_wfourcc(pb, name);
2720 avio_wb32(pb, size - 8);
2721 ffio_wfourcc(pb, "data");
2722 avio_wb32(pb, 0x15);
2724 if (len==4) avio_wb32(pb, num);
2725 else avio_w8 (pb, num);
2730 /* iTunes meta data list */
2731 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2734 int64_t pos = avio_tell(pb);
2735 avio_wb32(pb, 0); /* size */
2736 ffio_wfourcc(pb, "ilst");
2737 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
2738 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
2739 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2740 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2741 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
2742 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
2744 !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2745 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2746 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
2747 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
2748 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2749 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2750 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
2751 mov_write_string_metadata(s, pb, "desc", "description",1);
2752 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
2753 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
2754 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
2755 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
2756 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
2757 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
2758 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
2759 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
2760 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
2761 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
2762 mov_write_trkn_tag(pb, mov, s, 0); // track number
2763 mov_write_trkn_tag(pb, mov, s, 1); // disc number
2764 mov_write_tmpo_tag(pb, s);
2765 return update_size(pb, pos);
2768 /* iTunes meta data tag */
2769 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2773 int64_t pos = avio_tell(pb);
2774 avio_wb32(pb, 0); /* size */
2775 ffio_wfourcc(pb, "meta");
2777 mov_write_itunes_hdlr_tag(pb, mov, s);
2778 mov_write_ilst_tag(pb, mov, s);
2779 size = update_size(pb, pos);
2783 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
2784 const char *name, const char *key)
2787 AVDictionaryEntry *t;
2789 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
2792 len = strlen(t->value);
2795 avio_wb32(pb, size);
2796 ffio_wfourcc(pb, name);
2797 avio_write(pb, t->value, len);
2803 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2807 GET_UTF8(val, *b++, return -1;)
2810 avio_wb16(pb, 0x00);
2814 static uint16_t language_code(const char *str)
2816 return (((str[0] - 0x60) & 0x1F) << 10) +
2817 (((str[1] - 0x60) & 0x1F) << 5) +
2818 (( str[2] - 0x60) & 0x1F);
2821 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2822 const char *tag, const char *str)
2824 int64_t pos = avio_tell(pb);
2825 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2826 if (!t || !utf8len(t->value))
2828 avio_wb32(pb, 0); /* size */
2829 ffio_wfourcc(pb, tag); /* type */
2830 avio_wb32(pb, 0); /* version + flags */
2831 if (!strcmp(tag, "yrrc"))
2832 avio_wb16(pb, atoi(t->value));
2834 avio_wb16(pb, language_code("eng")); /* language */
2835 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2836 if (!strcmp(tag, "albm") &&
2837 (t = av_dict_get(s->metadata, "track", NULL, 0)))
2838 avio_w8(pb, atoi(t->value));
2840 return update_size(pb, pos);
2843 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2845 int64_t pos = avio_tell(pb);
2846 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2848 avio_wb32(pb, 0); // size
2849 ffio_wfourcc(pb, "chpl");
2850 avio_wb32(pb, 0x01000000); // version + flags
2851 avio_wb32(pb, 0); // unknown
2852 avio_w8(pb, nb_chapters);
2854 for (i = 0; i < nb_chapters; i++) {
2855 AVChapter *c = s->chapters[i];
2856 AVDictionaryEntry *t;
2857 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2859 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2860 int len = FFMIN(strlen(t->value), 255);
2862 avio_write(pb, t->value, len);
2866 return update_size(pb, pos);
2869 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2872 AVIOContext *pb_buf;
2876 ret = avio_open_dyn_buf(&pb_buf);
2880 if (mov->mode & MODE_3GP) {
2881 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2882 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2883 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2884 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2885 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2886 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2887 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2888 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2889 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2890 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
2891 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
2892 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
2893 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
2894 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
2895 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
2896 // currently ignored by mov.c
2897 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
2898 // add support for libquicktime, this atom is also actually read by mov.c
2899 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
2900 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
2901 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
2902 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
2904 /* iTunes meta data */
2905 mov_write_meta_tag(pb_buf, mov, s);
2908 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
2909 mov_write_chpl_tag(pb_buf, s);
2911 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2912 avio_wb32(pb, size + 8);
2913 ffio_wfourcc(pb, "udta");
2914 avio_write(pb, buf, size);
2921 static void mov_write_psp_udta_tag(AVIOContext *pb,
2922 const char *str, const char *lang, int type)
2924 int len = utf8len(str) + 1;
2927 avio_wb16(pb, len * 2 + 10); /* size */
2928 avio_wb32(pb, type); /* type */
2929 avio_wb16(pb, language_code(lang)); /* language */
2930 avio_wb16(pb, 0x01); /* ? */
2931 ascii_to_wc(pb, str);
2934 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2936 MOVMuxContext *mov = s->priv_data;
2937 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2941 pos = avio_tell(pb);
2942 avio_wb32(pb, 0); /* size placeholder*/
2943 ffio_wfourcc(pb, "uuid");
2944 ffio_wfourcc(pb, "USMT");
2945 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2946 avio_wb32(pb, 0xbb88695c);
2947 avio_wb32(pb, 0xfac9c740);
2949 pos2 = avio_tell(pb);
2950 avio_wb32(pb, 0); /* size placeholder*/
2951 ffio_wfourcc(pb, "MTDT");
2955 avio_wb16(pb, 0x0C); /* size */
2956 avio_wb32(pb, 0x0B); /* type */
2957 avio_wb16(pb, language_code("und")); /* language */
2958 avio_wb16(pb, 0x0); /* ? */
2959 avio_wb16(pb, 0x021C); /* data */
2962 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
2963 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
2964 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2966 update_size(pb, pos2);
2967 return update_size(pb, pos);
2973 static void build_chunks(MOVTrack *trk)
2976 MOVIentry *chunk = &trk->cluster[0];
2977 uint64_t chunkSize = chunk->size;
2978 chunk->chunkNum = 1;
2979 if (trk->chunkCount)
2981 trk->chunkCount = 1;
2982 for (i = 1; i<trk->entry; i++){
2983 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
2984 chunkSize + trk->cluster[i].size < (1<<20)){
2985 chunkSize += trk->cluster[i].size;
2986 chunk->samples_in_chunk += trk->cluster[i].entries;
2988 trk->cluster[i].chunkNum = chunk->chunkNum+1;
2989 chunk=&trk->cluster[i];
2990 chunkSize = chunk->size;
2996 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3000 int64_t pos = avio_tell(pb);
3001 avio_wb32(pb, 0); /* size placeholder*/
3002 ffio_wfourcc(pb, "moov");
3004 for (i = 0; i < mov->nb_streams; i++) {
3005 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3008 mov->tracks[i].time = mov->time;
3009 mov->tracks[i].track_id = i + 1;
3011 if (mov->tracks[i].entry)
3012 build_chunks(&mov->tracks[i]);
3015 if (mov->chapter_track)
3016 for (i = 0; i < s->nb_streams; i++) {
3017 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3018 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3020 for (i = 0; i < mov->nb_streams; i++) {
3021 if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
3022 mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
3023 mov->tracks[i].tref_id =
3024 mov->tracks[mov->tracks[i].src_track].track_id;
3027 for (i = 0; i < mov->nb_streams; i++) {
3028 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3029 int src_trk = mov->tracks[i].src_track;
3030 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3031 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3032 //src_trk may have a different timescale than the tmcd track
3033 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3034 mov->tracks[i].timescale,
3035 mov->tracks[src_trk].timescale);
3039 mov_write_mvhd_tag(pb, mov);
3040 if (mov->mode != MODE_MOV && !mov->iods_skip)
3041 mov_write_iods_tag(pb, mov);
3042 for (i = 0; i < mov->nb_streams; i++) {
3043 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3044 mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3047 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3048 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3050 if (mov->mode == MODE_PSP)
3051 mov_write_uuidusmt_tag(pb, s);
3053 mov_write_udta_tag(pb, mov, s);
3055 return update_size(pb, pos);
3058 static void param_write_int(AVIOContext *pb, const char *name, int value)
3060 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3063 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3065 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3068 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3071 len = FFMIN(sizeof(buf) / 2 - 1, len);
3072 ff_data_to_hex(buf, value, len, 0);
3073 buf[2 * len] = '\0';
3074 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3077 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
3079 int64_t pos = avio_tell(pb);
3081 static const uint8_t uuid[] = {
3082 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3083 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3087 ffio_wfourcc(pb, "uuid");
3088 avio_write(pb, uuid, sizeof(uuid));
3091 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3092 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3093 avio_printf(pb, "<head>\n");
3095 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3097 avio_printf(pb, "</head>\n");
3098 avio_printf(pb, "<body>\n");
3099 avio_printf(pb, "<switch>\n");
3100 for (i = 0; i < mov->nb_streams; i++) {
3101 MOVTrack *track = &mov->tracks[i];
3103 /* track->track_id is initialized in write_moov, and thus isn't known
3105 int track_id = i + 1;
3107 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3109 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
3114 avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
3115 track->enc->bit_rate);
3116 param_write_int(pb, "systemBitrate", track->enc->bit_rate);
3117 param_write_int(pb, "trackID", track_id);
3118 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3119 if (track->enc->codec_id == AV_CODEC_ID_H264) {
3121 int size = track->enc->extradata_size;
3122 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
3124 param_write_hex(pb, "CodecPrivateData",
3125 ptr ? ptr : track->enc->extradata,
3129 param_write_string(pb, "FourCC", "H264");
3130 } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
3131 param_write_string(pb, "FourCC", "WVC1");
3132 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3133 track->enc->extradata_size);
3135 param_write_int(pb, "MaxWidth", track->enc->width);
3136 param_write_int(pb, "MaxHeight", track->enc->height);
3137 param_write_int(pb, "DisplayWidth", track->enc->width);
3138 param_write_int(pb, "DisplayHeight", track->enc->height);
3140 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
3141 param_write_string(pb, "FourCC", "AACL");
3142 } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
3143 param_write_string(pb, "FourCC", "WMAP");
3145 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3146 track->enc->extradata_size);
3147 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3148 track->enc->codec_id));
3149 param_write_int(pb, "Channels", track->enc->channels);
3150 param_write_int(pb, "SamplingRate", track->enc->sample_rate);
3151 param_write_int(pb, "BitsPerSample", 16);
3152 param_write_int(pb, "PacketSize", track->enc->block_align ?
3153 track->enc->block_align : 4);
3155 avio_printf(pb, "</%s>\n", type);
3157 avio_printf(pb, "</switch>\n");
3158 avio_printf(pb, "</body>\n");
3159 avio_printf(pb, "</smil>\n");
3161 return update_size(pb, pos);
3164 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3167 ffio_wfourcc(pb, "mfhd");
3169 avio_wb32(pb, mov->fragments);
3173 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3174 MOVTrack *track, int64_t moof_offset)
3176 int64_t pos = avio_tell(pb);
3177 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3178 MOV_TFHD_BASE_DATA_OFFSET;
3179 if (!track->entry) {
3180 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3182 flags |= MOV_TFHD_DEFAULT_FLAGS;
3184 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3185 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3186 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3187 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3188 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3191 /* Don't set a default sample size, the silverlight player refuses
3192 * to play files with that set. Don't set a default sample duration,
3193 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3194 * file format says it MUST NOT be set. */
3195 if (track->mode == MODE_ISM)
3196 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3197 MOV_TFHD_BASE_DATA_OFFSET);
3199 avio_wb32(pb, 0); /* size placeholder */
3200 ffio_wfourcc(pb, "tfhd");
3201 avio_w8(pb, 0); /* version */
3202 avio_wb24(pb, flags);
3204 avio_wb32(pb, track->track_id); /* track-id */
3205 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3206 avio_wb64(pb, moof_offset);
3207 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3208 track->default_duration = get_cluster_duration(track, 0);
3209 avio_wb32(pb, track->default_duration);
3211 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3212 track->default_size = track->entry ? track->cluster[0].size : 1;
3213 avio_wb32(pb, track->default_size);
3215 track->default_size = -1;
3217 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3218 track->default_sample_flags =
3219 track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
3220 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3221 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3222 avio_wb32(pb, track->default_sample_flags);
3225 return update_size(pb, pos);
3228 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3230 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3231 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3234 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3235 MOVTrack *track, int moof_size)
3237 int64_t pos = avio_tell(pb);
3238 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3241 for (i = 0; i < track->entry; i++) {
3242 if (get_cluster_duration(track, i) != track->default_duration)
3243 flags |= MOV_TRUN_SAMPLE_DURATION;
3244 if (track->cluster[i].size != track->default_size)
3245 flags |= MOV_TRUN_SAMPLE_SIZE;
3246 if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3247 flags |= MOV_TRUN_SAMPLE_FLAGS;
3249 if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
3250 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3251 if (track->flags & MOV_TRACK_CTTS)
3252 flags |= MOV_TRUN_SAMPLE_CTS;
3254 avio_wb32(pb, 0); /* size placeholder */
3255 ffio_wfourcc(pb, "trun");
3256 avio_w8(pb, 0); /* version */
3257 avio_wb24(pb, flags);
3259 avio_wb32(pb, track->entry); /* sample count */
3260 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3261 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3263 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3265 avio_wb32(pb, moof_size + 8 + track->data_offset +
3266 track->cluster[0].pos); /* data offset */
3267 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3268 avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
3270 for (i = 0; i < track->entry; i++) {
3271 if (flags & MOV_TRUN_SAMPLE_DURATION)
3272 avio_wb32(pb, get_cluster_duration(track, i));
3273 if (flags & MOV_TRUN_SAMPLE_SIZE)
3274 avio_wb32(pb, track->cluster[i].size);
3275 if (flags & MOV_TRUN_SAMPLE_FLAGS)
3276 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3277 if (flags & MOV_TRUN_SAMPLE_CTS)
3278 avio_wb32(pb, track->cluster[i].cts);
3281 mov->first_trun = 0;
3282 return update_size(pb, pos);
3285 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3287 int64_t pos = avio_tell(pb);
3288 static const uint8_t uuid[] = {
3289 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3290 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3293 avio_wb32(pb, 0); /* size placeholder */
3294 ffio_wfourcc(pb, "uuid");
3295 avio_write(pb, uuid, sizeof(uuid));
3298 avio_wb64(pb, track->frag_start);
3299 avio_wb64(pb, track->start_dts + track->track_duration -
3300 track->cluster[0].dts);
3302 return update_size(pb, pos);
3305 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3306 MOVTrack *track, int entry)
3308 int n = track->nb_frag_info - 1 - entry, i;
3309 int size = 8 + 16 + 4 + 1 + 16*n;
3310 static const uint8_t uuid[] = {
3311 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3312 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3318 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3319 avio_wb32(pb, size);
3320 ffio_wfourcc(pb, "uuid");
3321 avio_write(pb, uuid, sizeof(uuid));
3325 for (i = 0; i < n; i++) {
3326 int index = entry + 1 + i;
3327 avio_wb64(pb, track->frag_info[index].time);
3328 avio_wb64(pb, track->frag_info[index].duration);
3330 if (n < mov->ism_lookahead) {
3331 int free_size = 16 * (mov->ism_lookahead - n);
3332 avio_wb32(pb, free_size);
3333 ffio_wfourcc(pb, "free");
3334 ffio_fill(pb, 0, free_size - 8);
3340 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3343 int64_t pos = avio_tell(pb);
3345 for (i = 0; i < mov->ism_lookahead; i++) {
3346 /* Update the tfrf tag for the last ism_lookahead fragments,
3347 * nb_frag_info - 1 is the next fragment to be written. */
3348 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3350 avio_seek(pb, pos, SEEK_SET);
3354 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3358 for (i = 0; i < mov->nb_streams; i++) {
3359 MOVTrack *track = &mov->tracks[i];
3360 MOVFragmentInfo *info;
3361 if ((tracks >= 0 && i != tracks) || !track->entry)
3363 track->nb_frag_info++;
3364 if (track->nb_frag_info >= track->frag_info_capacity) {
3365 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3366 if (av_reallocp_array(&track->frag_info,
3368 sizeof(*track->frag_info)))
3369 return AVERROR(ENOMEM);
3370 track->frag_info_capacity = new_capacity;
3372 info = &track->frag_info[track->nb_frag_info - 1];
3373 info->offset = avio_tell(pb);
3375 // Try to recreate the original pts for the first packet
3376 // from the fields we have stored
3377 info->time = track->start_dts + track->frag_start +
3378 track->cluster[0].cts;
3379 // If the pts is less than zero, we will have trimmed
3380 // away parts of the media track using an edit list,
3381 // and the corresponding start presentation time is zero.
3384 info->duration = track->start_dts + track->track_duration -
3385 track->cluster[0].dts;
3386 info->tfrf_offset = 0;
3387 mov_write_tfrf_tags(pb, mov, track);
3392 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3394 int64_t pos = avio_tell(pb);
3396 avio_wb32(pb, 0); /* size */
3397 ffio_wfourcc(pb, "tfdt");
3398 avio_w8(pb, 1); /* version */
3400 avio_wb64(pb, track->frag_start);
3401 return update_size(pb, pos);
3404 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3405 MOVTrack *track, int64_t moof_offset,
3408 int64_t pos = avio_tell(pb);
3409 avio_wb32(pb, 0); /* size placeholder */
3410 ffio_wfourcc(pb, "traf");
3412 mov_write_tfhd_tag(pb, mov, track, moof_offset);
3413 if (mov->mode != MODE_ISM)
3414 mov_write_tfdt_tag(pb, track);
3415 mov_write_trun_tag(pb, mov, track, moof_size);
3416 if (mov->mode == MODE_ISM) {
3417 mov_write_tfxd_tag(pb, track);
3419 if (mov->ism_lookahead) {
3420 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3422 if (track->nb_frag_info > 0) {
3423 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3424 if (!info->tfrf_offset)
3425 info->tfrf_offset = avio_tell(pb);
3427 avio_wb32(pb, 8 + size);
3428 ffio_wfourcc(pb, "free");
3429 for (i = 0; i < size; i++)
3434 return update_size(pb, pos);
3437 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3438 int tracks, int moof_size)
3440 int64_t pos = avio_tell(pb);
3443 avio_wb32(pb, 0); /* size placeholder */
3444 ffio_wfourcc(pb, "moof");
3445 mov->first_trun = 1;
3447 mov_write_mfhd_tag(pb, mov);
3448 for (i = 0; i < mov->nb_streams; i++) {
3449 MOVTrack *track = &mov->tracks[i];
3450 if (tracks >= 0 && i != tracks)
3454 mov_write_traf_tag(pb, mov, track, pos, moof_size);
3457 return update_size(pb, pos);
3460 static int mov_write_sidx_tag(AVIOContext *pb,
3461 MOVTrack *track, int ref_size, int total_sidx_size)
3463 int64_t pos = avio_tell(pb), offset_pos, end_pos;
3464 int64_t presentation_time, duration, offset;
3465 int starts_with_SAP, i, entries;
3469 presentation_time = track->start_dts + track->frag_start +
3470 track->cluster[0].cts;
3471 duration = track->start_dts + track->track_duration -
3472 track->cluster[0].dts;
3473 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
3475 entries = track->nb_frag_info;
3476 presentation_time = track->frag_info[0].time;
3479 // pts<0 should be cut away using edts
3480 if (presentation_time < 0)
3481 presentation_time = 0;
3483 avio_wb32(pb, 0); /* size */
3484 ffio_wfourcc(pb, "sidx");
3485 avio_w8(pb, 1); /* version */
3487 avio_wb32(pb, track->track_id); /* reference_ID */
3488 avio_wb32(pb, track->timescale); /* timescale */
3489 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
3490 offset_pos = avio_tell(pb);
3491 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
3492 avio_wb16(pb, 0); /* reserved */
3494 avio_wb16(pb, entries); /* reference_count */
3495 for (i = 0; i < entries; i++) {
3496 if (!track->entry) {
3497 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
3498 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
3500 duration = track->frag_info[i].duration;
3501 ref_size = track->frag_info[i].size;
3502 starts_with_SAP = 1;
3504 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
3505 avio_wb32(pb, duration); /* subsegment_duration */
3506 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
3509 end_pos = avio_tell(pb);
3510 offset = pos + total_sidx_size - end_pos;
3511 avio_seek(pb, offset_pos, SEEK_SET);
3512 avio_wb64(pb, offset);
3513 avio_seek(pb, end_pos, SEEK_SET);
3514 return update_size(pb, pos);
3517 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
3518 int tracks, int ref_size)
3521 AVIOContext *avio_buf;
3523 for (round = 0; round < 2; round++) {
3524 // First run one round to calculate the total size of all
3526 // This would be much simpler if we'd only write one sidx
3527 // atom, for the first track in the moof.
3529 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3534 for (i = 0; i < mov->nb_streams; i++) {
3535 MOVTrack *track = &mov->tracks[i];
3536 if (tracks >= 0 && i != tracks)
3538 // When writing a sidx for the full file, entry is 0, but
3539 // we want to include all tracks. ref_size is 0 in this case,
3540 // since we read it from frag_info instead.
3541 if (!track->entry && ref_size > 0)
3543 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
3547 total_size = ffio_close_null_buf(avio_buf);
3552 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3555 AVIOContext *avio_buf;
3558 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3560 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
3561 moof_size = ffio_close_null_buf(avio_buf);
3563 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_FASTSTART))
3564 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
3566 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
3569 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
3572 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
3574 int64_t pos = avio_tell(pb);
3577 avio_wb32(pb, 0); /* size placeholder */
3578 ffio_wfourcc(pb, "tfra");
3579 avio_w8(pb, 1); /* version */
3582 avio_wb32(pb, track->track_id);
3583 avio_wb32(pb, 0); /* length of traf/trun/sample num */
3584 avio_wb32(pb, track->nb_frag_info);
3585 for (i = 0; i < track->nb_frag_info; i++) {
3586 avio_wb64(pb, track->frag_info[i].time);
3587 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
3588 avio_w8(pb, 1); /* traf number */
3589 avio_w8(pb, 1); /* trun number */
3590 avio_w8(pb, 1); /* sample number */
3593 return update_size(pb, pos);
3596 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
3598 int64_t pos = avio_tell(pb);
3601 avio_wb32(pb, 0); /* size placeholder */
3602 ffio_wfourcc(pb, "mfra");
3603 /* An empty mfra atom is enough to indicate to the publishing point that
3604 * the stream has ended. */
3605 if (mov->flags & FF_MOV_FLAG_ISML)
3606 return update_size(pb, pos);
3608 for (i = 0; i < mov->nb_streams; i++) {
3609 MOVTrack *track = &mov->tracks[i];
3610 if (track->nb_frag_info)
3611 mov_write_tfra_tag(pb, track);
3615 ffio_wfourcc(pb, "mfro");
3616 avio_wb32(pb, 0); /* version + flags */
3617 avio_wb32(pb, avio_tell(pb) + 4 - pos);
3619 return update_size(pb, pos);
3622 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
3624 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
3625 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
3627 mov->mdat_pos = avio_tell(pb);
3628 avio_wb32(pb, 0); /* size placeholder*/
3629 ffio_wfourcc(pb, "mdat");
3633 /* TODO: This needs to be more general */
3634 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
3636 MOVMuxContext *mov = s->priv_data;
3637 int64_t pos = avio_tell(pb);
3638 int has_h264 = 0, has_video = 0;
3642 for (i = 0; i < s->nb_streams; i++) {
3643 AVStream *st = s->streams[i];
3644 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3646 if (st->codec->codec_id == AV_CODEC_ID_H264)
3650 avio_wb32(pb, 0); /* size */
3651 ffio_wfourcc(pb, "ftyp");
3653 if (mov->major_brand && strlen(mov->major_brand) >= 4)
3654 ffio_wfourcc(pb, mov->major_brand);
3655 else if (mov->mode == MODE_3GP) {
3656 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
3657 minor = has_h264 ? 0x100 : 0x200;
3658 } else if (mov->mode & MODE_3G2) {
3659 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
3660 minor = has_h264 ? 0x20000 : 0x10000;
3661 } else if (mov->mode == MODE_PSP)
3662 ffio_wfourcc(pb, "MSNV");
3663 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
3664 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
3665 else if (mov->mode == MODE_MP4)
3666 ffio_wfourcc(pb, "isom");
3667 else if (mov->mode == MODE_IPOD)
3668 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3669 else if (mov->mode == MODE_ISM)
3670 ffio_wfourcc(pb, "isml");
3671 else if (mov->mode == MODE_F4V)
3672 ffio_wfourcc(pb, "f4v ");
3674 ffio_wfourcc(pb, "qt ");
3676 avio_wb32(pb, minor);
3678 if (mov->mode == MODE_MOV)
3679 ffio_wfourcc(pb, "qt ");
3680 else if (mov->mode == MODE_ISM) {
3681 ffio_wfourcc(pb, "piff");
3682 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
3683 ffio_wfourcc(pb, "isom");
3684 ffio_wfourcc(pb, "iso2");
3686 ffio_wfourcc(pb, "avc1");
3689 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
3690 // brand. This is compatible with users that don't understand tfdt.
3691 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
3692 ffio_wfourcc(pb, "iso6");
3694 if (mov->mode == MODE_3GP)
3695 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3696 else if (mov->mode & MODE_3G2)
3697 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3698 else if (mov->mode == MODE_PSP)
3699 ffio_wfourcc(pb, "MSNV");
3700 else if (mov->mode == MODE_MP4)
3701 ffio_wfourcc(pb, "mp41");
3703 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_FASTSTART)
3704 ffio_wfourcc(pb, "dash");
3706 return update_size(pb, pos);
3709 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3711 AVStream *video_st = s->streams[0];
3712 AVCodecContext *video_codec = s->streams[0]->codec;
3713 AVCodecContext *audio_codec = s->streams[1]->codec;
3714 int audio_rate = audio_codec->sample_rate;
3715 // TODO: should be avg_frame_rate
3716 int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
3717 int audio_kbitrate = audio_codec->bit_rate / 1000;
3718 int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3720 avio_wb32(pb, 0x94); /* size */
3721 ffio_wfourcc(pb, "uuid");
3722 ffio_wfourcc(pb, "PROF");
3724 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3725 avio_wb32(pb, 0xbb88695c);
3726 avio_wb32(pb, 0xfac9c740);
3728 avio_wb32(pb, 0x0); /* ? */
3729 avio_wb32(pb, 0x3); /* 3 sections ? */
3731 avio_wb32(pb, 0x14); /* size */
3732 ffio_wfourcc(pb, "FPRF");
3733 avio_wb32(pb, 0x0); /* ? */
3734 avio_wb32(pb, 0x0); /* ? */
3735 avio_wb32(pb, 0x0); /* ? */
3737 avio_wb32(pb, 0x2c); /* size */
3738 ffio_wfourcc(pb, "APRF"); /* audio */
3740 avio_wb32(pb, 0x2); /* TrackID */
3741 ffio_wfourcc(pb, "mp4a");
3742 avio_wb32(pb, 0x20f);
3744 avio_wb32(pb, audio_kbitrate);
3745 avio_wb32(pb, audio_kbitrate);
3746 avio_wb32(pb, audio_rate);
3747 avio_wb32(pb, audio_codec->channels);
3749 avio_wb32(pb, 0x34); /* size */
3750 ffio_wfourcc(pb, "VPRF"); /* video */
3752 avio_wb32(pb, 0x1); /* TrackID */
3753 if (video_codec->codec_id == AV_CODEC_ID_H264) {
3754 ffio_wfourcc(pb, "avc1");
3755 avio_wb16(pb, 0x014D);
3756 avio_wb16(pb, 0x0015);
3758 ffio_wfourcc(pb, "mp4v");
3759 avio_wb16(pb, 0x0000);
3760 avio_wb16(pb, 0x0103);
3763 avio_wb32(pb, video_kbitrate);
3764 avio_wb32(pb, video_kbitrate);
3765 avio_wb32(pb, frame_rate);
3766 avio_wb32(pb, frame_rate);
3767 avio_wb16(pb, video_codec->width);
3768 avio_wb16(pb, video_codec->height);
3769 avio_wb32(pb, 0x010001); /* ? */
3772 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
3774 MOVMuxContext *mov = s->priv_data;
3777 mov_write_ftyp_tag(pb,s);
3778 if (mov->mode == MODE_PSP) {
3779 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
3780 for (i = 0; i < s->nb_streams; i++) {
3781 AVStream *st = s->streams[i];
3782 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3784 else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3790 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
3791 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3792 return AVERROR(EINVAL);
3794 mov_write_uuidprof_tag(pb, s);
3799 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3802 int i, closed_gop = 0;
3804 for (i = 0; i < pkt->size - 4; i++) {
3805 c = (c << 8) + pkt->data[i];
3806 if (c == 0x1b8) { // gop
3807 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
3808 } else if (c == 0x100) { // pic
3809 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
3810 if (!temp_ref || closed_gop) // I picture is not reordered
3811 *flags = MOV_SYNC_SAMPLE;
3813 *flags = MOV_PARTIAL_SYNC_SAMPLE;
3820 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
3822 const uint8_t *start, *next, *end = pkt->data + pkt->size;
3823 int seq = 0, entry = 0;
3824 int key = pkt->flags & AV_PKT_FLAG_KEY;
3825 start = find_next_marker(pkt->data, end);
3826 for (next = start; next < end; start = next) {
3827 next = find_next_marker(start + 4, end);
3828 switch (AV_RB32(start)) {
3829 case VC1_CODE_SEQHDR:
3832 case VC1_CODE_ENTRYPOINT:
3835 case VC1_CODE_SLICE:
3836 trk->vc1_info.slices = 1;
3840 if (!trk->entry && !fragment) {
3841 /* First packet in first fragment */
3842 trk->vc1_info.first_packet_seq = seq;
3843 trk->vc1_info.first_packet_entry = entry;
3844 } else if ((seq && !trk->vc1_info.packet_seq) ||
3845 (entry && !trk->vc1_info.packet_entry)) {
3847 for (i = 0; i < trk->entry; i++)
3848 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
3849 trk->has_keyframes = 0;
3851 trk->vc1_info.packet_seq = 1;
3853 trk->vc1_info.packet_entry = 1;
3855 /* First fragment */
3856 if ((!seq || trk->vc1_info.first_packet_seq) &&
3857 (!entry || trk->vc1_info.first_packet_entry)) {
3858 /* First packet had the same headers as this one, readd the
3859 * sync sample flag. */
3860 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
3861 trk->has_keyframes = 1;
3865 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
3867 else if (trk->vc1_info.packet_seq)
3869 else if (trk->vc1_info.packet_entry)
3872 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
3873 trk->has_keyframes++;
3877 static int mov_flush_fragment(AVFormatContext *s)
3879 MOVMuxContext *mov = s->priv_data;
3880 int i, first_track = -1;
3881 int64_t mdat_size = 0;
3883 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3886 if (mov->fragments == 0) {
3887 int64_t pos = avio_tell(s->pb);
3889 int buf_size, moov_size;
3891 for (i = 0; i < mov->nb_streams; i++)
3892 if (!mov->tracks[i].entry)
3894 /* Don't write the initial moov unless all tracks have data */
3895 if (i < mov->nb_streams)
3898 moov_size = get_moov_size(s);
3899 for (i = 0; i < mov->nb_streams; i++)
3900 mov->tracks[i].data_offset = pos + moov_size + 8;
3902 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
3903 mov_write_identification(s->pb, s);
3904 mov_write_moov_tag(s->pb, mov, s);
3906 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
3907 if (mov->flags & FF_MOV_FLAG_FASTSTART)
3908 mov->reserved_moov_pos = avio_tell(s->pb);
3914 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
3915 mov->mdat_buf = NULL;
3916 avio_wb32(s->pb, buf_size + 8);
3917 ffio_wfourcc(s->pb, "mdat");
3918 avio_write(s->pb, buf, buf_size);
3923 for (i = 0; i < mov->nb_streams; i++) {
3924 if (mov->tracks[i].entry)
3925 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
3926 mov->tracks[i].track_duration -
3927 mov->tracks[i].cluster[0].dts;
3928 mov->tracks[i].entry = 0;
3934 for (i = 0; i < mov->nb_streams; i++) {
3935 MOVTrack *track = &mov->tracks[i];
3936 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
3937 track->data_offset = 0;
3939 track->data_offset = mdat_size;
3940 if (!track->mdat_buf)
3942 mdat_size += avio_tell(track->mdat_buf);
3943 if (first_track < 0)
3950 for (i = 0; i < mov->nb_streams; i++) {
3951 MOVTrack *track = &mov->tracks[i];
3952 int buf_size, write_moof = 1, moof_tracks = -1;
3954 int64_t duration = 0;
3957 duration = track->start_dts + track->track_duration -
3958 track->cluster[0].dts;
3959 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
3960 if (!track->mdat_buf)
3962 mdat_size = avio_tell(track->mdat_buf);
3965 write_moof = i == first_track;
3971 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
3974 avio_wb32(s->pb, mdat_size + 8);
3975 ffio_wfourcc(s->pb, "mdat");
3979 track->frag_start += duration;
3981 if (!track->mdat_buf)
3983 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
3984 track->mdat_buf = NULL;
3986 avio_write(s->pb, buf, buf_size);
3996 static int mov_auto_flush_fragment(AVFormatContext *s)
3998 MOVMuxContext *mov = s->priv_data;
3999 int ret = mov_flush_fragment(s);
4002 // If using delay_moov, the first flush only wrote the moov,
4003 // not the actual moof+mdat pair, thus flush once again.
4004 if (mov->fragments == 1 && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4005 ret = mov_flush_fragment(s);
4009 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4011 MOVMuxContext *mov = s->priv_data;
4012 AVIOContext *pb = s->pb;
4013 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4014 AVCodecContext *enc = trk->enc;
4015 unsigned int samples_in_chunk = 0;
4016 int size = pkt->size, ret = 0;
4017 uint8_t *reformatted_data = NULL;
4020 int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
4021 if (duration < 0 || duration > INT_MAX) {
4022 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4026 pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
4027 pkt->pts = AV_NOPTS_VALUE;
4029 if (pkt->duration < 0) {
4030 av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
4031 return AVERROR(EINVAL);
4034 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4036 if (mov->fragments > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4037 if (!trk->mdat_buf) {
4038 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4043 if (!mov->mdat_buf) {
4044 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4051 if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
4052 /* We must find out how many AMR blocks there are in one packet */
4053 static uint16_t packed_size[16] =
4054 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4057 while (len < size && samples_in_chunk < 100) {
4058 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4061 if (samples_in_chunk > 1) {
4062 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4065 } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
4066 enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4067 samples_in_chunk = enc->frame_size;
4068 } else if (trk->sample_size)
4069 samples_in_chunk = size / trk->sample_size;
4071 samples_in_chunk = 1;
4073 /* copy extradata if it exists */
4074 if (trk->vos_len == 0 && enc->extradata_size > 0 && !TAG_IS_AVCI(trk->tag)) {
4075 trk->vos_len = enc->extradata_size;
4076 trk->vos_data = av_malloc(trk->vos_len);
4077 memcpy(trk->vos_data, enc->extradata, trk->vos_len);
4080 if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4081 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4082 if (!s->streams[pkt->stream_index]->nb_frames) {
4083 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4084 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4085 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4088 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4090 if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4091 /* from x264 or from bytestream h264 */
4092 /* nal reformating needed */
4093 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4094 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4096 avio_write(pb, reformatted_data, size);
4098 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4100 } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4101 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4102 /* extradata is Annex B, assume the bitstream is too and convert it */
4103 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4104 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4105 avio_write(pb, reformatted_data, size);
4107 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4109 } else if (CONFIG_AC3_PARSER && enc->codec_id == AV_CODEC_ID_EAC3) {
4110 size = handle_eac3(mov, pkt, trk);
4115 avio_write(pb, pkt->data, size);
4117 avio_write(pb, pkt->data, size);
4120 if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
4121 enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4122 /* copy frame to create needed atoms */
4123 trk->vos_len = size;
4124 trk->vos_data = av_malloc(size);
4125 if (!trk->vos_data) {
4126 ret = AVERROR(ENOMEM);
4129 memcpy(trk->vos_data, pkt->data, size);
4132 if (trk->entry >= trk->cluster_capacity) {
4133 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4134 if (av_reallocp_array(&trk->cluster, new_capacity,
4135 sizeof(*trk->cluster))) {
4136 ret = AVERROR(ENOMEM);
4139 trk->cluster_capacity = new_capacity;
4142 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
4143 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4144 trk->cluster[trk->entry].chunkNum = 0;
4145 trk->cluster[trk->entry].size = size;
4146 trk->cluster[trk->entry].entries = samples_in_chunk;
4147 trk->cluster[trk->entry].dts = pkt->dts;
4148 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4149 if (!trk->frag_discont) {
4150 /* First packet of a new fragment. We already wrote the duration
4151 * of the last packet of the previous fragment based on track_duration,
4152 * which might not exactly match our dts. Therefore adjust the dts
4153 * of this packet to be what the previous packets duration implies. */
4154 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4155 /* We also may have written the pts and the corresponding duration
4156 * in sidx tags; make sure the sidx pts and duration match up with
4157 * the next fragment. This means the cts of the first sample must
4158 * be the same in all fragments. */
4159 pkt->pts = pkt->dts + trk->start_cts;
4161 /* New fragment, but discontinuous from previous fragments.
4162 * Pretend the duration sum of the earlier fragments is
4163 * pkt->dts - trk->start_dts. */
4164 trk->frag_start = pkt->dts - trk->start_dts;
4165 trk->frag_discont = 0;
4169 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4170 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4171 /* Not using edit lists and shifting the first track to start from zero.
4172 * If the other streams start from a later timestamp, we won't be able
4173 * to signal the difference in starting time without an edit list.
4174 * Thus move the timestamp for this first sample to 0, increasing
4175 * its duration instead. */
4176 trk->cluster[trk->entry].dts = trk->start_dts = 0;
4178 if (trk->start_dts == AV_NOPTS_VALUE) {
4179 trk->start_dts = pkt->dts;
4180 if (trk->frag_discont) {
4181 /* Pretend the whole stream started at dts=0, with earlier fragments
4182 * already written, with a duration summing up to pkt->dts. */
4183 trk->frag_start = pkt->dts;
4185 trk->frag_discont = 0;
4186 } else if (pkt->dts && mov->fragments >= 1)
4187 av_log(s, AV_LOG_WARNING,
4188 "Track %d starts with a nonzero dts %"PRId64", while the moov "
4189 "already has been written. Set the delay_moov flag to handle "
4191 pkt->stream_index, pkt->dts);
4193 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4194 trk->last_sample_is_subtitle_end = 0;
4196 if (pkt->pts == AV_NOPTS_VALUE) {
4197 av_log(s, AV_LOG_WARNING, "pts has no value\n");
4198 pkt->pts = pkt->dts;
4200 if (pkt->dts != pkt->pts)
4201 trk->flags |= MOV_TRACK_CTTS;
4202 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
4203 trk->cluster[trk->entry].flags = 0;
4204 if (trk->start_cts == AV_NOPTS_VALUE)
4205 trk->start_cts = pkt->pts - pkt->dts;
4207 if (enc->codec_id == AV_CODEC_ID_VC1) {
4208 mov_parse_vc1_frame(pkt, trk, mov->fragments);
4209 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4210 if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4211 trk->entry > 0) { // force sync sample for the first key frame
4212 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4213 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4214 trk->flags |= MOV_TRACK_STPS;
4216 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
4218 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
4219 trk->has_keyframes++;
4222 trk->sample_count += samples_in_chunk;
4223 mov->mdat_size += size;
4225 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
4226 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
4227 reformatted_data, size);
4232 av_free(reformatted_data);
4236 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
4238 MOVMuxContext *mov = s->priv_data;
4239 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4240 AVCodecContext *enc = trk->enc;
4241 int64_t frag_duration = 0;
4242 int size = pkt->size;
4245 return 0; /* Discard 0 sized packets */
4247 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
4249 for (i = 0; i < s->nb_streams; i++)
4250 mov->tracks[i].frag_discont = 1;
4251 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
4254 if (trk->entry && pkt->stream_index < s->nb_streams)
4255 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
4256 s->streams[pkt->stream_index]->time_base,
4258 if ((mov->max_fragment_duration &&
4259 frag_duration >= mov->max_fragment_duration) ||
4260 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
4261 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
4262 enc->codec_type == AVMEDIA_TYPE_VIDEO &&
4263 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
4264 if (frag_duration >= mov->min_fragment_duration)
4265 mov_auto_flush_fragment(s);
4268 return ff_mov_write_packet(s, pkt);
4271 static int mov_write_subtitle_end_packet(AVFormatContext *s,
4275 uint8_t data[2] = {0};
4278 av_init_packet(&end);
4279 end.size = sizeof(data);
4284 end.stream_index = stream_index;
4286 ret = mov_write_single_packet(s, &end);
4287 av_free_packet(&end);
4292 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4295 mov_flush_fragment(s);
4299 MOVMuxContext *mov = s->priv_data;
4301 if (!pkt->size) return 0; /* Discard 0 sized packets */
4304 * Subtitles require special handling.
4306 * 1) For full complaince, every track must have a sample at
4307 * dts == 0, which is rarely true for subtitles. So, as soon
4308 * as we see any packet with dts > 0, write an empty subtitle
4309 * at dts == 0 for any subtitle track with no samples in it.
4311 * 2) For each subtitle track, check if the current packet's
4312 * dts is past the duration of the last subtitle sample. If
4313 * so, we now need to write an end sample for that subtitle.
4315 * This must be done conditionally to allow for subtitles that
4316 * immediately replace each other, in which case an end sample
4317 * is not needed, and is, in fact, actively harmful.
4319 * 3) See mov_write_trailer for how the final end sample is
4322 for (i = 0; i < mov->nb_streams; i++) {
4323 MOVTrack *trk = &mov->tracks[i];
4326 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4327 trk->track_duration < pkt->dts &&
4328 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
4329 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
4330 if (ret < 0) return ret;
4331 trk->last_sample_is_subtitle_end = 1;
4335 return mov_write_single_packet(s, pkt);
4339 // QuickTime chapters involve an additional text track with the chapter names
4340 // as samples, and a tref pointing from the other tracks to the chapter one.
4341 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
4345 MOVMuxContext *mov = s->priv_data;
4346 MOVTrack *track = &mov->tracks[tracknum];
4347 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
4350 track->mode = mov->mode;
4351 track->tag = MKTAG('t','e','x','t');
4352 track->timescale = MOV_TIMESCALE;
4353 track->enc = avcodec_alloc_context3(NULL);
4355 return AVERROR(ENOMEM);
4356 track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4358 // These properties are required to make QT recognize the chapter track
4359 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
4360 if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
4361 return AVERROR(ENOMEM);
4362 memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
4364 if (avio_open_dyn_buf(&pb) >= 0) {
4368 /* Stub header (usually for Quicktime chapter track) */
4370 avio_wb32(pb, 0x01); // displayFlags
4371 avio_w8(pb, 0x00); // horizontal justification
4372 avio_w8(pb, 0x00); // vertical justification
4373 avio_w8(pb, 0x00); // bgColourRed
4374 avio_w8(pb, 0x00); // bgColourGreen
4375 avio_w8(pb, 0x00); // bgColourBlue
4376 avio_w8(pb, 0x00); // bgColourAlpha
4378 avio_wb16(pb, 0x00); // defTextBoxTop
4379 avio_wb16(pb, 0x00); // defTextBoxLeft
4380 avio_wb16(pb, 0x00); // defTextBoxBottom
4381 avio_wb16(pb, 0x00); // defTextBoxRight
4383 avio_wb16(pb, 0x00); // startChar
4384 avio_wb16(pb, 0x00); // endChar
4385 avio_wb16(pb, 0x01); // fontID
4386 avio_w8(pb, 0x00); // fontStyleFlags
4387 avio_w8(pb, 0x00); // fontSize
4388 avio_w8(pb, 0x00); // fgColourRed
4389 avio_w8(pb, 0x00); // fgColourGreen
4390 avio_w8(pb, 0x00); // fgColourBlue
4391 avio_w8(pb, 0x00); // fgColourAlpha
4393 avio_wb32(pb, 0x0D); // box size
4394 ffio_wfourcc(pb, "ftab"); // box atom name
4395 avio_wb16(pb, 0x01); // entry count
4397 avio_wb16(pb, 0x01); // font ID
4398 avio_w8(pb, 0x00); // font name length
4400 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
4401 track->enc->extradata = buf;
4402 track->enc->extradata_size = size;
4409 for (i = 0; i < s->nb_chapters; i++) {
4410 AVChapter *c = s->chapters[i];
4411 AVDictionaryEntry *t;
4413 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
4414 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
4415 pkt.duration = end - pkt.dts;
4417 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
4418 const char encd[12] = {
4419 0x00, 0x00, 0x00, 0x0C,
4421 0x00, 0x00, 0x01, 0x00 };
4422 len = strlen(t->value);
4423 pkt.size = len + 2 + 12;
4424 pkt.data = av_malloc(pkt.size);
4426 return AVERROR(ENOMEM);
4427 AV_WB16(pkt.data, len);
4428 memcpy(pkt.data + 2, t->value, len);
4429 memcpy(pkt.data + len + 2, encd, sizeof(encd));
4430 ff_mov_write_packet(s, &pkt);
4431 av_freep(&pkt.data);
4438 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
4441 MOVMuxContext *mov = s->priv_data;
4442 MOVTrack *track = &mov->tracks[index];
4443 AVStream *src_st = s->streams[src_index];
4445 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
4446 AVRational rate = find_fps(s, src_st);
4448 /* compute the frame number */
4449 ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
4453 /* tmcd track based on video stream */
4454 track->mode = mov->mode;
4455 track->tag = MKTAG('t','m','c','d');
4456 track->src_track = src_index;
4457 track->timescale = mov->tracks[src_index].timescale;
4458 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
4459 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
4461 /* set st to src_st for metadata access*/
4464 /* encode context: tmcd data stream */
4465 track->enc = avcodec_alloc_context3(NULL);
4466 track->enc->codec_type = AVMEDIA_TYPE_DATA;
4467 track->enc->codec_tag = track->tag;
4468 track->enc->time_base = av_inv_q(rate);
4470 /* the tmcd track just contains one packet with the frame number */
4471 pkt.data = av_malloc(pkt.size);
4472 AV_WB32(pkt.data, tc.start);
4473 ret = ff_mov_write_packet(s, &pkt);
4479 * st->disposition controls the "enabled" flag in the tkhd tag.
4480 * QuickTime will not play a track if it is not enabled. So make sure
4481 * that one track of each type (audio, video, subtitle) is enabled.
4483 * Subtitles are special. For audio and video, setting "enabled" also
4484 * makes the track "default" (i.e. it is rendered when played). For
4485 * subtitles, an "enabled" subtitle is not rendered by default, but
4486 * if no subtitle is enabled, the subtitle menu in QuickTime will be
4489 static void enable_tracks(AVFormatContext *s)
4491 MOVMuxContext *mov = s->priv_data;
4493 int enabled[AVMEDIA_TYPE_NB];
4494 int first[AVMEDIA_TYPE_NB];
4496 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4501 for (i = 0; i < s->nb_streams; i++) {
4502 AVStream *st = s->streams[i];
4504 if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
4505 st->codec->codec_type >= AVMEDIA_TYPE_NB)
4508 if (first[st->codec->codec_type] < 0)
4509 first[st->codec->codec_type] = i;
4510 if (st->disposition & AV_DISPOSITION_DEFAULT) {
4511 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
4512 enabled[st->codec->codec_type]++;
4516 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4518 case AVMEDIA_TYPE_VIDEO:
4519 case AVMEDIA_TYPE_AUDIO:
4520 case AVMEDIA_TYPE_SUBTITLE:
4522 mov->per_stream_grouping = 1;
4523 if (!enabled[i] && first[i] >= 0)
4524 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
4530 static void mov_free(AVFormatContext *s)
4532 MOVMuxContext *mov = s->priv_data;
4535 if (mov->chapter_track) {
4536 if (mov->tracks[mov->chapter_track].enc)
4537 av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
4538 av_freep(&mov->tracks[mov->chapter_track].enc);
4541 for (i = 0; i < mov->nb_streams; i++) {
4542 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
4543 ff_mov_close_hinting(&mov->tracks[i]);
4544 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
4545 av_freep(&mov->tracks[i].enc);
4546 av_freep(&mov->tracks[i].cluster);
4547 av_freep(&mov->tracks[i].frag_info);
4549 if (mov->tracks[i].vos_len)
4550 av_freep(&mov->tracks[i].vos_data);
4553 av_freep(&mov->tracks);
4556 static uint32_t rgb_to_yuv(uint32_t rgb)
4561 r = (rgb >> 16) & 0xFF;
4562 g = (rgb >> 8) & 0xFF;
4565 y = av_clip_uint8( 16. + 0.257 * r + 0.504 * g + 0.098 * b);
4566 cb = av_clip_uint8(128. - 0.148 * r - 0.291 * g + 0.439 * b);
4567 cr = av_clip_uint8(128. + 0.439 * r - 0.368 * g - 0.071 * b);
4569 return (y << 16) | (cr << 8) | cb;
4572 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
4575 int i, width = 720, height = 480;
4576 int have_palette = 0, have_size = 0;
4577 uint32_t palette[16];
4578 char *cur = st->codec->extradata;
4580 while (cur && *cur) {
4581 if (strncmp("palette:", cur, 8) == 0) {
4583 count = sscanf(cur + 8,
4584 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4585 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4586 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4587 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
4588 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
4589 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
4590 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
4591 &palette[12], &palette[13], &palette[14], &palette[15]);
4593 for (i = 0; i < count; i++) {
4594 palette[i] = rgb_to_yuv(palette[i]);
4597 } else if (!strncmp("size:", cur, 5)) {
4598 sscanf(cur + 5, "%dx%d", &width, &height);
4601 if (have_palette && have_size)
4603 cur += strcspn(cur, "\n\r");
4604 cur += strspn(cur, "\n\r");
4607 track->vos_data = av_malloc(16*4);
4608 if (!track->vos_data)
4609 return AVERROR(ENOMEM);
4610 for (i = 0; i < 16; i++) {
4611 AV_WB32(track->vos_data + i * 4, palette[i]);
4613 track->vos_len = 16 * 4;
4615 st->codec->width = width;
4616 st->codec->height = track->height = height;
4621 static int mov_write_header(AVFormatContext *s)
4623 AVIOContext *pb = s->pb;
4624 MOVMuxContext *mov = s->priv_data;
4625 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
4626 int i, ret, hint_track = 0, tmcd_track = 0;
4630 /* Default mode == MP4 */
4631 mov->mode = MODE_MP4;
4634 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
4635 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
4636 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
4637 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
4638 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
4639 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
4640 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
4643 if (s->flags & AVFMT_FLAG_BITEXACT)
4646 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4647 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
4649 /* Set the FRAGMENT flag if any of the fragmentation methods are
4651 if (mov->max_fragment_duration || mov->max_fragment_size ||
4652 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
4653 FF_MOV_FLAG_FRAG_KEYFRAME |
4654 FF_MOV_FLAG_FRAG_CUSTOM))
4655 mov->flags |= FF_MOV_FLAG_FRAGMENT;
4657 /* Set other implicit flags immediately */
4658 if (mov->mode == MODE_ISM)
4659 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
4660 FF_MOV_FLAG_FRAGMENT;
4661 if (mov->flags & FF_MOV_FLAG_DASH)
4662 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
4663 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
4665 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4666 mov->reserved_moov_size = -1;
4669 if (mov->use_editlist < 0) {
4670 mov->use_editlist = 1;
4671 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
4672 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
4673 // If we can avoid needing an edit list by shifting the
4674 // tracks, prefer that over (trying to) write edit lists
4675 // in fragmented output.
4676 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
4677 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
4678 mov->use_editlist = 0;
4681 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
4682 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
4683 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
4685 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
4686 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
4688 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
4689 * is enabled, we don't support non-seekable output at all. */
4690 if (!s->pb->seekable &&
4691 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
4692 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
4693 return AVERROR(EINVAL);
4696 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
4697 if ((ret = mov_write_identification(pb, s)) < 0)
4701 mov->nb_streams = s->nb_streams;
4702 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
4703 mov->chapter_track = mov->nb_streams++;
4705 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4706 /* Add hint tracks for each audio and video stream */
4707 hint_track = mov->nb_streams;
4708 for (i = 0; i < s->nb_streams; i++) {
4709 AVStream *st = s->streams[i];
4710 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4711 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4717 if (mov->mode == MODE_MOV) {
4718 tmcd_track = mov->nb_streams;
4720 /* +1 tmcd track for each video stream with a timecode */
4721 for (i = 0; i < s->nb_streams; i++) {
4722 AVStream *st = s->streams[i];
4723 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4724 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
4725 mov->nb_meta_tmcd++;
4728 /* check if there is already a tmcd track to remux */
4729 if (mov->nb_meta_tmcd) {
4730 for (i = 0; i < s->nb_streams; i++) {
4731 AVStream *st = s->streams[i];
4732 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
4733 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
4734 "so timecode metadata are now ignored\n");
4735 mov->nb_meta_tmcd = 0;
4740 mov->nb_streams += mov->nb_meta_tmcd;
4743 // Reserve an extra stream for chapters for the case where chapters
4744 // are written in the trailer
4745 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
4747 return AVERROR(ENOMEM);
4749 for (i = 0; i < s->nb_streams; i++) {
4750 AVStream *st= s->streams[i];
4751 MOVTrack *track= &mov->tracks[i];
4752 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4755 track->enc = st->codec;
4756 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
4757 if (track->language < 0)
4758 track->language = 0;
4759 track->mode = mov->mode;
4760 track->tag = mov_find_codec_tag(s, track);
4762 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
4763 "codec not currently supported in container\n",
4764 avcodec_get_name(st->codec->codec_id), i);
4765 ret = AVERROR(EINVAL);
4768 /* If hinting of this track is enabled by a later hint track,
4769 * this is updated. */
4770 track->hint_track = -1;
4771 track->start_dts = AV_NOPTS_VALUE;
4772 track->start_cts = AV_NOPTS_VALUE;
4773 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4774 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
4775 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
4776 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
4777 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
4778 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
4779 ret = AVERROR(EINVAL);
4782 track->height = track->tag >> 24 == 'n' ? 486 : 576;
4784 if (mov->video_track_timescale) {
4785 track->timescale = mov->video_track_timescale;
4787 track->timescale = st->time_base.den;
4788 while(track->timescale < 10000)
4789 track->timescale *= 2;
4791 if (st->codec->width > 65535 || st->codec->height > 65535) {
4792 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
4793 ret = AVERROR(EINVAL);
4796 if (track->mode == MODE_MOV && track->timescale > 100000)
4797 av_log(s, AV_LOG_WARNING,
4798 "WARNING codec timebase is very high. If duration is too long,\n"
4799 "file may not be playable by quicktime. Specify a shorter timebase\n"
4800 "or choose different container.\n");
4801 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4802 track->timescale = st->codec->sample_rate;
4803 if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
4804 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
4805 track->audio_vbr = 1;
4806 }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
4807 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
4808 st->codec->codec_id == AV_CODEC_ID_ILBC){
4809 if (!st->codec->block_align) {
4810 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
4811 ret = AVERROR(EINVAL);
4814 track->sample_size = st->codec->block_align;
4815 }else if (st->codec->frame_size > 1){ /* assume compressed audio */
4816 track->audio_vbr = 1;
4818 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
4820 if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
4821 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
4822 track->audio_vbr = 1;
4824 if (track->mode != MODE_MOV &&
4825 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
4826 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
4827 i, track->enc->sample_rate);
4828 ret = AVERROR(EINVAL);
4831 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4832 track->timescale = st->time_base.den;
4833 } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
4834 track->timescale = st->time_base.den;
4836 track->timescale = MOV_TIMESCALE;
4839 track->height = st->codec->height;
4840 /* The ism specific timescale isn't mandatory, but is assumed by
4841 * some tools, such as mp4split. */
4842 if (mov->mode == MODE_ISM)
4843 track->timescale = 10000000;
4845 avpriv_set_pts_info(st, 64, 1, track->timescale);
4847 /* copy extradata if it exists */
4848 if (st->codec->extradata_size) {
4849 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
4850 mov_create_dvd_sub_decoder_specific_info(track, st);
4851 else if (!TAG_IS_AVCI(track->tag)){
4852 track->vos_len = st->codec->extradata_size;
4853 track->vos_data = av_malloc(track->vos_len);
4854 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
4859 for (i = 0; i < s->nb_streams; i++) {
4861 AVStream *st= s->streams[i];
4862 MOVTrack *track= &mov->tracks[i];
4864 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4865 track->enc->channel_layout != AV_CH_LAYOUT_MONO)
4868 for (j = 0; j < s->nb_streams; j++) {
4869 AVStream *stj= s->streams[j];
4870 MOVTrack *trackj= &mov->tracks[j];
4874 if (stj->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4875 trackj->enc->channel_layout != AV_CH_LAYOUT_MONO ||
4876 trackj->language != track->language ||
4877 trackj->tag != track->tag
4880 track->multichannel_as_mono++;
4887 if (mov->reserved_moov_size){
4888 mov->reserved_moov_pos= avio_tell(pb);
4889 if (mov->reserved_moov_size > 0)
4890 avio_skip(pb, mov->reserved_moov_size);
4893 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4894 /* If no fragmentation options have been set, set a default. */
4895 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
4896 FF_MOV_FLAG_FRAG_CUSTOM)) &&
4897 !mov->max_fragment_duration && !mov->max_fragment_size)
4898 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
4900 if (mov->flags & FF_MOV_FLAG_FASTSTART)
4901 mov->reserved_moov_pos = avio_tell(pb);
4902 mov_write_mdat_tag(pb, mov);
4905 if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
4906 mov->time = ff_iso8601_to_unix_time(t->value);
4908 mov->time += 0x7C25B080; // 1970 based -> 1904 based
4910 if (mov->chapter_track)
4911 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4914 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4915 /* Initialize the hint tracks for each audio and video stream */
4916 for (i = 0; i < s->nb_streams; i++) {
4917 AVStream *st = s->streams[i];
4918 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4919 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4920 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
4927 if (mov->nb_meta_tmcd) {
4928 /* Initialize the tmcd tracks */
4929 for (i = 0; i < s->nb_streams; i++) {
4930 AVStream *st = s->streams[i];
4933 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4935 t = av_dict_get(st->metadata, "timecode", NULL, 0);
4938 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
4947 if (mov->flags & FF_MOV_FLAG_ISML)
4948 mov_write_isml_manifest(pb, mov);
4950 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
4951 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
4952 mov_write_moov_tag(pb, mov, s);
4954 if (mov->flags & FF_MOV_FLAG_FASTSTART)
4955 mov->reserved_moov_pos = avio_tell(pb);
4964 static int get_moov_size(AVFormatContext *s)
4967 AVIOContext *moov_buf;
4968 MOVMuxContext *mov = s->priv_data;
4970 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
4972 mov_write_moov_tag(moov_buf, mov, s);
4973 return ffio_close_null_buf(moov_buf);
4976 static int get_sidx_size(AVFormatContext *s)
4980 MOVMuxContext *mov = s->priv_data;
4982 if ((ret = ffio_open_null_buf(&buf)) < 0)
4984 mov_write_sidx_tags(buf, mov, -1, 0);
4985 return ffio_close_null_buf(buf);
4989 * This function gets the moov size if moved to the top of the file: the chunk
4990 * offset table can switch between stco (32-bit entries) to co64 (64-bit
4991 * entries) when the moov is moved to the beginning, so the size of the moov
4992 * would change. It also updates the chunk offset tables.
4994 static int compute_moov_size(AVFormatContext *s)
4996 int i, moov_size, moov_size2;
4997 MOVMuxContext *mov = s->priv_data;
4999 moov_size = get_moov_size(s);
5003 for (i = 0; i < mov->nb_streams; i++)
5004 mov->tracks[i].data_offset += moov_size;
5006 moov_size2 = get_moov_size(s);
5010 /* if the size changed, we just switched from stco to co64 and need to
5011 * update the offsets */
5012 if (moov_size2 != moov_size)
5013 for (i = 0; i < mov->nb_streams; i++)
5014 mov->tracks[i].data_offset += moov_size2 - moov_size;
5019 static int compute_sidx_size(AVFormatContext *s)
5022 MOVMuxContext *mov = s->priv_data;
5024 sidx_size = get_sidx_size(s);
5028 for (i = 0; i < mov->nb_streams; i++)
5029 mov->tracks[i].data_offset += sidx_size;
5034 static int shift_data(AVFormatContext *s)
5036 int ret = 0, moov_size;
5037 MOVMuxContext *mov = s->priv_data;
5038 int64_t pos, pos_end = avio_tell(s->pb);
5039 uint8_t *buf, *read_buf[2];
5040 int read_buf_id = 0;
5042 AVIOContext *read_pb;
5044 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
5045 moov_size = compute_sidx_size(s);
5047 moov_size = compute_moov_size(s);
5051 buf = av_malloc(moov_size * 2);
5053 return AVERROR(ENOMEM);
5055 read_buf[1] = buf + moov_size;
5057 /* Shift the data: the AVIO context of the output can only be used for
5058 * writing, so we re-open the same output, but for reading. It also avoids
5059 * a read/seek/write/seek back and forth. */
5061 ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
5063 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
5064 "the second pass (faststart)\n", s->filename);
5068 /* mark the end of the shift to up to the last data we wrote, and get ready
5070 pos_end = avio_tell(s->pb);
5071 avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
5073 /* start reading at where the new moov will be placed */
5074 avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
5075 pos = avio_tell(read_pb);
5077 #define READ_BLOCK do { \
5078 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
5082 /* shift data by chunk of at most moov_size */
5087 n = read_size[read_buf_id];
5090 avio_write(s->pb, read_buf[read_buf_id], n);
5092 } while (pos < pos_end);
5093 avio_close(read_pb);
5100 static int mov_write_trailer(AVFormatContext *s)
5102 MOVMuxContext *mov = s->priv_data;
5103 AVIOContext *pb = s->pb;
5109 * Before actually writing the trailer, make sure that there are no
5110 * dangling subtitles, that need a terminating sample.
5112 for (i = 0; i < mov->nb_streams; i++) {
5113 MOVTrack *trk = &mov->tracks[i];
5114 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
5115 !trk->last_sample_is_subtitle_end) {
5116 mov_write_subtitle_end_packet(s, i, trk->track_duration);
5117 trk->last_sample_is_subtitle_end = 1;
5121 // If there were no chapters when the header was written, but there
5122 // are chapters now, write them in the trailer. This only works
5123 // when we are not doing fragments.
5124 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5125 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
5126 mov->chapter_track = mov->nb_streams++;
5127 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5132 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5133 moov_pos = avio_tell(pb);
5135 /* Write size of mdat tag */
5136 if (mov->mdat_size + 8 <= UINT32_MAX) {
5137 avio_seek(pb, mov->mdat_pos, SEEK_SET);
5138 avio_wb32(pb, mov->mdat_size + 8);
5140 /* overwrite 'wide' placeholder atom */
5141 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
5142 /* special value: real atom size will be 64 bit value after
5145 ffio_wfourcc(pb, "mdat");
5146 avio_wb64(pb, mov->mdat_size + 16);
5148 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
5150 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5151 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
5152 res = shift_data(s);
5154 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5155 mov_write_moov_tag(pb, mov, s);
5157 } else if (mov->reserved_moov_size > 0) {
5159 mov_write_moov_tag(pb, mov, s);
5160 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
5162 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
5163 res = AVERROR(EINVAL);
5166 avio_wb32(pb, size);
5167 ffio_wfourcc(pb, "free");
5168 ffio_fill(pb, 0, size - 8);
5169 avio_seek(pb, moov_pos, SEEK_SET);
5171 mov_write_moov_tag(pb, mov, s);
5174 mov_auto_flush_fragment(s);
5175 for (i = 0; i < mov->nb_streams; i++)
5176 mov->tracks[i].data_offset = 0;
5177 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5178 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
5179 res = shift_data(s);
5181 int64_t end = avio_tell(pb);
5182 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5183 mov_write_sidx_tags(pb, mov, -1, 0);
5184 avio_seek(pb, end, SEEK_SET);
5185 mov_write_mfra_tag(pb, mov);
5188 mov_write_mfra_tag(pb, mov);
5198 #if CONFIG_MOV_MUXER
5200 AVOutputFormat ff_mov_muxer = {
5202 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5203 .extensions = "mov",
5204 .priv_data_size = sizeof(MOVMuxContext),
5205 .audio_codec = AV_CODEC_ID_AAC,
5206 .video_codec = CONFIG_LIBX264_ENCODER ?
5207 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5208 .write_header = mov_write_header,
5209 .write_packet = mov_write_packet,
5210 .write_trailer = mov_write_trailer,
5211 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5212 .codec_tag = (const AVCodecTag* const []){
5213 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
5215 .priv_class = &mov_muxer_class,
5218 #if CONFIG_TGP_MUXER
5220 AVOutputFormat ff_tgp_muxer = {
5222 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
5223 .extensions = "3gp",
5224 .priv_data_size = sizeof(MOVMuxContext),
5225 .audio_codec = AV_CODEC_ID_AMR_NB,
5226 .video_codec = AV_CODEC_ID_H263,
5227 .write_header = mov_write_header,
5228 .write_packet = mov_write_packet,
5229 .write_trailer = mov_write_trailer,
5230 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5231 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5232 .priv_class = &tgp_muxer_class,
5235 #if CONFIG_MP4_MUXER
5237 AVOutputFormat ff_mp4_muxer = {
5239 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
5240 .mime_type = "application/mp4",
5241 .extensions = "mp4",
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 = &mp4_muxer_class,
5254 #if CONFIG_PSP_MUXER
5256 AVOutputFormat ff_psp_muxer = {
5258 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
5259 .extensions = "mp4,psp",
5260 .priv_data_size = sizeof(MOVMuxContext),
5261 .audio_codec = AV_CODEC_ID_AAC,
5262 .video_codec = CONFIG_LIBX264_ENCODER ?
5263 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5264 .write_header = mov_write_header,
5265 .write_packet = mov_write_packet,
5266 .write_trailer = mov_write_trailer,
5267 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5268 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5269 .priv_class = &psp_muxer_class,
5272 #if CONFIG_TG2_MUXER
5274 AVOutputFormat ff_tg2_muxer = {
5276 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
5277 .extensions = "3g2",
5278 .priv_data_size = sizeof(MOVMuxContext),
5279 .audio_codec = AV_CODEC_ID_AMR_NB,
5280 .video_codec = AV_CODEC_ID_H263,
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_3gp_tags, 0 },
5286 .priv_class = &tg2_muxer_class,
5289 #if CONFIG_IPOD_MUXER
5291 AVOutputFormat ff_ipod_muxer = {
5293 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
5294 .mime_type = "application/mp4",
5295 .extensions = "m4v,m4a",
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 []){ codec_ipod_tags, 0 },
5304 .priv_class = &ipod_muxer_class,
5307 #if CONFIG_ISMV_MUXER
5309 AVOutputFormat ff_ismv_muxer = {
5311 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
5312 .mime_type = "application/mp4",
5313 .extensions = "ismv,isma",
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 | AVFMT_TS_NEGATIVE,
5321 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5322 .priv_class = &ismv_muxer_class,
5325 #if CONFIG_F4V_MUXER
5327 AVOutputFormat ff_f4v_muxer = {
5329 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
5330 .mime_type = "application/f4v",
5331 .extensions = "f4v",
5332 .priv_data_size = sizeof(MOVMuxContext),
5333 .audio_codec = AV_CODEC_ID_AAC,
5334 .video_codec = AV_CODEC_ID_H264,
5335 .write_header = mov_write_header,
5336 .write_packet = mov_write_packet,
5337 .write_trailer = mov_write_trailer,
5338 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
5339 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
5340 .priv_class = &f4v_muxer_class,