swscale: aarch64: Fix yuv2rgb with negative strides
[ffmpeg.git] / libavformat / movenc.c
1 /*
2 * MOV, 3GP, MP4 muxer
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>
6 *
7 * This file is part of FFmpeg.
8 *
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.
13 *
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.
18 *
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
22 */
23
24 #include <stdint.h>
25 #include <inttypes.h>
26
27 #include "movenc.h"
28 #include "avformat.h"
29 #include "avio_internal.h"
30 #include "riff.h"
31 #include "avio.h"
32 #include "isom.h"
33 #include "avc.h"
34 #include "libavcodec/ac3_parser.h"
35 #include "libavcodec/dnxhddata.h"
36 #include "libavcodec/get_bits.h"
37 #include "libavcodec/put_bits.h"
38 #include "libavcodec/vc1_common.h"
39 #include "libavcodec/raw.h"
40 #include "internal.h"
41 #include "libavutil/avstring.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/libm.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/dict.h"
47 #include "libavutil/pixdesc.h"
48 #include "libavutil/timecode.h"
49 #include "libavutil/color_utils.h"
50 #include "hevc.h"
51 #include "rtpenc.h"
52 #include "mov_chan.h"
53 #include "vpcc.h"
54
55 static const AVOption options[] = {
56 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
57 { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
58 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
59 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
60 { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
61 { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
63 { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
64 { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66 { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
67 { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
68 { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69 { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
70 { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
71 { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
72 { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
73 { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
74 { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
75 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
76 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
77 { "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},
78 { "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},
79 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
80 { "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},
81 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
82 { "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},
83 { "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},
84 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
85 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
86 { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
87 { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
88 { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
89 { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
90 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
91 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
92 { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
93 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
94 { NULL },
95 };
96
97 #define MOV_CLASS(flavor)\
98 static const AVClass flavor ## _muxer_class = {\
99 .class_name = #flavor " muxer",\
100 .item_name = av_default_item_name,\
101 .option = options,\
102 .version = LIBAVUTIL_VERSION_INT,\
103 };
104
105 static int get_moov_size(AVFormatContext *s);
106
107 static int utf8len(const uint8_t *b)
108 {
109 int len = 0;
110 int val;
111 while (*b) {
112 GET_UTF8(val, *b++, return -1;)
113 len++;
114 }
115 return len;
116 }
117
118 //FIXME support 64 bit variant with wide placeholders
119 static int64_t update_size(AVIOContext *pb, int64_t pos)
120 {
121 int64_t curpos = avio_tell(pb);
122 avio_seek(pb, pos, SEEK_SET);
123 avio_wb32(pb, curpos - pos); /* rewrite size */
124 avio_seek(pb, curpos, SEEK_SET);
125
126 return curpos - pos;
127 }
128
129 static int co64_required(const MOVTrack *track)
130 {
131 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
132 return 1;
133 return 0;
134 }
135
136 /* Chunk offset atom */
137 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
138 {
139 int i;
140 int mode64 = co64_required(track); // use 32 bit size variant if possible
141 int64_t pos = avio_tell(pb);
142 avio_wb32(pb, 0); /* size */
143 if (mode64)
144 ffio_wfourcc(pb, "co64");
145 else
146 ffio_wfourcc(pb, "stco");
147 avio_wb32(pb, 0); /* version & flags */
148 avio_wb32(pb, track->chunkCount); /* entry count */
149 for (i = 0; i < track->entry; i++) {
150 if (!track->cluster[i].chunkNum)
151 continue;
152 if (mode64 == 1)
153 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
154 else
155 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
156 }
157 return update_size(pb, pos);
158 }
159
160 /* Sample size atom */
161 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
162 {
163 int equalChunks = 1;
164 int i, j, entries = 0, tst = -1, oldtst = -1;
165
166 int64_t pos = avio_tell(pb);
167 avio_wb32(pb, 0); /* size */
168 ffio_wfourcc(pb, "stsz");
169 avio_wb32(pb, 0); /* version & flags */
170
171 for (i = 0; i < track->entry; i++) {
172 tst = track->cluster[i].size / track->cluster[i].entries;
173 if (oldtst != -1 && tst != oldtst)
174 equalChunks = 0;
175 oldtst = tst;
176 entries += track->cluster[i].entries;
177 }
178 if (equalChunks && track->entry) {
179 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
180 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
181 avio_wb32(pb, sSize); // sample size
182 avio_wb32(pb, entries); // sample count
183 } else {
184 avio_wb32(pb, 0); // sample size
185 avio_wb32(pb, entries); // sample count
186 for (i = 0; i < track->entry; i++) {
187 for (j = 0; j < track->cluster[i].entries; j++) {
188 avio_wb32(pb, track->cluster[i].size /
189 track->cluster[i].entries);
190 }
191 }
192 }
193 return update_size(pb, pos);
194 }
195
196 /* Sample to chunk atom */
197 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
198 {
199 int index = 0, oldval = -1, i;
200 int64_t entryPos, curpos;
201
202 int64_t pos = avio_tell(pb);
203 avio_wb32(pb, 0); /* size */
204 ffio_wfourcc(pb, "stsc");
205 avio_wb32(pb, 0); // version & flags
206 entryPos = avio_tell(pb);
207 avio_wb32(pb, track->chunkCount); // entry count
208 for (i = 0; i < track->entry; i++) {
209 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
210 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
211 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
212 avio_wb32(pb, 0x1); // sample description index
213 oldval = track->cluster[i].samples_in_chunk;
214 index++;
215 }
216 }
217 curpos = avio_tell(pb);
218 avio_seek(pb, entryPos, SEEK_SET);
219 avio_wb32(pb, index); // rewrite size
220 avio_seek(pb, curpos, SEEK_SET);
221
222 return update_size(pb, pos);
223 }
224
225 /* Sync sample atom */
226 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
227 {
228 int64_t curpos, entryPos;
229 int i, index = 0;
230 int64_t pos = avio_tell(pb);
231 avio_wb32(pb, 0); // size
232 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
233 avio_wb32(pb, 0); // version & flags
234 entryPos = avio_tell(pb);
235 avio_wb32(pb, track->entry); // entry count
236 for (i = 0; i < track->entry; i++) {
237 if (track->cluster[i].flags & flag) {
238 avio_wb32(pb, i + 1);
239 index++;
240 }
241 }
242 curpos = avio_tell(pb);
243 avio_seek(pb, entryPos, SEEK_SET);
244 avio_wb32(pb, index); // rewrite size
245 avio_seek(pb, curpos, SEEK_SET);
246 return update_size(pb, pos);
247 }
248
249 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
250 {
251 avio_wb32(pb, 0x11); /* size */
252 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
253 else ffio_wfourcc(pb, "damr");
254 ffio_wfourcc(pb, "FFMP");
255 avio_w8(pb, 0); /* decoder version */
256
257 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
258 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
259 avio_w8(pb, 0x01); /* Frames per sample */
260 return 0x11;
261 }
262
263 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
264 {
265 GetBitContext gbc;
266 PutBitContext pbc;
267 uint8_t buf[3];
268 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
269
270 if (track->vos_len < 7)
271 return -1;
272
273 avio_wb32(pb, 11);
274 ffio_wfourcc(pb, "dac3");
275
276 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
277 fscod = get_bits(&gbc, 2);
278 frmsizecod = get_bits(&gbc, 6);
279 bsid = get_bits(&gbc, 5);
280 bsmod = get_bits(&gbc, 3);
281 acmod = get_bits(&gbc, 3);
282 if (acmod == 2) {
283 skip_bits(&gbc, 2); // dsurmod
284 } else {
285 if ((acmod & 1) && acmod != 1)
286 skip_bits(&gbc, 2); // cmixlev
287 if (acmod & 4)
288 skip_bits(&gbc, 2); // surmixlev
289 }
290 lfeon = get_bits1(&gbc);
291
292 init_put_bits(&pbc, buf, sizeof(buf));
293 put_bits(&pbc, 2, fscod);
294 put_bits(&pbc, 5, bsid);
295 put_bits(&pbc, 3, bsmod);
296 put_bits(&pbc, 3, acmod);
297 put_bits(&pbc, 1, lfeon);
298 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
299 put_bits(&pbc, 5, 0); // reserved
300
301 flush_put_bits(&pbc);
302 avio_write(pb, buf, sizeof(buf));
303
304 return 11;
305 }
306
307 struct eac3_info {
308 AVPacket pkt;
309 uint8_t ec3_done;
310 uint8_t num_blocks;
311
312 /* Layout of the EC3SpecificBox */
313 /* maximum bitrate */
314 uint16_t data_rate;
315 /* number of independent substreams */
316 uint8_t num_ind_sub;
317 struct {
318 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
319 uint8_t fscod;
320 /* bit stream identification 5 bits */
321 uint8_t bsid;
322 /* one bit reserved */
323 /* audio service mixing (not supported yet) 1 bit */
324 /* bit stream mode 3 bits */
325 uint8_t bsmod;
326 /* audio coding mode 3 bits */
327 uint8_t acmod;
328 /* sub woofer on 1 bit */
329 uint8_t lfeon;
330 /* 3 bits reserved */
331 /* number of dependent substreams associated with this substream 4 bits */
332 uint8_t num_dep_sub;
333 /* channel locations of the dependent substream(s), if any, 9 bits */
334 uint16_t chan_loc;
335 /* if there is no dependent substream, then one bit reserved instead */
336 } substream[1]; /* TODO: support 8 independent substreams */
337 };
338
339 #if CONFIG_AC3_PARSER
340 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
341 {
342 GetBitContext gbc;
343 AC3HeaderInfo tmp, *hdr = &tmp;
344 struct eac3_info *info;
345 int num_blocks;
346
347 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
348 return AVERROR(ENOMEM);
349 info = track->eac3_priv;
350
351 init_get_bits(&gbc, pkt->data, pkt->size * 8);
352 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
353 /* drop the packets until we see a good one */
354 if (!track->entry) {
355 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
356 return 0;
357 }
358 return AVERROR_INVALIDDATA;
359 }
360
361 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
362 num_blocks = hdr->num_blocks;
363
364 if (!info->ec3_done) {
365 /* AC-3 substream must be the first one */
366 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
367 return AVERROR(EINVAL);
368
369 /* this should always be the case, given that our AC-3 parser
370 * concatenates dependent frames to their independent parent */
371 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
372 /* substream ids must be incremental */
373 if (hdr->substreamid > info->num_ind_sub + 1)
374 return AVERROR(EINVAL);
375
376 if (hdr->substreamid == info->num_ind_sub + 1) {
377 //info->num_ind_sub++;
378 avpriv_request_sample(mov->fc, "Multiple independent substreams");
379 return AVERROR_PATCHWELCOME;
380 } else if (hdr->substreamid < info->num_ind_sub ||
381 hdr->substreamid == 0 && info->substream[0].bsid) {
382 info->ec3_done = 1;
383 goto concatenate;
384 }
385 } else {
386 if (hdr->substreamid != 0) {
387 avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
388 return AVERROR_PATCHWELCOME;
389 }
390 }
391
392 /* fill the info needed for the "dec3" atom */
393 info->substream[hdr->substreamid].fscod = hdr->sr_code;
394 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
395 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
396 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
397 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
398
399 /* Parse dependent substream(s), if any */
400 if (pkt->size != hdr->frame_size) {
401 int cumul_size = hdr->frame_size;
402 int parent = hdr->substreamid;
403
404 while (cumul_size != pkt->size) {
405 int i;
406 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
407 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
408 return AVERROR_INVALIDDATA;
409 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
410 return AVERROR(EINVAL);
411 cumul_size += hdr->frame_size;
412 info->substream[parent].num_dep_sub++;
413
414 /* header is parsed up to lfeon, but custom channel map may be needed */
415 /* skip bsid */
416 skip_bits(&gbc, 5);
417 /* skip volume control params */
418 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
419 skip_bits(&gbc, 5); // skip dialog normalization
420 if (get_bits1(&gbc)) {
421 skip_bits(&gbc, 8); // skip compression gain word
422 }
423 }
424 /* get the dependent stream channel map, if exists */
425 if (get_bits1(&gbc))
426 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
427 else
428 info->substream[parent].chan_loc |= hdr->channel_mode;
429 }
430 }
431 }
432
433 concatenate:
434 if (!info->num_blocks && num_blocks == 6)
435 return pkt->size;
436 else if (info->num_blocks + num_blocks > 6)
437 return AVERROR_INVALIDDATA;
438
439 if (!info->num_blocks) {
440 int ret;
441 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
442 return ret;
443 info->num_blocks = num_blocks;
444 return 0;
445 } else {
446 int ret;
447 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
448 return ret;
449 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
450 info->num_blocks += num_blocks;
451 info->pkt.duration += pkt->duration;
452 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
453 return ret;
454 if (info->num_blocks != 6)
455 return 0;
456 av_packet_unref(pkt);
457 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
458 return ret;
459 av_packet_unref(&info->pkt);
460 info->num_blocks = 0;
461 }
462
463 return pkt->size;
464 }
465 #endif
466
467 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
468 {
469 PutBitContext pbc;
470 uint8_t *buf;
471 struct eac3_info *info;
472 int size, i;
473
474 if (!track->eac3_priv)
475 return AVERROR(EINVAL);
476
477 info = track->eac3_priv;
478 size = 2 + 4 * (info->num_ind_sub + 1);
479 buf = av_malloc(size);
480 if (!buf) {
481 size = AVERROR(ENOMEM);
482 goto end;
483 }
484
485 init_put_bits(&pbc, buf, size);
486 put_bits(&pbc, 13, info->data_rate);
487 put_bits(&pbc, 3, info->num_ind_sub);
488 for (i = 0; i <= info->num_ind_sub; i++) {
489 put_bits(&pbc, 2, info->substream[i].fscod);
490 put_bits(&pbc, 5, info->substream[i].bsid);
491 put_bits(&pbc, 1, 0); /* reserved */
492 put_bits(&pbc, 1, 0); /* asvc */
493 put_bits(&pbc, 3, info->substream[i].bsmod);
494 put_bits(&pbc, 3, info->substream[i].acmod);
495 put_bits(&pbc, 1, info->substream[i].lfeon);
496 put_bits(&pbc, 5, 0); /* reserved */
497 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
498 if (!info->substream[i].num_dep_sub) {
499 put_bits(&pbc, 1, 0); /* reserved */
500 size--;
501 } else {
502 put_bits(&pbc, 9, info->substream[i].chan_loc);
503 }
504 }
505 flush_put_bits(&pbc);
506
507 avio_wb32(pb, size + 8);
508 ffio_wfourcc(pb, "dec3");
509 avio_write(pb, buf, size);
510
511 av_free(buf);
512
513 end:
514 av_packet_unref(&info->pkt);
515 av_freep(&track->eac3_priv);
516
517 return size;
518 }
519
520 /**
521 * This function writes extradata "as is".
522 * Extradata must be formatted like a valid atom (with size and tag).
523 */
524 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
525 {
526 avio_write(pb, track->par->extradata, track->par->extradata_size);
527 return track->par->extradata_size;
528 }
529
530 static int mov_write_enda_tag(AVIOContext *pb)
531 {
532 avio_wb32(pb, 10);
533 ffio_wfourcc(pb, "enda");
534 avio_wb16(pb, 1); /* little endian */
535 return 10;
536 }
537
538 static int mov_write_enda_tag_be(AVIOContext *pb)
539 {
540 avio_wb32(pb, 10);
541 ffio_wfourcc(pb, "enda");
542 avio_wb16(pb, 0); /* big endian */
543 return 10;
544 }
545
546 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
547 {
548 int i = 3;
549 avio_w8(pb, tag);
550 for (; i > 0; i--)
551 avio_w8(pb, (size >> (7 * i)) | 0x80);
552 avio_w8(pb, size & 0x7F);
553 }
554
555 static unsigned compute_avg_bitrate(MOVTrack *track)
556 {
557 uint64_t size = 0;
558 int i;
559 if (!track->track_duration)
560 return 0;
561 for (i = 0; i < track->entry; i++)
562 size += track->cluster[i].size;
563 return size * 8 * track->timescale / track->track_duration;
564 }
565
566 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
567 {
568 AVCPBProperties *props;
569 int64_t pos = avio_tell(pb);
570 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
571 unsigned avg_bitrate;
572
573 avio_wb32(pb, 0); // size
574 ffio_wfourcc(pb, "esds");
575 avio_wb32(pb, 0); // Version
576
577 // ES descriptor
578 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
579 avio_wb16(pb, track->track_id);
580 avio_w8(pb, 0x00); // flags (= no flags)
581
582 // DecoderConfig descriptor
583 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
584
585 // Object type indication
586 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
587 track->par->codec_id == AV_CODEC_ID_MP3) &&
588 track->par->sample_rate > 24000)
589 avio_w8(pb, 0x6B); // 11172-3
590 else
591 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
592
593 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
594 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
595 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
596 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
597 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
598 avio_w8(pb, 0x15); // flags (= Audiostream)
599 else
600 avio_w8(pb, 0x11); // flags (= Visualstream)
601
602 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
603 NULL);
604
605 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
606
607 avg_bitrate = compute_avg_bitrate(track);
608 avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
609 avio_wb32(pb, avg_bitrate);
610
611 if (track->vos_len) {
612 // DecoderSpecific info descriptor
613 put_descr(pb, 0x05, track->vos_len);
614 avio_write(pb, track->vos_data, track->vos_len);
615 }
616
617 // SL descriptor
618 put_descr(pb, 0x06, 1);
619 avio_w8(pb, 0x02);
620 return update_size(pb, pos);
621 }
622
623 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
624 {
625 return codec_id == AV_CODEC_ID_PCM_S24LE ||
626 codec_id == AV_CODEC_ID_PCM_S32LE ||
627 codec_id == AV_CODEC_ID_PCM_F32LE ||
628 codec_id == AV_CODEC_ID_PCM_F64LE;
629 }
630
631 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
632 {
633 return codec_id == AV_CODEC_ID_PCM_S24BE ||
634 codec_id == AV_CODEC_ID_PCM_S32BE ||
635 codec_id == AV_CODEC_ID_PCM_F32BE ||
636 codec_id == AV_CODEC_ID_PCM_F64BE;
637 }
638
639 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
640 {
641 int ret;
642 int64_t pos = avio_tell(pb);
643 avio_wb32(pb, 0);
644 avio_wl32(pb, track->tag); // store it byteswapped
645 track->par->codec_tag = av_bswap16(track->tag >> 16);
646 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
647 return ret;
648 return update_size(pb, pos);
649 }
650
651 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
652 {
653 int ret;
654 int64_t pos = avio_tell(pb);
655 avio_wb32(pb, 0);
656 ffio_wfourcc(pb, "wfex");
657 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
658 return ret;
659 return update_size(pb, pos);
660 }
661
662 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
663 {
664 uint32_t layout_tag, bitmap;
665 int64_t pos = avio_tell(pb);
666
667 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
668 track->par->channel_layout,
669 &bitmap);
670 if (!layout_tag) {
671 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
672 "lack of channel information\n");
673 return 0;
674 }
675
676 if (track->multichannel_as_mono)
677 return 0;
678
679 avio_wb32(pb, 0); // Size
680 ffio_wfourcc(pb, "chan"); // Type
681 avio_w8(pb, 0); // Version
682 avio_wb24(pb, 0); // Flags
683 avio_wb32(pb, layout_tag); // mChannelLayoutTag
684 avio_wb32(pb, bitmap); // mChannelBitmap
685 avio_wb32(pb, 0); // mNumberChannelDescriptions
686
687 return update_size(pb, pos);
688 }
689
690 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
691 {
692 int64_t pos = avio_tell(pb);
693
694 avio_wb32(pb, 0); /* size */
695 ffio_wfourcc(pb, "wave");
696
697 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
698 avio_wb32(pb, 12); /* size */
699 ffio_wfourcc(pb, "frma");
700 avio_wl32(pb, track->tag);
701 }
702
703 if (track->par->codec_id == AV_CODEC_ID_AAC) {
704 /* useless atom needed by mplayer, ipod, not needed by quicktime */
705 avio_wb32(pb, 12); /* size */
706 ffio_wfourcc(pb, "mp4a");
707 avio_wb32(pb, 0);
708 mov_write_esds_tag(pb, track);
709 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
710 mov_write_enda_tag(pb);
711 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
712 mov_write_enda_tag_be(pb);
713 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
714 mov_write_amr_tag(pb, track);
715 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
716 mov_write_ac3_tag(pb, track);
717 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
718 mov_write_eac3_tag(pb, track);
719 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
720 track->par->codec_id == AV_CODEC_ID_QDM2) {
721 mov_write_extradata_tag(pb, track);
722 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
723 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
724 mov_write_ms_tag(s, pb, track);
725 }
726
727 avio_wb32(pb, 8); /* size */
728 avio_wb32(pb, 0); /* null tag */
729
730 return update_size(pb, pos);
731 }
732
733 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
734 {
735 uint8_t *unescaped;
736 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
737 int unescaped_size, seq_found = 0;
738 int level = 0, interlace = 0;
739 int packet_seq = track->vc1_info.packet_seq;
740 int packet_entry = track->vc1_info.packet_entry;
741 int slices = track->vc1_info.slices;
742 PutBitContext pbc;
743
744 if (track->start_dts == AV_NOPTS_VALUE) {
745 /* No packets written yet, vc1_info isn't authoritative yet. */
746 /* Assume inline sequence and entry headers. */
747 packet_seq = packet_entry = 1;
748 av_log(NULL, AV_LOG_WARNING,
749 "moov atom written before any packets, unable to write correct "
750 "dvc1 atom. Set the delay_moov flag to fix this.\n");
751 }
752
753 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
754 if (!unescaped)
755 return AVERROR(ENOMEM);
756 start = find_next_marker(track->vos_data, end);
757 for (next = start; next < end; start = next) {
758 GetBitContext gb;
759 int size;
760 next = find_next_marker(start + 4, end);
761 size = next - start - 4;
762 if (size <= 0)
763 continue;
764 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
765 init_get_bits(&gb, unescaped, 8 * unescaped_size);
766 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
767 int profile = get_bits(&gb, 2);
768 if (profile != PROFILE_ADVANCED) {
769 av_free(unescaped);
770 return AVERROR(ENOSYS);
771 }
772 seq_found = 1;
773 level = get_bits(&gb, 3);
774 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
775 * width, height */
776 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
777 skip_bits(&gb, 1); /* broadcast */
778 interlace = get_bits1(&gb);
779 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
780 }
781 }
782 if (!seq_found) {
783 av_free(unescaped);
784 return AVERROR(ENOSYS);
785 }
786
787 init_put_bits(&pbc, buf, 7);
788 /* VC1DecSpecStruc */
789 put_bits(&pbc, 4, 12); /* profile - advanced */
790 put_bits(&pbc, 3, level);
791 put_bits(&pbc, 1, 0); /* reserved */
792 /* VC1AdvDecSpecStruc */
793 put_bits(&pbc, 3, level);
794 put_bits(&pbc, 1, 0); /* cbr */
795 put_bits(&pbc, 6, 0); /* reserved */
796 put_bits(&pbc, 1, !interlace); /* no interlace */
797 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
798 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
799 put_bits(&pbc, 1, !slices); /* no slice code */
800 put_bits(&pbc, 1, 0); /* no bframe */
801 put_bits(&pbc, 1, 0); /* reserved */
802
803 /* framerate */
804 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
805 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
806 else
807 put_bits32(&pbc, 0xffffffff);
808
809 flush_put_bits(&pbc);
810
811 av_free(unescaped);
812
813 return 0;
814 }
815
816 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
817 {
818 uint8_t buf[7] = { 0 };
819 int ret;
820
821 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
822 return ret;
823
824 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
825 ffio_wfourcc(pb, "dvc1");
826 avio_write(pb, buf, sizeof(buf));
827 avio_write(pb, track->vos_data, track->vos_len);
828
829 return 0;
830 }
831
832 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
833 {
834 avio_wb32(pb, track->vos_len + 8);
835 ffio_wfourcc(pb, "glbl");
836 avio_write(pb, track->vos_data, track->vos_len);
837 return 8 + track->vos_len;
838 }
839
840 /**
841 * Compute flags for 'lpcm' tag.
842 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
843 */
844 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
845 {
846 switch (codec_id) {
847 case AV_CODEC_ID_PCM_F32BE:
848 case AV_CODEC_ID_PCM_F64BE:
849 return 11;
850 case AV_CODEC_ID_PCM_F32LE:
851 case AV_CODEC_ID_PCM_F64LE:
852 return 9;
853 case AV_CODEC_ID_PCM_U8:
854 return 10;
855 case AV_CODEC_ID_PCM_S16BE:
856 case AV_CODEC_ID_PCM_S24BE:
857 case AV_CODEC_ID_PCM_S32BE:
858 return 14;
859 case AV_CODEC_ID_PCM_S8:
860 case AV_CODEC_ID_PCM_S16LE:
861 case AV_CODEC_ID_PCM_S24LE:
862 case AV_CODEC_ID_PCM_S32LE:
863 return 12;
864 default:
865 return 0;
866 }
867 }
868
869 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
870 {
871 int64_t next_dts;
872
873 if (cluster_idx >= track->entry)
874 return 0;
875
876 if (cluster_idx + 1 == track->entry)
877 next_dts = track->track_duration + track->start_dts;
878 else
879 next_dts = track->cluster[cluster_idx + 1].dts;
880
881 next_dts -= track->cluster[cluster_idx].dts;
882
883 av_assert0(next_dts >= 0);
884 av_assert0(next_dts <= INT_MAX);
885
886 return next_dts;
887 }
888
889 static int get_samples_per_packet(MOVTrack *track)
890 {
891 int i, first_duration;
892
893 // return track->par->frame_size;
894
895 /* use 1 for raw PCM */
896 if (!track->audio_vbr)
897 return 1;
898
899 /* check to see if duration is constant for all clusters */
900 if (!track->entry)
901 return 0;
902 first_duration = get_cluster_duration(track, 0);
903 for (i = 1; i < track->entry; i++) {
904 if (get_cluster_duration(track, i) != first_duration)
905 return 0;
906 }
907 return first_duration;
908 }
909
910 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
911 {
912 int64_t pos = avio_tell(pb);
913 int version = 0;
914 uint32_t tag = track->tag;
915
916 if (track->mode == MODE_MOV) {
917 if (track->timescale > UINT16_MAX || !track->par->channels) {
918 if (mov_get_lpcm_flags(track->par->codec_id))
919 tag = AV_RL32("lpcm");
920 version = 2;
921 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
922 mov_pcm_be_gt16(track->par->codec_id) ||
923 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
924 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
925 track->par->codec_id == AV_CODEC_ID_QDM2) {
926 version = 1;
927 }
928 }
929
930 avio_wb32(pb, 0); /* size */
931 if (mov->encryption_scheme != MOV_ENC_NONE) {
932 ffio_wfourcc(pb, "enca");
933 } else {
934 avio_wl32(pb, tag); // store it byteswapped
935 }
936 avio_wb32(pb, 0); /* Reserved */
937 avio_wb16(pb, 0); /* Reserved */
938 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
939
940 /* SoundDescription */
941 avio_wb16(pb, version); /* Version */
942 avio_wb16(pb, 0); /* Revision level */
943 avio_wb32(pb, 0); /* Reserved */
944
945 if (version == 2) {
946 avio_wb16(pb, 3);
947 avio_wb16(pb, 16);
948 avio_wb16(pb, 0xfffe);
949 avio_wb16(pb, 0);
950 avio_wb32(pb, 0x00010000);
951 avio_wb32(pb, 72);
952 avio_wb64(pb, av_double2int(track->par->sample_rate));
953 avio_wb32(pb, track->par->channels);
954 avio_wb32(pb, 0x7F000000);
955 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
956 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
957 avio_wb32(pb, track->sample_size);
958 avio_wb32(pb, get_samples_per_packet(track));
959 } else {
960 if (track->mode == MODE_MOV) {
961 avio_wb16(pb, track->par->channels);
962 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
963 track->par->codec_id == AV_CODEC_ID_PCM_S8)
964 avio_wb16(pb, 8); /* bits per sample */
965 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
966 avio_wb16(pb, track->par->bits_per_coded_sample);
967 else
968 avio_wb16(pb, 16);
969 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
970 } else { /* reserved for mp4/3gp */
971 avio_wb16(pb, 2);
972 avio_wb16(pb, 16);
973 avio_wb16(pb, 0);
974 }
975
976 avio_wb16(pb, 0); /* packet size (= 0) */
977 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
978 track->par->sample_rate : 0);
979 avio_wb16(pb, 0); /* Reserved */
980 }
981
982 if (version == 1) { /* SoundDescription V1 extended info */
983 if (mov_pcm_le_gt16(track->par->codec_id) ||
984 mov_pcm_be_gt16(track->par->codec_id))
985 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
986 else
987 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
988 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
989 avio_wb32(pb, track->sample_size); /* Bytes per frame */
990 avio_wb32(pb, 2); /* Bytes per sample */
991 }
992
993 if (track->mode == MODE_MOV &&
994 (track->par->codec_id == AV_CODEC_ID_AAC ||
995 track->par->codec_id == AV_CODEC_ID_AC3 ||
996 track->par->codec_id == AV_CODEC_ID_EAC3 ||
997 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
998 track->par->codec_id == AV_CODEC_ID_ALAC ||
999 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1000 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1001 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1002 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1003 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1004 mov_write_wave_tag(s, pb, track);
1005 else if (track->tag == MKTAG('m','p','4','a'))
1006 mov_write_esds_tag(pb, track);
1007 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1008 mov_write_amr_tag(pb, track);
1009 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1010 mov_write_ac3_tag(pb, track);
1011 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1012 mov_write_eac3_tag(pb, track);
1013 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1014 mov_write_extradata_tag(pb, track);
1015 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1016 mov_write_wfex_tag(s, pb, track);
1017 else if (track->vos_len > 0)
1018 mov_write_glbl_tag(pb, track);
1019
1020 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1021 mov_write_chan_tag(s, pb, track);
1022
1023 if (mov->encryption_scheme != MOV_ENC_NONE) {
1024 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1025 }
1026
1027 return update_size(pb, pos);
1028 }
1029
1030 static int mov_write_d263_tag(AVIOContext *pb)
1031 {
1032 avio_wb32(pb, 0xf); /* size */
1033 ffio_wfourcc(pb, "d263");
1034 ffio_wfourcc(pb, "FFMP");
1035 avio_w8(pb, 0); /* decoder version */
1036 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1037 avio_w8(pb, 0xa); /* level */
1038 avio_w8(pb, 0); /* profile */
1039 return 0xf;
1040 }
1041
1042 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1043 {
1044 int64_t pos = avio_tell(pb);
1045
1046 avio_wb32(pb, 0);
1047 ffio_wfourcc(pb, "avcC");
1048 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1049 return update_size(pb, pos);
1050 }
1051
1052 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1053 {
1054 int64_t pos = avio_tell(pb);
1055
1056 avio_wb32(pb, 0);
1057 ffio_wfourcc(pb, "vpcC");
1058 avio_wb32(pb, 0); /* version & flags */
1059 ff_isom_write_vpcc(s, pb, track->par);
1060 return update_size(pb, pos);
1061 }
1062
1063 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1064 {
1065 int64_t pos = avio_tell(pb);
1066
1067 avio_wb32(pb, 0);
1068 ffio_wfourcc(pb, "hvcC");
1069 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1070 return update_size(pb, pos);
1071 }
1072
1073 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1074 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1075 {
1076 int i;
1077 int interlaced;
1078 int cid;
1079 int display_width = track->par->width;
1080
1081 if (track->vos_data && track->vos_len > 0x29) {
1082 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1083 /* looks like a DNxHD bit stream */
1084 interlaced = (track->vos_data[5] & 2);
1085 cid = AV_RB32(track->vos_data + 0x28);
1086 } else {
1087 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1088 return 0;
1089 }
1090 } else {
1091 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1092 return 0;
1093 }
1094
1095 avio_wb32(pb, 24); /* size */
1096 ffio_wfourcc(pb, "ACLR");
1097 ffio_wfourcc(pb, "ACLR");
1098 ffio_wfourcc(pb, "0001");
1099 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1100 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1101 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1102 } else { /* Full range (0-255) */
1103 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1104 }
1105 avio_wb32(pb, 0); /* unknown */
1106
1107 if (track->tag == MKTAG('A','V','d','h')) {
1108 avio_wb32(pb, 32);
1109 ffio_wfourcc(pb, "ADHR");
1110 ffio_wfourcc(pb, "0001");
1111 avio_wb32(pb, cid);
1112 avio_wb32(pb, 0); /* unknown */
1113 avio_wb32(pb, 1); /* unknown */
1114 avio_wb32(pb, 0); /* unknown */
1115 avio_wb32(pb, 0); /* unknown */
1116 return 0;
1117 }
1118
1119 avio_wb32(pb, 24); /* size */
1120 ffio_wfourcc(pb, "APRG");
1121 ffio_wfourcc(pb, "APRG");
1122 ffio_wfourcc(pb, "0001");
1123 avio_wb32(pb, 1); /* unknown */
1124 avio_wb32(pb, 0); /* unknown */
1125
1126 avio_wb32(pb, 120); /* size */
1127 ffio_wfourcc(pb, "ARES");
1128 ffio_wfourcc(pb, "ARES");
1129 ffio_wfourcc(pb, "0001");
1130 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1131 if ( track->par->sample_aspect_ratio.num > 0
1132 && track->par->sample_aspect_ratio.den > 0)
1133 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1134 avio_wb32(pb, display_width);
1135 /* values below are based on samples created with quicktime and avid codecs */
1136 if (interlaced) {
1137 avio_wb32(pb, track->par->height / 2);
1138 avio_wb32(pb, 2); /* unknown */
1139 avio_wb32(pb, 0); /* unknown */
1140 avio_wb32(pb, 4); /* unknown */
1141 } else {
1142 avio_wb32(pb, track->par->height);
1143 avio_wb32(pb, 1); /* unknown */
1144 avio_wb32(pb, 0); /* unknown */
1145 if (track->par->height == 1080)
1146 avio_wb32(pb, 5); /* unknown */
1147 else
1148 avio_wb32(pb, 6); /* unknown */
1149 }
1150 /* padding */
1151 for (i = 0; i < 10; i++)
1152 avio_wb64(pb, 0);
1153
1154 return 0;
1155 }
1156
1157 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1158 {
1159 avio_wb32(pb, 12);
1160 ffio_wfourcc(pb, "DpxE");
1161 if (track->par->extradata_size >= 12 &&
1162 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1163 avio_wb32(pb, track->par->extradata[11]);
1164 } else {
1165 avio_wb32(pb, 1);
1166 }
1167 return 0;
1168 }
1169
1170 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1171 {
1172 int tag = track->par->codec_tag;
1173
1174 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
1175 return 0;
1176
1177 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1178 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1179 else if (track->par->codec_id == AV_CODEC_ID_VP9) tag = MKTAG('v','p','0','9');
1180 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1181 else if (track->par->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1182 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1183 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1184 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1185 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1186 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1187 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1188
1189 return tag;
1190 }
1191
1192 static const AVCodecTag codec_ipod_tags[] = {
1193 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1194 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1195 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1196 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1197 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1198 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1199 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1200 { AV_CODEC_ID_NONE, 0 },
1201 };
1202
1203 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1204 {
1205 int tag = track->par->codec_tag;
1206
1207 // keep original tag for subs, ipod supports both formats
1208 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1209 (tag == MKTAG('t', 'x', '3', 'g') ||
1210 tag == MKTAG('t', 'e', 'x', 't'))))
1211 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
1212
1213 if (!av_match_ext(s->filename, "m4a") &&
1214 !av_match_ext(s->filename, "m4b") &&
1215 !av_match_ext(s->filename, "m4v"))
1216 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1217 "Quicktime/Ipod might not play the file\n");
1218
1219 return tag;
1220 }
1221
1222 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1223 {
1224 int tag;
1225
1226 if (track->par->width == 720) { /* SD */
1227 if (track->par->height == 480) { /* NTSC */
1228 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1229 else tag = MKTAG('d','v','c',' ');
1230 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1231 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1232 else tag = MKTAG('d','v','p','p');
1233 } else if (track->par->height == 720) { /* HD 720 line */
1234 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1235 else tag = MKTAG('d','v','h','p');
1236 } else if (track->par->height == 1080) { /* HD 1080 line */
1237 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1238 else tag = MKTAG('d','v','h','6');
1239 } else {
1240 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1241 return 0;
1242 }
1243
1244 return tag;
1245 }
1246
1247 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1248 {
1249 AVRational rate = st->avg_frame_rate;
1250
1251 #if FF_API_LAVF_AVCTX
1252 FF_DISABLE_DEPRECATION_WARNINGS
1253 rate = av_inv_q(st->codec->time_base);
1254 if (av_timecode_check_frame_rate(rate) < 0) {
1255 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1256 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1257 rate = st->avg_frame_rate;
1258 }
1259 FF_ENABLE_DEPRECATION_WARNINGS
1260 #endif
1261
1262 return rate;
1263 }
1264
1265 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1266 {
1267 int tag = track->par->codec_tag;
1268 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1269 AVStream *st = track->st;
1270 int rate = av_q2d(find_fps(s, st));
1271
1272 if (!tag)
1273 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1274
1275 if (track->par->format == AV_PIX_FMT_YUV420P) {
1276 if (track->par->width == 1280 && track->par->height == 720) {
1277 if (!interlaced) {
1278 if (rate == 24) tag = MKTAG('x','d','v','4');
1279 else if (rate == 25) tag = MKTAG('x','d','v','5');
1280 else if (rate == 30) tag = MKTAG('x','d','v','1');
1281 else if (rate == 50) tag = MKTAG('x','d','v','a');
1282 else if (rate == 60) tag = MKTAG('x','d','v','9');
1283 }
1284 } else if (track->par->width == 1440 && track->par->height == 1080) {
1285 if (!interlaced) {
1286 if (rate == 24) tag = MKTAG('x','d','v','6');
1287 else if (rate == 25) tag = MKTAG('x','d','v','7');
1288 else if (rate == 30) tag = MKTAG('x','d','v','8');
1289 } else {
1290 if (rate == 25) tag = MKTAG('x','d','v','3');
1291 else if (rate == 30) tag = MKTAG('x','d','v','2');
1292 }
1293 } else if (track->par->width == 1920 && track->par->height == 1080) {
1294 if (!interlaced) {
1295 if (rate == 24) tag = MKTAG('x','d','v','d');
1296 else if (rate == 25) tag = MKTAG('x','d','v','e');
1297 else if (rate == 30) tag = MKTAG('x','d','v','f');
1298 } else {
1299 if (rate == 25) tag = MKTAG('x','d','v','c');
1300 else if (rate == 30) tag = MKTAG('x','d','v','b');
1301 }
1302 }
1303 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1304 if (track->par->width == 1280 && track->par->height == 720) {
1305 if (!interlaced) {
1306 if (rate == 24) tag = MKTAG('x','d','5','4');
1307 else if (rate == 25) tag = MKTAG('x','d','5','5');
1308 else if (rate == 30) tag = MKTAG('x','d','5','1');
1309 else if (rate == 50) tag = MKTAG('x','d','5','a');
1310 else if (rate == 60) tag = MKTAG('x','d','5','9');
1311 }
1312 } else if (track->par->width == 1920 && track->par->height == 1080) {
1313 if (!interlaced) {
1314 if (rate == 24) tag = MKTAG('x','d','5','d');
1315 else if (rate == 25) tag = MKTAG('x','d','5','e');
1316 else if (rate == 30) tag = MKTAG('x','d','5','f');
1317 } else {
1318 if (rate == 25) tag = MKTAG('x','d','5','c');
1319 else if (rate == 30) tag = MKTAG('x','d','5','b');
1320 }
1321 }
1322 }
1323
1324 return tag;
1325 }
1326
1327 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1328 {
1329 int tag = track->par->codec_tag;
1330 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1331 AVStream *st = track->st;
1332 int rate = av_q2d(find_fps(s, st));
1333
1334 if (!tag)
1335 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1336
1337 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1338 if (track->par->width == 960 && track->par->height == 720) {
1339 if (!interlaced) {
1340 if (rate == 24) tag = MKTAG('a','i','5','p');
1341 else if (rate == 25) tag = MKTAG('a','i','5','q');
1342 else if (rate == 30) tag = MKTAG('a','i','5','p');
1343 else if (rate == 50) tag = MKTAG('a','i','5','q');
1344 else if (rate == 60) tag = MKTAG('a','i','5','p');
1345 }
1346 } else if (track->par->width == 1440 && track->par->height == 1080) {
1347 if (!interlaced) {
1348 if (rate == 24) tag = MKTAG('a','i','5','3');
1349 else if (rate == 25) tag = MKTAG('a','i','5','2');
1350 else if (rate == 30) tag = MKTAG('a','i','5','3');
1351 } else {
1352 if (rate == 50) tag = MKTAG('a','i','5','5');
1353 else if (rate == 60) tag = MKTAG('a','i','5','6');
1354 }
1355 }
1356 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1357 if (track->par->width == 1280 && track->par->height == 720) {
1358 if (!interlaced) {
1359 if (rate == 24) tag = MKTAG('a','i','1','p');
1360 else if (rate == 25) tag = MKTAG('a','i','1','q');
1361 else if (rate == 30) tag = MKTAG('a','i','1','p');
1362 else if (rate == 50) tag = MKTAG('a','i','1','q');
1363 else if (rate == 60) tag = MKTAG('a','i','1','p');
1364 }
1365 } else if (track->par->width == 1920 && track->par->height == 1080) {
1366 if (!interlaced) {
1367 if (rate == 24) tag = MKTAG('a','i','1','3');
1368 else if (rate == 25) tag = MKTAG('a','i','1','2');
1369 else if (rate == 30) tag = MKTAG('a','i','1','3');
1370 } else {
1371 if (rate == 25) tag = MKTAG('a','i','1','5');
1372 else if (rate == 50) tag = MKTAG('a','i','1','5');
1373 else if (rate == 60) tag = MKTAG('a','i','1','6');
1374 }
1375 } else if ( track->par->width == 4096 && track->par->height == 2160
1376 || track->par->width == 3840 && track->par->height == 2160
1377 || track->par->width == 2048 && track->par->height == 1080) {
1378 tag = MKTAG('a','i','v','x');
1379 }
1380 }
1381
1382 return tag;
1383 }
1384
1385 static const struct {
1386 enum AVPixelFormat pix_fmt;
1387 uint32_t tag;
1388 unsigned bps;
1389 } mov_pix_fmt_tags[] = {
1390 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1391 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1392 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1393 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1394 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1395 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1396 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1397 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1398 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1399 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1400 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1401 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1402 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1403 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1404 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1405 };
1406
1407 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1408 {
1409 int tag = MKTAG('A','V','d','n');
1410 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1411 track->par->profile != FF_PROFILE_DNXHD)
1412 tag = MKTAG('A','V','d','h');
1413 return tag;
1414 }
1415
1416 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1417 {
1418 int tag = track->par->codec_tag;
1419 int i;
1420 enum AVPixelFormat pix_fmt;
1421
1422 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1423 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1424 tag = mov_pix_fmt_tags[i].tag;
1425 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1426 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1427 break;
1428 }
1429 }
1430
1431 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1432 track->par->bits_per_coded_sample);
1433 if (tag == MKTAG('r','a','w',' ') &&
1434 track->par->format != pix_fmt &&
1435 track->par->format != AV_PIX_FMT_NONE)
1436 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1437 av_get_pix_fmt_name(track->par->format));
1438 return tag;
1439 }
1440
1441 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1442 {
1443 int tag = track->par->codec_tag;
1444
1445 // "rtp " is used to distinguish internally created RTP-hint tracks
1446 // (with rtp_ctx) from other tracks.
1447 if (tag == MKTAG('r','t','p',' '))
1448 tag = 0;
1449 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1450 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1451 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1452 track->par->codec_id == AV_CODEC_ID_H263 ||
1453 track->par->codec_id == AV_CODEC_ID_H264 ||
1454 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1455 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1456 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1457 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1458 tag = mov_get_dv_codec_tag(s, track);
1459 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1460 tag = mov_get_rawvideo_codec_tag(s, track);
1461 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1462 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1463 else if (track->par->codec_id == AV_CODEC_ID_H264)
1464 tag = mov_get_h264_codec_tag(s, track);
1465 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1466 tag = mov_get_dnxhd_codec_tag(s, track);
1467 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1468 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1469 if (!tag) { // if no mac fcc found, try with Microsoft tags
1470 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1471 if (tag)
1472 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1473 "the file may be unplayable!\n");
1474 }
1475 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1476 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1477 if (!tag) { // if no mac fcc found, try with Microsoft tags
1478 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1479 if (ms_tag) {
1480 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1481 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1482 "the file may be unplayable!\n");
1483 }
1484 }
1485 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1486 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1487 }
1488
1489 return tag;
1490 }
1491
1492 static const AVCodecTag codec_3gp_tags[] = {
1493 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1494 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1495 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1496 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1497 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1498 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1499 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1500 { AV_CODEC_ID_NONE, 0 },
1501 };
1502
1503 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1504 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1505 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1506 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1507 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1508 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1509 { AV_CODEC_ID_NONE, 0 },
1510 };
1511
1512 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1513 {
1514 int tag;
1515
1516 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1517 tag = mp4_get_codec_tag(s, track);
1518 else if (track->mode == MODE_ISM) {
1519 tag = mp4_get_codec_tag(s, track);
1520 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
1521 tag = MKTAG('w', 'm', 'a', ' ');
1522 } else if (track->mode == MODE_IPOD)
1523 tag = ipod_get_codec_tag(s, track);
1524 else if (track->mode & MODE_3GP)
1525 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
1526 else if (track->mode == MODE_F4V)
1527 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
1528 else
1529 tag = mov_get_codec_tag(s, track);
1530
1531 return tag;
1532 }
1533
1534 /** Write uuid atom.
1535 * Needed to make file play in iPods running newest firmware
1536 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1537 */
1538 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1539 {
1540 avio_wb32(pb, 28);
1541 ffio_wfourcc(pb, "uuid");
1542 avio_wb32(pb, 0x6b6840f2);
1543 avio_wb32(pb, 0x5f244fc5);
1544 avio_wb32(pb, 0xba39a51b);
1545 avio_wb32(pb, 0xcf0323f3);
1546 avio_wb32(pb, 0x0);
1547 return 28;
1548 }
1549
1550 static const uint16_t fiel_data[] = {
1551 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1552 };
1553
1554 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1555 {
1556 unsigned mov_field_order = 0;
1557 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1558 mov_field_order = fiel_data[field_order];
1559 else
1560 return 0;
1561 avio_wb32(pb, 10);
1562 ffio_wfourcc(pb, "fiel");
1563 avio_wb16(pb, mov_field_order);
1564 return 10;
1565 }
1566
1567 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1568 {
1569 int64_t pos = avio_tell(pb);
1570 avio_wb32(pb, 0); /* size */
1571 avio_wl32(pb, track->tag); // store it byteswapped
1572 avio_wb32(pb, 0); /* Reserved */
1573 avio_wb16(pb, 0); /* Reserved */
1574 avio_wb16(pb, 1); /* Data-reference index */
1575
1576 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1577 mov_write_esds_tag(pb, track);
1578 else if (track->par->extradata_size)
1579 avio_write(pb, track->par->extradata, track->par->extradata_size);
1580
1581 return update_size(pb, pos);
1582 }
1583
1584 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1585 {
1586 AVRational sar;
1587 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1588 track->par->sample_aspect_ratio.den, INT_MAX);
1589
1590 avio_wb32(pb, 16);
1591 ffio_wfourcc(pb, "pasp");
1592 avio_wb32(pb, sar.num);
1593 avio_wb32(pb, sar.den);
1594 return 16;
1595 }
1596
1597 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1598 {
1599 uint32_t gama = 0;
1600 if (gamma <= 0.0)
1601 {
1602 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1603 }
1604 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1605
1606 if (gamma > 1e-6) {
1607 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1608 av_log(pb, AV_LOG_DEBUG, "writing gama value %d\n", gama);
1609
1610 av_assert0(track->mode == MODE_MOV);
1611 avio_wb32(pb, 12);
1612 ffio_wfourcc(pb, "gama");
1613 avio_wb32(pb, gama);
1614 return 12;
1615 }
1616 else {
1617 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1618 }
1619 return 0;
1620 }
1621
1622 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1623 {
1624 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1625 // Ref (MP4): ISO/IEC 14496-12:2012
1626
1627 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1628 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1629 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1630 if ((track->par->width >= 1920 && track->par->height >= 1080)
1631 || (track->par->width == 1280 && track->par->height == 720)) {
1632 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1633 track->par->color_primaries = AVCOL_PRI_BT709;
1634 } else if (track->par->width == 720 && track->height == 576) {
1635 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1636 track->par->color_primaries = AVCOL_PRI_BT470BG;
1637 } else if (track->par->width == 720 &&
1638 (track->height == 486 || track->height == 480)) {
1639 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1640 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1641 } else {
1642 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1643 }
1644 switch (track->par->color_primaries) {
1645 case AVCOL_PRI_BT709:
1646 track->par->color_trc = AVCOL_TRC_BT709;
1647 track->par->color_space = AVCOL_SPC_BT709;
1648 break;
1649 case AVCOL_PRI_SMPTE170M:
1650 case AVCOL_PRI_BT470BG:
1651 track->par->color_trc = AVCOL_TRC_BT709;
1652 track->par->color_space = AVCOL_SPC_SMPTE170M;
1653 break;
1654 }
1655 }
1656
1657 /* We should only ever be called by MOV or MP4. */
1658 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1659
1660 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1661 ffio_wfourcc(pb, "colr");
1662 if (track->mode == MODE_MP4)
1663 ffio_wfourcc(pb, "nclx");
1664 else
1665 ffio_wfourcc(pb, "nclc");
1666 switch (track->par->color_primaries) {
1667 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1668 case AVCOL_PRI_SMPTE170M:
1669 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1670 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1671 default: avio_wb16(pb, 2);
1672 }
1673 switch (track->par->color_trc) {
1674 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1675 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1676 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1677 default: avio_wb16(pb, 2);
1678 }
1679 switch (track->par->color_space) {
1680 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1681 case AVCOL_SPC_BT470BG:
1682 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1683 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1684 default: avio_wb16(pb, 2);
1685 }
1686
1687 if (track->mode == MODE_MP4) {
1688 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1689 avio_w8(pb, full_range << 7);
1690 return 19;
1691 } else {
1692 return 18;
1693 }
1694 }
1695
1696 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1697 {
1698 AVDictionaryEntry *encoder;
1699 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1700 || (track->par->width == 1440 && track->par->height == 1080)
1701 || (track->par->width == 1920 && track->par->height == 1080);
1702
1703 if (track->mode == MODE_MOV &&
1704 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1705 av_strlcpy(compressor_name, encoder->value, 32);
1706 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1707 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1708 AVStream *st = track->st;
1709 int rate = av_q2d(find_fps(NULL, st));
1710 av_strlcatf(compressor_name, len, "XDCAM");
1711 if (track->par->format == AV_PIX_FMT_YUV422P) {
1712 av_strlcatf(compressor_name, len, " HD422");
1713 } else if(track->par->width == 1440) {
1714 av_strlcatf(compressor_name, len, " HD");
1715 } else
1716 av_strlcatf(compressor_name, len, " EX");
1717
1718 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1719
1720 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1721 }
1722 }
1723
1724 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1725 {
1726 int64_t pos = avio_tell(pb);
1727 char compressor_name[32] = { 0 };
1728 int avid = 0;
1729
1730 avio_wb32(pb, 0); /* size */
1731 if (mov->encryption_scheme != MOV_ENC_NONE) {
1732 ffio_wfourcc(pb, "encv");
1733 } else {
1734 avio_wl32(pb, track->tag); // store it byteswapped
1735 }
1736 avio_wb32(pb, 0); /* Reserved */
1737 avio_wb16(pb, 0); /* Reserved */
1738 avio_wb16(pb, 1); /* Data-reference index */
1739
1740 avio_wb16(pb, 0); /* Codec stream version */
1741 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1742 if (track->mode == MODE_MOV) {
1743 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1744 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1745 avio_wb32(pb, 0); /* Temporal Quality */
1746 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1747 } else {
1748 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1749 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1750 }
1751 } else {
1752 avio_wb32(pb, 0); /* Reserved */
1753 avio_wb32(pb, 0); /* Reserved */
1754 avio_wb32(pb, 0); /* Reserved */
1755 }
1756 avio_wb16(pb, track->par->width); /* Video width */
1757 avio_wb16(pb, track->height); /* Video height */
1758 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1759 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1760 avio_wb32(pb, 0); /* Data size (= 0) */
1761 avio_wb16(pb, 1); /* Frame count (= 1) */
1762
1763 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1764 find_compressor(compressor_name, 32, track);
1765 avio_w8(pb, strlen(compressor_name));
1766 avio_write(pb, compressor_name, 31);
1767
1768 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1769 avio_wb16(pb, track->par->bits_per_coded_sample |
1770 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1771 else
1772 avio_wb16(pb, 0x18); /* Reserved */
1773
1774 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1775 int pal_size, i;
1776 avio_wb16(pb, 0); /* Color table ID */
1777 avio_wb32(pb, 0); /* Color table seed */
1778 avio_wb16(pb, 0x8000); /* Color table flags */
1779 if (track->par->bits_per_coded_sample < 0 || track->par->bits_per_coded_sample > 8)
1780 return AVERROR(EINVAL);
1781 pal_size = 1 << track->par->bits_per_coded_sample;
1782 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1783 for (i = 0; i < pal_size; i++) {
1784 uint32_t rgb = track->palette[i];
1785 uint16_t r = (rgb >> 16) & 0xff;
1786 uint16_t g = (rgb >> 8) & 0xff;
1787 uint16_t b = rgb & 0xff;
1788 avio_wb16(pb, 0);
1789 avio_wb16(pb, (r << 8) | r);
1790 avio_wb16(pb, (g << 8) | g);
1791 avio_wb16(pb, (b << 8) | b);
1792 }
1793 } else
1794 avio_wb16(pb, 0xffff); /* Reserved */
1795
1796 if (track->tag == MKTAG('m','p','4','v'))
1797 mov_write_esds_tag(pb, track);
1798 else if (track->par->codec_id == AV_CODEC_ID_H263)
1799 mov_write_d263_tag(pb);
1800 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1801 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1802 mov_write_extradata_tag(pb, track);
1803 avio_wb32(pb, 0);
1804 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1805 mov_write_avid_tag(pb, track);
1806 avid = 1;
1807 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1808 mov_write_hvcc_tag(pb, track);
1809 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1810 mov_write_avcc_tag(pb, track);
1811 if (track->mode == MODE_IPOD)
1812 mov_write_uuid_tag_ipod(pb);
1813 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1814 mov_write_vpcc_tag(mov->fc, pb, track);
1815 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1816 mov_write_dvc1_tag(pb, track);
1817 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1818 track->par->codec_id == AV_CODEC_ID_VP6A) {
1819 /* Don't write any potential extradata here - the cropping
1820 * is signalled via the normal width/height fields. */
1821 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1822 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1823 mov_write_dpxe_tag(pb, track);
1824 } else if (track->vos_len > 0)
1825 mov_write_glbl_tag(pb, track);
1826
1827 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1828 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1829 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1830 int field_order = track->par->field_order;
1831
1832 #if FF_API_LAVF_AVCTX
1833 FF_DISABLE_DEPRECATION_WARNINGS
1834 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1835 field_order = track->st->codec->field_order;
1836 FF_ENABLE_DEPRECATION_WARNINGS
1837 #endif
1838
1839 if (field_order != AV_FIELD_UNKNOWN)
1840 mov_write_fiel_tag(pb, track, field_order);
1841 }
1842
1843 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1844 if (track->mode == MODE_MOV)
1845 mov_write_gama_tag(pb, track, mov->gamma);
1846 else
1847 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1848 }
1849 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1850 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1851 mov_write_colr_tag(pb, track);
1852 else
1853 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1854 }
1855
1856 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
1857 mov_write_pasp_tag(pb, track);
1858 }
1859
1860 if (mov->encryption_scheme != MOV_ENC_NONE) {
1861 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1862 }
1863
1864 /* extra padding for avid stsd */
1865 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1866 if (avid)
1867 avio_wb32(pb, 0);
1868
1869 return update_size(pb, pos);
1870 }
1871
1872 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1873 {
1874 int64_t pos = avio_tell(pb);
1875 avio_wb32(pb, 0); /* size */
1876 ffio_wfourcc(pb, "rtp ");
1877 avio_wb32(pb, 0); /* Reserved */
1878 avio_wb16(pb, 0); /* Reserved */
1879 avio_wb16(pb, 1); /* Data-reference index */
1880
1881 avio_wb16(pb, 1); /* Hint track version */
1882 avio_wb16(pb, 1); /* Highest compatible version */
1883 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1884
1885 avio_wb32(pb, 12); /* size */
1886 ffio_wfourcc(pb, "tims");
1887 avio_wb32(pb, track->timescale);
1888
1889 return update_size(pb, pos);
1890 }
1891
1892 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1893 {
1894 uint64_t str_size =strlen(reel_name);
1895 int64_t pos = avio_tell(pb);
1896
1897 if (str_size >= UINT16_MAX){
1898 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1899 avio_wb16(pb, 0);
1900 return AVERROR(EINVAL);
1901 }
1902
1903 avio_wb32(pb, 0); /* size */
1904 ffio_wfourcc(pb, "name"); /* Data format */
1905 avio_wb16(pb, str_size); /* string size */
1906 avio_wb16(pb, track->language); /* langcode */
1907 avio_write(pb, reel_name, str_size); /* reel name */
1908 return update_size(pb,pos);
1909 }
1910
1911 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1912 {
1913 int64_t pos = avio_tell(pb);
1914 #if 1
1915 int frame_duration;
1916 int nb_frames;
1917 AVDictionaryEntry *t = NULL;
1918
1919 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
1920 #if FF_API_LAVF_AVCTX
1921 FF_DISABLE_DEPRECATION_WARNINGS
1922 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
1923 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
1924 FF_ENABLE_DEPRECATION_WARNINGS
1925 #else
1926 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
1927 return AVERROR(EINVAL);
1928 #endif
1929 } else {
1930 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
1931 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
1932 }
1933
1934 if (nb_frames > 255) {
1935 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1936 return AVERROR(EINVAL);
1937 }
1938
1939 avio_wb32(pb, 0); /* size */
1940 ffio_wfourcc(pb, "tmcd"); /* Data format */
1941 avio_wb32(pb, 0); /* Reserved */
1942 avio_wb32(pb, 1); /* Data reference index */
1943 avio_wb32(pb, 0); /* Flags */
1944 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1945 avio_wb32(pb, track->timescale); /* Timescale */
1946 avio_wb32(pb, frame_duration); /* Frame duration */
1947 avio_w8(pb, nb_frames); /* Number of frames */
1948 avio_w8(pb, 0); /* Reserved */
1949
1950 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1951 if (t && utf8len(t->value) && track->mode != MODE_MP4)
1952 mov_write_source_reference_tag(pb, track, t->value);
1953 else
1954 avio_wb16(pb, 0); /* zero size */
1955 #else
1956
1957 avio_wb32(pb, 0); /* size */
1958 ffio_wfourcc(pb, "tmcd"); /* Data format */
1959 avio_wb32(pb, 0); /* Reserved */
1960 avio_wb32(pb, 1); /* Data reference index */
1961 if (track->par->extradata_size)
1962 avio_write(pb, track->par->extradata, track->par->extradata_size);
1963 #endif
1964 return update_size(pb, pos);
1965 }
1966
1967 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1968 {
1969 int64_t pos = avio_tell(pb);
1970 avio_wb32(pb, 0); /* size */
1971 ffio_wfourcc(pb, "stsd");
1972 avio_wb32(pb, 0); /* version & flags */
1973 avio_wb32(pb, 1); /* entry count */
1974 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
1975 mov_write_video_tag(pb, mov, track);
1976 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1977 mov_write_audio_tag(s, pb, mov, track);
1978 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1979 mov_write_subtitle_tag(pb, track);
1980 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
1981 mov_write_rtp_tag(pb, track);
1982 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
1983 mov_write_tmcd_tag(pb, track);
1984 return update_size(pb, pos);
1985 }
1986
1987 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1988 {
1989 MOVStts *ctts_entries;
1990 uint32_t entries = 0;
1991 uint32_t atom_size;
1992 int i;
1993
1994 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1995 if (!ctts_entries)
1996 return AVERROR(ENOMEM);
1997 ctts_entries[0].count = 1;
1998 ctts_entries[0].duration = track->cluster[0].cts;
1999 for (i = 1; i < track->entry; i++) {
2000 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2001 ctts_entries[entries].count++; /* compress */
2002 } else {
2003 entries++;
2004 ctts_entries[entries].duration = track->cluster[i].cts;
2005 ctts_entries[entries].count = 1;
2006 }
2007 }
2008 entries++; /* last one */
2009 atom_size = 16 + (entries * 8);
2010 avio_wb32(pb, atom_size); /* size */
2011 ffio_wfourcc(pb, "ctts");
2012 avio_wb32(pb, 0); /* version & flags */
2013 avio_wb32(pb, entries); /* entry count */
2014 for (i = 0; i < entries; i++) {
2015 avio_wb32(pb, ctts_entries[i].count);
2016 avio_wb32(pb, ctts_entries[i].duration);
2017 }
2018 av_free(ctts_entries);
2019 return atom_size;
2020 }
2021
2022 /* Time to sample atom */
2023 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2024 {
2025 MOVStts *stts_entries = NULL;
2026 uint32_t entries = -1;
2027 uint32_t atom_size;
2028 int i;
2029
2030 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2031 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2032 if (!stts_entries)
2033 return AVERROR(ENOMEM);
2034 stts_entries[0].count = track->sample_count;
2035 stts_entries[0].duration = 1;
2036 entries = 1;
2037 } else {
2038 if (track->entry) {
2039 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2040 if (!stts_entries)
2041 return AVERROR(ENOMEM);
2042 }
2043 for (i = 0; i < track->entry; i++) {
2044 int duration = get_cluster_duration(track, i);
2045 if (i && duration == stts_entries[entries].duration) {
2046 stts_entries[entries].count++; /* compress */
2047 } else {
2048 entries++;
2049 stts_entries[entries].duration = duration;
2050 stts_entries[entries].count = 1;
2051 }
2052 }
2053 entries++; /* last one */
2054 }
2055 atom_size = 16 + (entries * 8);
2056 avio_wb32(pb, atom_size); /* size */
2057 ffio_wfourcc(pb, "stts");
2058 avio_wb32(pb, 0); /* version & flags */
2059 avio_wb32(pb, entries); /* entry count */
2060 for (i = 0; i < entries; i++) {
2061 avio_wb32(pb, stts_entries[i].count);
2062 avio_wb32(pb, stts_entries[i].duration);
2063 }
2064 av_free(stts_entries);
2065 return atom_size;
2066 }
2067
2068 static int mov_write_dref_tag(AVIOContext *pb)
2069 {
2070 avio_wb32(pb, 28); /* size */
2071 ffio_wfourcc(pb, "dref");
2072 avio_wb32(pb, 0); /* version & flags */
2073 avio_wb32(pb, 1); /* entry count */
2074
2075 avio_wb32(pb, 0xc); /* size */
2076 //FIXME add the alis and rsrc atom
2077 ffio_wfourcc(pb, "url ");
2078 avio_wb32(pb, 1); /* version & flags */
2079
2080 return 28;
2081 }
2082
2083 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2084 {
2085 int64_t pos = avio_tell(pb);
2086 int ret;
2087
2088 avio_wb32(pb, 0); /* size */
2089 ffio_wfourcc(pb, "stbl");
2090 mov_write_stsd_tag(s, pb, mov, track);
2091 mov_write_stts_tag(pb, track);
2092 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2093 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2094 track->has_keyframes && track->has_keyframes < track->entry)
2095 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2096 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2097 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2098 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2099 track->flags & MOV_TRACK_CTTS && track->entry) {
2100
2101 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2102 return ret;
2103 }
2104 mov_write_stsc_tag(pb, track);
2105 mov_write_stsz_tag(pb, track);
2106 mov_write_stco_tag(pb, track);
2107 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
2108 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2109 }
2110 return update_size(pb, pos);
2111 }
2112
2113 static int mov_write_dinf_tag(AVIOContext *pb)
2114 {
2115 int64_t pos = avio_tell(pb);
2116 avio_wb32(pb, 0); /* size */
2117 ffio_wfourcc(pb, "dinf");
2118 mov_write_dref_tag(pb);
2119 return update_size(pb, pos);
2120 }
2121
2122 static int mov_write_nmhd_tag(AVIOContext *pb)
2123 {
2124 avio_wb32(pb, 12);
2125 ffio_wfourcc(pb, "nmhd");
2126 avio_wb32(pb, 0);
2127 return 12;
2128 }
2129
2130 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2131 {
2132 int64_t pos = avio_tell(pb);
2133 const char *font = "Lucida Grande";
2134 avio_wb32(pb, 0); /* size */
2135 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2136 avio_wb32(pb, 0); /* version & flags */
2137 avio_wb16(pb, 0); /* text font */
2138 avio_wb16(pb, 0); /* text face */
2139 avio_wb16(pb, 12); /* text size */
2140 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2141 avio_wb16(pb, 0x0000); /* text color (red) */
2142 avio_wb16(pb, 0x0000); /* text color (green) */
2143 avio_wb16(pb, 0x0000); /* text color (blue) */
2144 avio_wb16(pb, 0xffff); /* background color (red) */
2145 avio_wb16(pb, 0xffff); /* background color (green) */
2146 avio_wb16(pb, 0xffff); /* background color (blue) */
2147 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2148 avio_write(pb, font, strlen(font)); /* font name */
2149 return update_size(pb, pos);
2150 }
2151
2152 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2153 {
2154 int64_t pos = avio_tell(pb);
2155 avio_wb32(pb, 0); /* size */
2156 ffio_wfourcc(pb, "gmhd");
2157 avio_wb32(pb, 0x18); /* gmin size */
2158 ffio_wfourcc(pb, "gmin");/* generic media info */
2159 avio_wb32(pb, 0); /* version & flags */
2160 avio_wb16(pb, 0x40); /* graphics mode = */
2161 avio_wb16(pb, 0x8000); /* opColor (r?) */
2162 avio_wb16(pb, 0x8000); /* opColor (g?) */
2163 avio_wb16(pb, 0x8000); /* opColor (b?) */
2164 avio_wb16(pb, 0); /* balance */
2165 avio_wb16(pb, 0); /* reserved */
2166
2167 /*
2168 * This special text atom is required for
2169 * Apple Quicktime chapters. The contents
2170 * don't appear to be documented, so the
2171 * bytes are copied verbatim.
2172 */
2173 if (track->tag != MKTAG('c','6','0','8')) {
2174 avio_wb32(pb, 0x2C); /* size */
2175 ffio_wfourcc(pb, "text");
2176 avio_wb16(pb, 0x01);
2177 avio_wb32(pb, 0x00);
2178 avio_wb32(pb, 0x00);
2179 avio_wb32(pb, 0x00);
2180 avio_wb32(pb, 0x01);
2181 avio_wb32(pb, 0x00);
2182 avio_wb32(pb, 0x00);
2183 avio_wb32(pb, 0x00);
2184 avio_wb32(pb, 0x00004000);
2185 avio_wb16(pb, 0x0000);
2186 }
2187
2188 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2189 int64_t tmcd_pos = avio_tell(pb);
2190 avio_wb32(pb, 0); /* size */
2191 ffio_wfourcc(pb, "tmcd");
2192 mov_write_tcmi_tag(pb, track);
2193 update_size(pb, tmcd_pos);
2194 }
2195 return update_size(pb, pos);
2196 }
2197
2198 static int mov_write_smhd_tag(AVIOContext *pb)
2199 {
2200 avio_wb32(pb, 16); /* size */
2201 ffio_wfourcc(pb, "smhd");
2202 avio_wb32(pb, 0); /* version & flags */
2203 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2204 avio_wb16(pb, 0); /* reserved */
2205 return 16;
2206 }
2207
2208 static int mov_write_vmhd_tag(AVIOContext *pb)
2209 {
2210 avio_wb32(pb, 0x14); /* size (always 0x14) */
2211 ffio_wfourcc(pb, "vmhd");
2212 avio_wb32(pb, 0x01); /* version & flags */
2213 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2214 return 0x14;
2215 }
2216
2217 static int is_clcp_track(MOVTrack *track)
2218 {
2219 return track->tag == MKTAG('c','7','0','8') ||
2220 track->tag == MKTAG('c','6','0','8');
2221 }
2222
2223 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2224 {
2225 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2226 int64_t pos = avio_tell(pb);
2227
2228 hdlr = "dhlr";
2229 hdlr_type = "url ";
2230 descr = "DataHandler";
2231
2232 if (track) {
2233 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2234 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2235 hdlr_type = "vide";
2236 descr = "VideoHandler";
2237 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2238 hdlr_type = "soun";
2239 descr = "SoundHandler";
2240 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2241 if (is_clcp_track(track)) {
2242 hdlr_type = "clcp";
2243 descr = "ClosedCaptionHandler";
2244 } else {
2245 if (track->tag == MKTAG('t','x','3','g')) {
2246 hdlr_type = "sbtl";
2247 } else if (track->tag == MKTAG('m','p','4','s')) {
2248 hdlr_type = "subp";
2249 } else {
2250 hdlr_type = "text";
2251 }
2252 descr = "SubtitleHandler";
2253 }
2254 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2255 hdlr_type = "hint";
2256 descr = "HintHandler";
2257 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2258 hdlr_type = "tmcd";
2259 descr = "TimeCodeHandler";
2260 } else {
2261 char tag_buf[32];
2262 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
2263 track->par->codec_tag);
2264
2265 av_log(s, AV_LOG_WARNING,
2266 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
2267 tag_buf, track->par->codec_tag);
2268 }
2269 if (track->st) {
2270 // hdlr.name is used by some players to identify the content title
2271 // of the track. So if an alternate handler description is
2272 // specified, use it.
2273 AVDictionaryEntry *t;
2274 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2275 if (t && utf8len(t->value))
2276 descr = t->value;
2277 }
2278 }
2279
2280 avio_wb32(pb, 0); /* size */
2281 ffio_wfourcc(pb, "hdlr");
2282 avio_wb32(pb, 0); /* Version & flags */
2283 avio_write(pb, hdlr, 4); /* handler */
2284 ffio_wfourcc(pb, hdlr_type); /* handler type */
2285 avio_wb32(pb, 0); /* reserved */
2286 avio_wb32(pb, 0); /* reserved */
2287 avio_wb32(pb, 0); /* reserved */
2288 if (!track || track->mode == MODE_MOV)
2289 avio_w8(pb, strlen(descr)); /* pascal string */
2290 avio_write(pb, descr, strlen(descr)); /* handler description */
2291 if (track && track->mode != MODE_MOV)
2292 avio_w8(pb, 0); /* c string */
2293 return update_size(pb, pos);
2294 }
2295
2296 static int mov_write_hmhd_tag(AVIOContext *pb)
2297 {
2298 /* This atom must be present, but leaving the values at zero
2299 * seems harmless. */
2300 avio_wb32(pb, 28); /* size */
2301 ffio_wfourcc(pb, "hmhd");
2302 avio_wb32(pb, 0); /* version, flags */
2303 avio_wb16(pb, 0); /* maxPDUsize */
2304 avio_wb16(pb, 0); /* avgPDUsize */
2305 avio_wb32(pb, 0); /* maxbitrate */
2306 avio_wb32(pb, 0); /* avgbitrate */
2307 avio_wb32(pb, 0); /* reserved */
2308 return 28;
2309 }
2310
2311 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2312 {
2313 int64_t pos = avio_tell(pb);
2314 int ret;
2315
2316 avio_wb32(pb, 0); /* size */
2317 ffio_wfourcc(pb, "minf");
2318 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2319 mov_write_vmhd_tag(pb);
2320 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2321 mov_write_smhd_tag(pb);
2322 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2323 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2324 mov_write_gmhd_tag(pb, track);
2325 } else {
2326 mov_write_nmhd_tag(pb);
2327 }
2328 } else if (track->tag == MKTAG('r','t','p',' ')) {
2329 mov_write_hmhd_tag(pb);
2330 } else if (track->tag == MKTAG('t','m','c','d')) {
2331 if (track->mode != MODE_MOV)
2332 mov_write_nmhd_tag(pb);
2333 else
2334 mov_write_gmhd_tag(pb, track);
2335 }
2336 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2337 mov_write_hdlr_tag(s, pb, NULL);
2338 mov_write_dinf_tag(pb);
2339 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2340 return ret;
2341 return update_size(pb, pos);
2342 }
2343
2344 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2345 MOVTrack *track)
2346 {
2347 int version = track->track_duration < INT32_MAX ? 0 : 1;
2348
2349 if (track->mode == MODE_ISM)
2350 version = 1;
2351
2352 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2353 ffio_wfourcc(pb, "mdhd");
2354 avio_w8(pb, version);
2355 avio_wb24(pb, 0); /* flags */
2356 if (version == 1) {
2357 avio_wb64(pb, track->time);
2358 avio_wb64(pb, track->time);
2359 } else {
2360 avio_wb32(pb, track->time); /* creation time */
2361 avio_wb32(pb, track->time); /* modification time */
2362 }
2363 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2364 if (!track->entry && mov->mode == MODE_ISM)
2365 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2366 else if (!track->entry)
2367 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2368 else
2369 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2370 avio_wb16(pb, track->language); /* language */
2371 avio_wb16(pb, 0); /* reserved (quality) */
2372
2373 if (version != 0 && track->mode == MODE_MOV) {
2374 av_log(NULL, AV_LOG_ERROR,
2375 "FATAL error, file duration too long for timebase, this file will not be\n"
2376 "playable with quicktime. Choose a different timebase or a different\n"
2377 "container format\n");
2378 }
2379
2380 return 32;
2381 }
2382
2383 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2384 MOVMuxContext *mov, MOVTrack *track)
2385 {
2386 int64_t pos = avio_tell(pb);
2387 int ret;
2388
2389 avio_wb32(pb, 0); /* size */
2390 ffio_wfourcc(pb, "mdia");
2391 mov_write_mdhd_tag(pb, mov, track);
2392 mov_write_hdlr_tag(s, pb, track);
2393 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2394 return ret;
2395 return update_size(pb, pos);
2396 }
2397
2398 /* transformation matrix
2399 |a b u|
2400 |c d v|
2401 |tx ty w| */
2402 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2403 int16_t d, int16_t tx, int16_t ty)
2404 {
2405 avio_wb32(pb, a << 16); /* 16.16 format */
2406 avio_wb32(pb, b << 16); /* 16.16 format */
2407 avio_wb32(pb, 0); /* u in 2.30 format */
2408 avio_wb32(pb, c << 16); /* 16.16 format */
2409 avio_wb32(pb, d << 16); /* 16.16 format */
2410 avio_wb32(pb, 0); /* v in 2.30 format */
2411 avio_wb32(pb, tx << 16); /* 16.16 format */
2412 avio_wb32(pb, ty << 16); /* 16.16 format */
2413 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2414 }
2415
2416 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2417 MOVTrack *track, AVStream *st)
2418 {
2419 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2420 track->timescale, AV_ROUND_UP);
2421 int version = duration < INT32_MAX ? 0 : 1;
2422 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2423 int rotation = 0;
2424 int group = 0;
2425
2426 uint32_t *display_matrix = NULL;
2427 int display_matrix_size, i;
2428
2429 if (st) {
2430 if (mov->per_stream_grouping)
2431 group = st->index;
2432 else
2433 group = st->codecpar->codec_type;
2434
2435 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2436 &display_matrix_size);
2437 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2438 display_matrix = NULL;
2439 }
2440
2441 if (track->flags & MOV_TRACK_ENABLED)
2442 flags |= MOV_TKHD_FLAG_ENABLED;
2443
2444 if (track->mode == MODE_ISM)
2445 version = 1;
2446
2447 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2448 ffio_wfourcc(pb, "tkhd");
2449 avio_w8(pb, version);
2450 avio_wb24(pb, flags);
2451 if (version == 1) {
2452 avio_wb64(pb, track->time);
2453 avio_wb64(pb, track->time);
2454 } else {
2455 avio_wb32(pb, track->time); /* creation time */
2456 avio_wb32(pb, track->time); /* modification time */
2457 }
2458 avio_wb32(pb, track->track_id); /* track-id */
2459 avio_wb32(pb, 0); /* reserved */
2460 if (!track->entry && mov->mode == MODE_ISM)
2461 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2462 else if (!track->entry)
2463 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2464 else
2465 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2466
2467 avio_wb32(pb, 0); /* reserved */
2468 avio_wb32(pb, 0); /* reserved */
2469 avio_wb16(pb, 0); /* layer */
2470 avio_wb16(pb, group); /* alternate group) */
2471 /* Volume, only for audio */
2472 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2473 avio_wb16(pb, 0x0100);
2474 else
2475 avio_wb16(pb, 0);
2476 avio_wb16(pb, 0); /* reserved */
2477
2478 /* Matrix structure */
2479 if (st && st->metadata) {
2480 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2481 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2482 }
2483 if (display_matrix) {
2484 for (i = 0; i < 9; i++)
2485 avio_wb32(pb, display_matrix[i]);
2486 } else if (rotation == 90) {
2487 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2488 } else if (rotation == 180) {
2489 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2490 } else if (rotation == 270) {
2491 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2492 } else {
2493 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2494 }
2495 /* Track width and height, for visual only */
2496 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2497 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2498 int64_t track_width_1616;
2499 if (track->mode == MODE_MOV) {
2500 track_width_1616 = track->par->width * 0x10000ULL;
2501 } else {
2502 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2503 track->par->width * 0x10000LL,
2504 st->sample_aspect_ratio.den);
2505 if (!track_width_1616 ||
2506 track->height != track->par->height ||
2507 track_width_1616 > UINT32_MAX)
2508 track_width_1616 = track->par->width * 0x10000ULL;
2509 }
2510 if (track_width_1616 > UINT32_MAX) {
2511 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2512 track_width_1616 = 0;
2513 }
2514 avio_wb32(pb, track_width_1616);
2515 if (track->height > 0xFFFF) {
2516 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2517 avio_wb32(pb, 0);
2518 } else
2519 avio_wb32(pb, track->height * 0x10000U);
2520 } else {
2521 avio_wb32(pb, 0);
2522 avio_wb32(pb, 0);
2523 }
2524 return 0x5c;
2525 }
2526
2527 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2528 {
2529 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2530 track->par->sample_aspect_ratio.den);
2531
2532 int64_t pos = avio_tell(pb);
2533
2534 avio_wb32(pb, 0); /* size */
2535 ffio_wfourcc(pb, "tapt");
2536
2537 avio_wb32(pb, 20);
2538 ffio_wfourcc(pb, "clef");
2539 avio_wb32(pb, 0);
2540 avio_wb32(pb, width << 16);
2541 avio_wb32(pb, track->par->height << 16);
2542
2543 avio_wb32(pb, 20);
2544 ffio_wfourcc(pb, "prof");
2545 avio_wb32(pb, 0);
2546 avio_wb32(pb, width << 16);
2547 avio_wb32(pb, track->par->height << 16);
2548
2549 avio_wb32(pb, 20);
2550 ffio_wfourcc(pb, "enof");
2551 avio_wb32(pb, 0);
2552 avio_wb32(pb, track->par->width << 16);
2553 avio_wb32(pb, track->par->height << 16);
2554
2555 return update_size(pb, pos);
2556 }
2557
2558 // This box seems important for the psp playback ... without it the movie seems to hang
2559 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2560 MOVTrack *track)
2561 {
2562 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2563 track->timescale, AV_ROUND_UP);
2564 int version = duration < INT32_MAX ? 0 : 1;
2565 int entry_size, entry_count, size;
2566 int64_t delay, start_ct = track->start_cts;
2567 int64_t start_dts = track->start_dts;
2568
2569 if (track->entry) {
2570 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2571
2572 av_log(mov->fc, AV_LOG_DEBUG,
2573 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2574 track->cluster[0].dts, track->cluster[0].cts,
2575 start_dts, start_ct, track->track_id);
2576 start_dts = track->cluster[0].dts;
2577 start_ct = track->cluster[0].cts;
2578 }
2579 }
2580
2581 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2582 track->timescale, AV_ROUND_DOWN);
2583 version |= delay < INT32_MAX ? 0 : 1;
2584
2585 entry_size = (version == 1) ? 20 : 12;
2586 entry_count = 1 + (delay > 0);
2587 size = 24 + entry_count * entry_size;
2588
2589 /* write the atom data */
2590 avio_wb32(pb, size);
2591 ffio_wfourcc(pb, "edts");
2592 avio_wb32(pb, size - 8);
2593 ffio_wfourcc(pb, "elst");
2594 avio_w8(pb, version);
2595 avio_wb24(pb, 0); /* flags */
2596
2597 avio_wb32(pb, entry_count);
2598 if (delay > 0) { /* add an empty edit to delay presentation */
2599 /* In the positive delay case, the delay includes the cts
2600 * offset, and the second edit list entry below trims out
2601 * the same amount from the actual content. This makes sure
2602 * that the offset last sample is included in the edit
2603 * list duration as well. */
2604 if (version == 1) {
2605 avio_wb64(pb, delay);
2606 avio_wb64(pb, -1);
2607 } else {
2608 avio_wb32(pb, delay);
2609 avio_wb32(pb, -1);
2610 }
2611 avio_wb32(pb, 0x00010000);
2612 } else {
2613 /* Avoid accidentally ending up with start_ct = -1 which has got a
2614 * special meaning. Normally start_ct should end up positive or zero
2615 * here, but use FFMIN in case dts is a small positive integer
2616 * rounded to 0 when represented in MOV_TIMESCALE units. */
2617 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2618 start_ct = -FFMIN(start_dts, 0);
2619 /* Note, this delay is calculated from the pts of the first sample,
2620 * ensuring that we don't reduce the duration for cases with
2621 * dts<0 pts=0. */
2622 duration += delay;
2623 }
2624
2625 /* For fragmented files, we don't know the full length yet. Setting
2626 * duration to 0 allows us to only specify the offset, including
2627 * the rest of the content (from all future fragments) without specifying
2628 * an explicit duration. */
2629 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2630 duration = 0;
2631
2632 /* duration */
2633 if (version == 1) {
2634 avio_wb64(pb, duration);
2635 avio_wb64(pb, start_ct);
2636 } else {
2637 avio_wb32(pb, duration);
2638 avio_wb32(pb, start_ct);
2639 }
2640 avio_wb32(pb, 0x00010000);
2641 return size;
2642 }
2643
2644 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2645 {
2646 avio_wb32(pb, 20); // size
2647 ffio_wfourcc(pb, "tref");
2648 avio_wb32(pb, 12); // size (subatom)
2649 avio_wl32(pb, track->tref_tag);
2650 avio_wb32(pb, track->tref_id);
2651 return 20;
2652 }
2653
2654 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2655 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2656 {
2657 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2658 ffio_wfourcc(pb, "uuid");
2659 ffio_wfourcc(pb, "USMT");
2660 avio_wb32(pb, 0x21d24fce);
2661 avio_wb32(pb, 0xbb88695c);
2662 avio_wb32(pb, 0xfac9c740);
2663 avio_wb32(pb, 0x1c); // another size here!
2664 ffio_wfourcc(pb, "MTDT");
2665 avio_wb32(pb, 0x00010012);
2666 avio_wb32(pb, 0x0a);
2667 avio_wb32(pb, 0x55c40000);
2668 avio_wb32(pb, 0x1);
2669 avio_wb32(pb, 0x0);
2670 return 0x34;
2671 }
2672
2673 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2674 {
2675 AVFormatContext *ctx = track->rtp_ctx;
2676 char buf[1000] = "";
2677 int len;
2678
2679 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2680 NULL, NULL, 0, 0, ctx);
2681 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2682 len = strlen(buf);
2683
2684 avio_wb32(pb, len + 24);
2685 ffio_wfourcc(pb, "udta");
2686 avio_wb32(pb, len + 16);
2687 ffio_wfourcc(pb, "hnti");
2688 avio_wb32(pb, len + 8);
2689 ffio_wfourcc(pb, "sdp ");
2690 avio_write(pb, buf, len);
2691 return len + 24;
2692 }
2693
2694 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2695 const char *tag, const char *str)
2696 {
2697 int64_t pos = avio_tell(pb);
2698 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2699 if (!t || !utf8len(t->value))
2700 return 0;
2701
2702 avio_wb32(pb, 0); /* size */
2703 ffio_wfourcc(pb, tag); /* type */
2704 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2705 return update_size(pb, pos);
2706 }
2707
2708 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2709 AVStream *st)
2710 {
2711 AVIOContext *pb_buf;
2712 int ret, size;
2713 uint8_t *buf;
2714
2715 if (!st)
2716 return 0;
2717
2718 ret = avio_open_dyn_buf(&pb_buf);
2719 if (ret < 0)
2720 return ret;
2721
2722 if (mov->mode & MODE_MP4)
2723 mov_write_track_metadata(pb_buf, st, "name", "title");
2724
2725 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2726 avio_wb32(pb, size + 8);
2727 ffio_wfourcc(pb, "udta");
2728 avio_write(pb, buf, size);
2729 }
2730 av_free(buf);
2731
2732 return 0;
2733 }
2734
2735 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2736 MOVTrack *track, AVStream *st)
2737 {
2738 int64_t pos = avio_tell(pb);
2739 int entry_backup = track->entry;
2740 int chunk_backup = track->chunkCount;
2741 int ret;
2742
2743 /* If we want to have an empty moov, but some samples already have been
2744 * buffered (delay_moov), pretend that no samples have been written yet. */
2745 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2746 track->chunkCount = track->entry = 0;
2747
2748 avio_wb32(pb, 0); /* size */
2749 ffio_wfourcc(pb, "trak");
2750 mov_write_tkhd_tag(pb, mov, track, st);
2751
2752 av_assert2(mov->use_editlist >= 0);
2753
2754 if (track->start_dts != AV_NOPTS_VALUE) {
2755 if (mov->use_editlist)
2756 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2757 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2758 av_log(mov->fc, AV_LOG_WARNING,
2759 "Not writing any edit list even though one would have been required\n");
2760 }
2761
2762 if (track->tref_tag)
2763 mov_write_tref_tag(pb, track);
2764
2765 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
2766 return ret;
2767 if (track->mode == MODE_PSP)
2768 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2769 if (track->tag == MKTAG('r','t','p',' '))
2770 mov_write_udta_sdp(pb, track);
2771 if (track->mode == MODE_MOV) {
2772 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2773 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2774 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2775 mov_write_tapt_tag(pb, track);
2776 }
2777 }
2778 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2779 mov_write_tapt_tag(pb, track);
2780 }
2781 }
2782 mov_write_track_udta_tag(pb, mov, st);
2783 track->entry = entry_backup;
2784 track->chunkCount = chunk_backup;
2785 return update_size(pb, pos);
2786 }
2787
2788 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2789 {
2790 int i, has_audio = 0, has_video = 0;
2791 int64_t pos = avio_tell(pb);
2792 int audio_profile = mov->iods_audio_profile;
2793 int video_profile = mov->iods_video_profile;
2794 for (i = 0; i < mov->nb_streams; i++) {
2795 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2796 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
2797 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
2798 }
2799 }
2800 if (audio_profile < 0)
2801 audio_profile = 0xFF - has_audio;
2802 if (video_profile < 0)
2803 video_profile = 0xFF - has_video;
2804 avio_wb32(pb, 0x0); /* size */
2805 ffio_wfourcc(pb, "iods");
2806 avio_wb32(pb, 0); /* version & flags */
2807 put_descr(pb, 0x10, 7);
2808 avio_wb16(pb, 0x004f);
2809 avio_w8(pb, 0xff);
2810 avio_w8(pb, 0xff);
2811 avio_w8(pb, audio_profile);
2812 avio_w8(pb, video_profile);
2813 avio_w8(pb, 0xff);
2814 return update_size(pb, pos);
2815 }
2816
2817 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2818 {
2819 avio_wb32(pb, 0x20); /* size */
2820 ffio_wfourcc(pb, "trex");
2821 avio_wb32(pb, 0); /* version & flags */
2822 avio_wb32(pb, track->track_id); /* track ID */
2823 avio_wb32(pb, 1); /* default sample description index */
2824 avio_wb32(pb, 0); /* default sample duration */
2825 avio_wb32(pb, 0); /* default sample size */
2826 avio_wb32(pb, 0); /* default sample flags */
2827 return 0;
2828 }
2829
2830 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2831 {
2832 int64_t pos = avio_tell(pb);
2833 int i;
2834 avio_wb32(pb, 0x0); /* size */
2835 ffio_wfourcc(pb, "mvex");
2836 for (i = 0; i < mov->nb_streams; i++)
2837 mov_write_trex_tag(pb, &mov->tracks[i]);
2838 return update_size(pb, pos);
2839 }
2840
2841 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2842 {
2843 int max_track_id = 1, i;
2844 int64_t max_track_len = 0;
2845 int version;
2846
2847 for (i = 0; i < mov->nb_streams; i++) {
2848 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2849 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2850 MOV_TIMESCALE,
2851 mov->tracks[i].timescale,
2852 AV_ROUND_UP);
2853 if (max_track_len < max_track_len_temp)
2854 max_track_len = max_track_len_temp;
2855 if (max_track_id < mov->tracks[i].track_id)
2856 max_track_id = mov->tracks[i].track_id;
2857 }
2858 }
2859 /* If using delay_moov, make sure the output is the same as if no
2860 * samples had been written yet. */
2861 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2862 max_track_len = 0;
2863 max_track_id = 1;
2864 }
2865
2866 version = max_track_len < UINT32_MAX ? 0 : 1;
2867 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
2868
2869 ffio_wfourcc(pb, "mvhd");
2870 avio_w8(pb, version);
2871 avio_wb24(pb, 0); /* flags */
2872 if (version == 1) {
2873 avio_wb64(pb, mov->time);
2874 avio_wb64(pb, mov->time);
2875 } else {
2876 avio_wb32(pb, mov->time); /* creation time */
2877 avio_wb32(pb, mov->time); /* modification time */
2878 }
2879 avio_wb32(pb, MOV_TIMESCALE);
2880 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2881
2882 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2883 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2884 avio_wb16(pb, 0); /* reserved */
2885 avio_wb32(pb, 0); /* reserved */
2886 avio_wb32(pb, 0); /* reserved */
2887
2888 /* Matrix structure */
2889 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2890
2891 avio_wb32(pb, 0); /* reserved (preview time) */
2892 avio_wb32(pb, 0); /* reserved (preview duration) */
2893 avio_wb32(pb, 0); /* reserved (poster time) */
2894 avio_wb32(pb, 0); /* reserved (selection time) */
2895 avio_wb32(pb, 0); /* reserved (selection duration) */
2896 avio_wb32(pb, 0); /* reserved (current time) */
2897 avio_wb32(pb, max_track_id + 1); /* Next track id */
2898 return 0x6c;
2899 }
2900
2901 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2902 AVFormatContext *s)
2903 {
2904 avio_wb32(pb, 33); /* size */
2905 ffio_wfourcc(pb, "hdlr");
2906 avio_wb32(pb, 0);
2907 avio_wb32(pb, 0);
2908 ffio_wfourcc(pb, "mdir");
2909 ffio_wfourcc(pb, "appl");
2910 avio_wb32(pb, 0);
2911 avio_wb32(pb, 0);
2912 avio_w8(pb, 0);
2913 return 33;
2914 }
2915
2916 /* helper function to write a data tag with the specified string as data */
2917 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2918 {
2919 if (long_style) {
2920 int size = 16 + strlen(data);
2921 avio_wb32(pb, size); /* size */
2922 ffio_wfourcc(pb, "data");
2923 avio_wb32(pb, 1);
2924 avio_wb32(pb, 0);
2925 avio_write(pb, data, strlen(data));
2926 return size;
2927 } else {
2928 if (!lang)
2929 lang = ff_mov_iso639_to_lang("und", 1);
2930 avio_wb16(pb, strlen(data)); /* string length */
2931 avio_wb16(pb, lang);
2932 avio_write(pb, data, strlen(data));
2933 return strlen(data) + 4;
2934 }
2935 }
2936
2937 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2938 const char *value, int lang, int long_style)
2939 {
2940 int size = 0;
2941 if (value && value[0]) {
2942 int64_t pos = avio_tell(pb);
2943 avio_wb32(pb, 0); /* size */
2944 ffio_wfourcc(pb, name);
2945 mov_write_string_data_tag(pb, value, lang, long_style);
2946 size = update_size(pb, pos);
2947 }
2948 return size;
2949 }
2950
2951 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
2952 const char *tag, int *lang)
2953 {
2954 int l, len, len2;
2955 AVDictionaryEntry *t, *t2 = NULL;
2956 char tag2[16];
2957
2958 *lang = 0;
2959
2960 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2961 return NULL;
2962
2963 len = strlen(t->key);
2964 snprintf(tag2, sizeof(tag2), "%s-", tag);
2965 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2966 len2 = strlen(t2->key);
2967 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2968 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2969 *lang = l;
2970 return t;
2971 }
2972 }
2973 return t;
2974 }
2975
2976 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2977 const char *name, const char *tag,
2978 int long_style)
2979 {
2980 int lang;
2981 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
2982 if (!t)
2983 return 0;
2984 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2985 }
2986
2987 /* iTunes bpm number */
2988 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2989 {
2990 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2991 int size = 0, tmpo = t ? atoi(t->value) : 0;
2992 if (tmpo) {
2993 size = 26;
2994 avio_wb32(pb, size);
2995 ffio_wfourcc(pb, "tmpo");
2996 avio_wb32(pb, size-8); /* size */
2997 ffio_wfourcc(pb, "data");
2998 avio_wb32(pb, 0x15); //type specifier
2999 avio_wb32(pb, 0);
3000 avio_wb16(pb, tmpo); // data
3001 }
3002 return size;
3003 }
3004
3005 /* 3GPP TS 26.244 */
3006 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3007 {
3008 int lang;
3009 int64_t pos = avio_tell(pb);
3010 double latitude, longitude, altitude;
3011 int32_t latitude_fix, longitude_fix, altitude_fix;
3012 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3013 const char *ptr, *place = "";
3014 char *end;
3015 static const char *astronomical_body = "earth";
3016 if (!t)
3017 return 0;
3018
3019 ptr = t->value;
3020 longitude = strtod(ptr, &end);
3021 if (end == ptr) {
3022 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3023 return 0;
3024 }
3025 ptr = end;
3026 latitude = strtod(ptr, &end);
3027 if (end == ptr) {
3028 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3029 return 0;
3030 }
3031 ptr = end;
3032 altitude = strtod(ptr, &end);
3033 /* If no altitude was present, the default 0 should be fine */
3034 if (*end == '/')
3035 place = end + 1;
3036
3037 latitude_fix = (int32_t) ((1 << 16) * latitude);
3038 longitude_fix = (int32_t) ((1 << 16) * longitude);
3039 altitude_fix = (int32_t) ((1 << 16) * altitude);
3040
3041 avio_wb32(pb, 0); /* size */
3042 ffio_wfourcc(pb, "loci"); /* type */
3043 avio_wb32(pb, 0); /* version + flags */
3044 avio_wb16(pb, lang);
3045 avio_write(pb, place, strlen(place) + 1);
3046 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3047 avio_wb32(pb, latitude_fix);
3048 avio_wb32(pb, longitude_fix);
3049 avio_wb32(pb, altitude_fix);
3050 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3051 avio_w8(pb, 0); /* additional notes, null terminated string */
3052
3053 return update_size(pb, pos);
3054 }
3055
3056 /* iTunes track or disc number */
3057 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3058 AVFormatContext *s, int disc)
3059 {
3060 AVDictionaryEntry *t = av_dict_get(s->metadata,
3061 disc ? "disc" : "track",
3062 NULL, 0);
3063 int size = 0, track = t ? atoi(t->value) : 0;
3064 if (track) {
3065 int tracks = 0;
3066 char *slash = strchr(t->value, '/');
3067 if (slash)
3068 tracks = atoi(slash + 1);
3069 avio_wb32(pb, 32); /* size */
3070 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3071 avio_wb32(pb, 24); /* size */
3072 ffio_wfourcc(pb, "data");
3073 avio_wb32(pb, 0); // 8 bytes empty
3074 avio_wb32(pb, 0);
3075 avio_wb16(pb, 0); // empty
3076 avio_wb16(pb, track); // track / disc number
3077 avio_wb16(pb, tracks); // total track / disc number
3078 avio_wb16(pb, 0); // empty
3079 size = 32;
3080 }
3081 return size;
3082 }
3083
3084 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3085 const char *name, const char *tag,
3086 int len)
3087 {
3088 AVDictionaryEntry *t = NULL;
3089 uint8_t num;
3090 int size = 24 + len;
3091
3092 if (len != 1 && len != 4)
3093 return -1;
3094
3095 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3096 return 0;
3097 num = atoi(t->value);
3098
3099 avio_wb32(pb, size);
3100 ffio_wfourcc(pb, name);
3101 avio_wb32(pb, size - 8);
3102 ffio_wfourcc(pb, "data");
3103 avio_wb32(pb, 0x15);
3104 avio_wb32(pb, 0);
3105 if (len==4) avio_wb32(pb, num);
3106 else avio_w8 (pb, num);
3107
3108 return size;
3109 }
3110
3111 /* iTunes meta data list */
3112 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3113 AVFormatContext *s)
3114 {
3115 int64_t pos = avio_tell(pb);
3116 avio_wb32(pb, 0); /* size */
3117 ffio_wfourcc(pb, "ilst");
3118 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3119 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3120 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3121 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3122 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3123 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3124 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3125 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3126 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3127 }
3128 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3129 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3130 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3131 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3132 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3133 mov_write_string_metadata(s, pb, "desc", "description",1);
3134 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3135 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3136 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3137 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3138 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3139 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3140 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3141 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3142 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3143 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3144 mov_write_trkn_tag(pb, mov, s, 0); // track number
3145 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3146 mov_write_tmpo_tag(pb, s);
3147 return update_size(pb, pos);
3148 }
3149
3150 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3151 AVFormatContext *s)
3152 {
3153 avio_wb32(pb, 33); /* size */
3154 ffio_wfourcc(pb, "hdlr");
3155 avio_wb32(pb, 0);
3156 avio_wb32(pb, 0);
3157 ffio_wfourcc(pb, "mdta");
3158 avio_wb32(pb, 0);
3159 avio_wb32(pb, 0);
3160 avio_wb32(pb, 0);
3161 avio_w8(pb, 0);
3162 return 33;
3163 }
3164
3165 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3166 AVFormatContext *s)
3167 {
3168 AVDictionaryEntry *t = NULL;
3169 int64_t pos = avio_tell(pb);
3170 int64_t curpos, entry_pos;
3171 int count = 0;
3172
3173 avio_wb32(pb, 0); /* size */
3174 ffio_wfourcc(pb, "keys");
3175 avio_wb32(pb, 0);
3176 entry_pos = avio_tell(pb);
3177 avio_wb32(pb, 0); /* entry count */
3178
3179 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3180 avio_wb32(pb, strlen(t->key) + 8);
3181 ffio_wfourcc(pb, "mdta");
3182 avio_write(pb, t->key, strlen(t->key));
3183 count += 1;
3184 }
3185 curpos = avio_tell(pb);
3186 avio_seek(pb, entry_pos, SEEK_SET);
3187 avio_wb32(pb, count); // rewrite entry count
3188 avio_seek(pb, curpos, SEEK_SET);
3189
3190 return update_size(pb, pos);
3191 }
3192
3193 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3194 AVFormatContext *s)
3195 {
3196 AVDictionaryEntry *t = NULL;
3197 int64_t pos = avio_tell(pb);
3198 int count = 1; /* keys are 1-index based */
3199
3200 avio_wb32(pb, 0); /* size */
3201 ffio_wfourcc(pb, "ilst");
3202
3203 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3204 int64_t entry_pos = avio_tell(pb);
3205 avio_wb32(pb, 0); /* size */
3206 avio_wb32(pb, count); /* key */
3207 mov_write_string_data_tag(pb, t->value, 0, 1);
3208 update_size(pb, entry_pos);
3209 count += 1;
3210 }
3211 return update_size(pb, pos);
3212 }
3213
3214 /* meta data tags */
3215 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3216 AVFormatContext *s)
3217 {
3218 int size = 0;
3219 int64_t pos = avio_tell(pb);
3220 avio_wb32(pb, 0); /* size */
3221 ffio_wfourcc(pb, "meta");
3222 avio_wb32(pb, 0);
3223 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3224 mov_write_mdta_hdlr_tag(pb, mov, s);
3225 mov_write_mdta_keys_tag(pb, mov, s);
3226 mov_write_mdta_ilst_tag(pb, mov, s);
3227 }
3228 else {
3229 /* iTunes metadata tag */
3230 mov_write_itunes_hdlr_tag(pb, mov, s);
3231 mov_write_ilst_tag(pb, mov, s);
3232 }
3233 size = update_size(pb, pos);
3234 return size;
3235 }
3236
3237 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3238 const char *name, const char *key)
3239 {
3240 int len;
3241 AVDictionaryEntry *t;
3242
3243 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3244 return 0;
3245
3246 len = strlen(t->value);
3247 if (len > 0) {
3248 int size = len + 8;
3249 avio_wb32(pb, size);
3250 ffio_wfourcc(pb, name);
3251 avio_write(pb, t->value, len);
3252 return size;
3253 }
3254 return 0;
3255 }
3256
3257 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3258 {
3259 int val;
3260 while (*b) {
3261 GET_UTF8(val, *b++, return -1;)
3262 avio_wb16(pb, val);
3263 }
3264 avio_wb16(pb, 0x00);
3265 return 0;
3266 }
3267
3268 static uint16_t language_code(const char *str)
3269 {
3270 return (((str[0] - 0x60) & 0x1F) << 10) +
3271 (((str[1] - 0x60) & 0x1F) << 5) +
3272 (( str[2] - 0x60) & 0x1F);
3273 }
3274
3275 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3276 const char *tag, const char *str)
3277 {
3278 int64_t pos = avio_tell(pb);
3279 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3280 if (!t || !utf8len(t->value))
3281 return 0;
3282 avio_wb32(pb, 0); /* size */
3283 ffio_wfourcc(pb, tag); /* type */
3284 avio_wb32(pb, 0); /* version + flags */
3285 if (!strcmp(tag, "yrrc"))
3286 avio_wb16(pb, atoi(t->value));
3287 else {
3288 avio_wb16(pb, language_code("eng")); /* language */
3289 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3290 if (!strcmp(tag, "albm") &&
3291 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3292 avio_w8(pb, atoi(t->value));
3293 }
3294 return update_size(pb, pos);
3295 }
3296
3297 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3298 {
3299 int64_t pos = avio_tell(pb);
3300 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3301
3302 avio_wb32(pb, 0); // size
3303 ffio_wfourcc(pb, "chpl");
3304 avio_wb32(pb, 0x01000000); // version + flags
3305 avio_wb32(pb, 0); // unknown
3306 avio_w8(pb, nb_chapters);
3307
3308 for (i = 0; i < nb_chapters; i++) {
3309 AVChapter *c = s->chapters[i];
3310 AVDictionaryEntry *t;
3311 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3312
3313 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3314 int len = FFMIN(strlen(t->value), 255);
3315 avio_w8(pb, len);
3316 avio_write(pb, t->value, len);
3317 } else
3318 avio_w8(pb, 0);
3319 }
3320 return update_size(pb, pos);
3321 }
3322
3323 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3324 AVFormatContext *s)
3325 {
3326 AVIOContext *pb_buf;
3327 int ret, size;
3328 uint8_t *buf;
3329
3330 ret = avio_open_dyn_buf(&pb_buf);
3331 if (ret < 0)
3332 return ret;
3333
3334 if (mov->mode & MODE_3GP) {
3335 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3336 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3337 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3338 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3339 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3340 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3341 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3342 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3343 mov_write_loci_tag(s, pb_buf);
3344 } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
3345 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3346 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3347 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3348 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3349 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3350 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3351 // currently ignored by mov.c
3352 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3353 // add support for libquicktime, this atom is also actually read by mov.c
3354 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3355 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3356 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3357 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3358 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3359 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3360 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3361 } else {
3362 /* iTunes meta data */
3363 mov_write_meta_tag(pb_buf, mov, s);
3364 mov_write_loci_tag(s, pb_buf);
3365 }
3366
3367 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3368 mov_write_chpl_tag(pb_buf, s);
3369
3370 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3371 avio_wb32(pb, size + 8);
3372 ffio_wfourcc(pb, "udta");
3373 avio_write(pb, buf, size);
3374 }
3375 av_free(buf);
3376
3377 return 0;
3378 }
3379
3380 static void mov_write_psp_udta_tag(AVIOContext *pb,
3381 const char *str, const char *lang, int type)
3382 {
3383 int len = utf8len(str) + 1;
3384 if (len <= 0)
3385 return;
3386 avio_wb16(pb, len * 2 + 10); /* size */
3387 avio_wb32(pb, type); /* type */
3388 avio_wb16(pb, language_code(lang)); /* language */
3389 avio_wb16(pb, 0x01); /* ? */
3390 ascii_to_wc(pb, str);
3391 }
3392
3393 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3394 {
3395 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3396 int64_t pos, pos2;
3397
3398 if (title) {
3399 pos = avio_tell(pb);
3400 avio_wb32(pb, 0); /* size placeholder*/
3401 ffio_wfourcc(pb, "uuid");
3402 ffio_wfourcc(pb, "USMT");
3403 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3404 avio_wb32(pb, 0xbb88695c);
3405 avio_wb32(pb, 0xfac9c740);
3406
3407 pos2 = avio_tell(pb);
3408 avio_wb32(pb, 0); /* size placeholder*/
3409 ffio_wfourcc(pb, "MTDT");
3410 avio_wb16(pb, 4);
3411
3412 // ?
3413 avio_wb16(pb, 0x0C); /* size */
3414 avio_wb32(pb, 0x0B); /* type */
3415 avio_wb16(pb, language_code("und")); /* language */
3416 avio_wb16(pb, 0x0); /* ? */
3417 avio_wb16(pb, 0x021C); /* data */
3418
3419 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3420 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3421 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3422 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3423
3424 update_size(pb, pos2);
3425 return update_size(pb, pos);
3426 }
3427
3428 return 0;
3429 }
3430
3431 static void build_chunks(MOVTrack *trk)
3432 {
3433 int i;
3434 MOVIentry *chunk = &trk->cluster[0];
3435 uint64_t chunkSize = chunk->size;
3436 chunk->chunkNum = 1;
3437 if (trk->chunkCount)
3438 return;
3439 trk->chunkCount = 1;
3440 for (i = 1; i<trk->entry; i++){
3441 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3442 chunkSize + trk->cluster[i].size < (1<<20)){
3443 chunkSize += trk->cluster[i].size;
3444 chunk->samples_in_chunk += trk->cluster[i].entries;
3445 } else {
3446 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3447 chunk=&trk->cluster[i];
3448 chunkSize = chunk->size;
3449 trk->chunkCount++;
3450 }
3451 }
3452 }
3453
3454 /**
3455 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3456 * the stream ids are used as track ids.
3457 *
3458 * This assumes mov->tracks and s->streams are in the same order and
3459 * there are no gaps in either of them (so mov->tracks[n] refers to
3460 * s->streams[n]).
3461 *
3462 * As an exception, there can be more entries in
3463 * s->streams than in mov->tracks, in which case new track ids are
3464 * generated (starting after the largest found stream id).
3465 */
3466 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3467 {
3468 int i;
3469
3470 if (mov->track_ids_ok)
3471 return 0;
3472
3473 if (mov->use_stream_ids_as_track_ids) {
3474 int next_generated_track_id = 0;
3475 for (i = 0; i < s->nb_streams; i++) {
3476 if (s->streams[i]->id > next_generated_track_id)
3477 next_generated_track_id = s->streams[i]->id;
3478 }
3479
3480 for (i = 0; i < mov->nb_streams; i++) {
3481 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3482 continue;
3483
3484 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3485 }
3486 } else {
3487 for (i = 0; i < mov->nb_streams; i++) {
3488 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3489 continue;
3490
3491 mov->tracks[i].track_id = i + 1;
3492 }
3493 }
3494
3495 mov->track_ids_ok = 1;
3496
3497 return 0;
3498 }
3499
3500 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3501 AVFormatContext *s)
3502 {
3503 int i;
3504 int64_t pos = avio_tell(pb);
3505 avio_wb32(pb, 0); /* size placeholder*/
3506 ffio_wfourcc(pb, "moov");
3507
3508 mov_setup_track_ids(mov, s);
3509
3510 for (i = 0; i < mov->nb_streams; i++) {
3511 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3512 continue;
3513
3514 mov->tracks[i].time = mov->time;
3515
3516 if (mov->tracks[i].entry)
3517 build_chunks(&mov->tracks[i]);
3518 }
3519
3520 if (mov->chapter_track)
3521 for (i = 0; i < s->nb_streams; i++) {
3522 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3523 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3524 }
3525 for (i = 0; i < mov->nb_streams; i++) {
3526 MOVTrack *track = &mov->tracks[i];
3527 if (track->tag == MKTAG('r','t','p',' ')) {
3528 track->tref_tag = MKTAG('h','i','n','t');
3529 track->tref_id = mov->tracks[track->src_track].track_id;
3530 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3531 int * fallback, size;
3532 fallback = (int*)av_stream_get_side_data(track->st,
3533 AV_PKT_DATA_FALLBACK_TRACK,
3534 &size);
3535 if (fallback != NULL && size == sizeof(int)) {
3536 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3537 track->tref_tag = MKTAG('f','a','l','l');
3538 track->tref_id = mov->tracks[*fallback].track_id;
3539 }
3540 }
3541 }
3542 }
3543 for (i = 0; i < mov->nb_streams; i++) {
3544 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3545 int src_trk = mov->tracks[i].src_track;
3546 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3547 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3548 //src_trk may have a different timescale than the tmcd track
3549 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3550 mov->tracks[i].timescale,
3551 mov->tracks[src_trk].timescale);
3552 }
3553 }
3554
3555 mov_write_mvhd_tag(pb, mov);
3556 if (mov->mode != MODE_MOV && !mov->iods_skip)
3557 mov_write_iods_tag(pb, mov);
3558 for (i = 0; i < mov->nb_streams; i++) {
3559 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3560 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3561 if (ret < 0)
3562 return ret;
3563 }
3564 }
3565 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3566 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3567
3568 if (mov->mode == MODE_PSP)
3569 mov_write_uuidusmt_tag(pb, s);
3570 else
3571 mov_write_udta_tag(pb, mov, s);
3572
3573 return update_size(pb, pos);
3574 }
3575
3576 static void param_write_int(AVIOContext *pb, const char *name, int value)
3577 {
3578 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3579 }
3580
3581 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3582 {
3583 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3584 }
3585
3586 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3587 {
3588 char buf[150];
3589 len = FFMIN(sizeof(buf) / 2 - 1, len);
3590 ff_data_to_hex(buf, value, len, 0);
3591 buf[2 * len] = '\0';
3592 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3593 }
3594
3595 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3596 {
3597 int64_t pos = avio_tell(pb);
3598 int i;
3599 int64_t manifest_bit_rate = 0;
3600 AVCPBProperties *props = NULL;
3601
3602 static const uint8_t uuid[] = {
3603 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3604 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3605 };
3606
3607 avio_wb32(pb, 0);
3608 ffio_wfourcc(pb, "uuid");
3609 avio_write(pb, uuid, sizeof(uuid));
3610 avio_wb32(pb, 0);
3611
3612 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3613 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3614 avio_printf(pb, "<head>\n");
3615 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3616 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3617 LIBAVFORMAT_IDENT);
3618 avio_printf(pb, "</head>\n");
3619 avio_printf(pb, "<body>\n");
3620 avio_printf(pb, "<switch>\n");
3621
3622 mov_setup_track_ids(mov, s);
3623
3624 for (i = 0; i < mov->nb_streams; i++) {
3625 MOVTrack *track = &mov->tracks[i];
3626 const char *type;
3627 int track_id = track->track_id;
3628
3629 AVStream *st = track->st;
3630 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3631
3632 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3633 type = "video";
3634 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3635 type = "audio";
3636 } else {
3637 continue;
3638 }
3639
3640 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3641
3642 if (track->par->bit_rate) {
3643 manifest_bit_rate = track->par->bit_rate;
3644 } else if (props) {
3645 manifest_bit_rate = props->max_bitrate;
3646 }
3647
3648 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3649 manifest_bit_rate);
3650 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3651 param_write_int(pb, "trackID", track_id);
3652 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3653 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3654 if (track->par->codec_id == AV_CODEC_ID_H264) {
3655 uint8_t *ptr;
3656 int size = track->par->extradata_size;
3657 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3658 &size)) {
3659 param_write_hex(pb, "CodecPrivateData",
3660 ptr ? ptr : track->par->extradata,
3661 size);
3662 av_free(ptr);
3663 }
3664 param_write_string(pb, "FourCC", "H264");
3665 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3666 param_write_string(pb, "FourCC", "WVC1");
3667 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3668 track->par->extradata_size);
3669 }
3670 param_write_int(pb, "MaxWidth", track->par->width);
3671 param_write_int(pb, "MaxHeight", track->par->height);
3672 param_write_int(pb, "DisplayWidth", track->par->width);
3673 param_write_int(pb, "DisplayHeight", track->par->height);
3674 } else {
3675 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3676 switch (track->par->profile)
3677 {
3678 case FF_PROFILE_AAC_HE_V2:
3679 param_write_string(pb, "FourCC", "AACP");
3680 break;
3681 case FF_PROFILE_AAC_HE:
3682 param_write_string(pb, "FourCC", "AACH");
3683 break;
3684 default:
3685 param_write_string(pb, "FourCC", "AACL");
3686 }
3687 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3688 param_write_string(pb, "FourCC", "WMAP");
3689 }
3690 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3691 track->par->extradata_size);
3692 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3693 track->par->codec_id));
3694 param_write_int(pb, "Channels", track->par->channels);
3695 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3696 param_write_int(pb, "BitsPerSample", 16);
3697 param_write_int(pb, "PacketSize", track->par->block_align ?
3698 track->par->block_align : 4);
3699 }
3700 avio_printf(pb, "</%s>\n", type);
3701 }
3702 avio_printf(pb, "</switch>\n");
3703 avio_printf(pb, "</body>\n");
3704 avio_printf(pb, "</smil>\n");
3705
3706 return update_size(pb, pos);
3707 }
3708
3709 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3710 {
3711 avio_wb32(pb, 16);
3712 ffio_wfourcc(pb, "mfhd");
3713 avio_wb32(pb, 0);
3714 avio_wb32(pb, mov->fragments);
3715 return 0;
3716 }
3717
3718 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3719 {
3720 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3721 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3722 }
3723
3724 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3725 MOVTrack *track, int64_t moof_offset)
3726 {
3727 int64_t pos = avio_tell(pb);
3728 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3729 MOV_TFHD_BASE_DATA_OFFSET;
3730 if (!track->entry) {
3731 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3732 } else {
3733 flags |= MOV_TFHD_DEFAULT_FLAGS;
3734 }
3735 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3736 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3737 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3738 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3739 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3740 }
3741
3742 /* Don't set a default sample size, the silverlight player refuses
3743 * to play files with that set. Don't set a default sample duration,
3744 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3745 * file format says it MUST NOT be set. */
3746 if (track->mode == MODE_ISM)
3747 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3748 MOV_TFHD_BASE_DATA_OFFSET);
3749
3750 avio_wb32(pb, 0); /* size placeholder */
3751 ffio_wfourcc(pb, "tfhd");
3752 avio_w8(pb, 0); /* version */
3753 avio_wb24(pb, flags);
3754
3755 avio_wb32(pb, track->track_id); /* track-id */
3756 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3757 avio_wb64(pb, moof_offset);
3758 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3759 track->default_duration = get_cluster_duration(track, 0);
3760 avio_wb32(pb, track->default_duration);
3761 }
3762 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3763 track->default_size = track->entry ? track->cluster[0].size : 1;
3764 avio_wb32(pb, track->default_size);
3765 } else
3766 track->default_size = -1;
3767
3768 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3769 /* Set the default flags based on the second sample, if available.
3770 * If the first sample is different, that can be signaled via a separate field. */
3771 if (track->entry > 1)
3772 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
3773 else
3774 track->default_sample_flags =
3775 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
3776 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3777 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3778 avio_wb32(pb, track->default_sample_flags);
3779 }
3780
3781 return update_size(pb, pos);
3782 }
3783
3784 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3785 MOVTrack *track, int moof_size,
3786 int first, int end)
3787 {
3788 int64_t pos = avio_tell(pb);
3789 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3790 int i;
3791
3792 for (i = first; i < end; i++) {
3793 if (get_cluster_duration(track, i) != track->default_duration)
3794 flags |= MOV_TRUN_SAMPLE_DURATION;
3795 if (track->cluster[i].size != track->default_size)
3796 flags |= MOV_TRUN_SAMPLE_SIZE;
3797 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3798 flags |= MOV_TRUN_SAMPLE_FLAGS;
3799 }
3800 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
3801 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
3802 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3803 if (track->flags & MOV_TRACK_CTTS)
3804 flags |= MOV_TRUN_SAMPLE_CTS;
3805
3806 avio_wb32(pb, 0); /* size placeholder */
3807 ffio_wfourcc(pb, "trun");
3808 avio_w8(pb, 0); /* version */
3809 avio_wb24(pb, flags);
3810
3811 avio_wb32(pb, end - first); /* sample count */
3812 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3813 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3814 !mov->first_trun)
3815 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3816 else
3817 avio_wb32(pb, moof_size + 8 + track->data_offset +
3818 track->cluster[first].pos); /* data offset */
3819 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3820 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
3821
3822 for (i = first; i < end; i++) {
3823 if (flags & MOV_TRUN_SAMPLE_DURATION)
3824 avio_wb32(pb, get_cluster_duration(track, i));
3825 if (flags & MOV_TRUN_SAMPLE_SIZE)
3826 avio_wb32(pb, track->cluster[i].size);
3827 if (flags & MOV_TRUN_SAMPLE_FLAGS)
3828 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3829 if (flags & MOV_TRUN_SAMPLE_CTS)
3830 avio_wb32(pb, track->cluster[i].cts);
3831 }
3832
3833 mov->first_trun = 0;
3834 return update_size(pb, pos);
3835 }
3836
3837 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3838 {
3839 int64_t pos = avio_tell(pb);
3840 static const uint8_t uuid[] = {
3841 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3842 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3843 };
3844
3845 avio_wb32(pb, 0); /* size placeholder */
3846 ffio_wfourcc(pb, "uuid");
3847 avio_write(pb, uuid, sizeof(uuid));
3848 avio_w8(pb, 1);
3849 avio_wb24(pb, 0);
3850 avio_wb64(pb, track->start_dts + track->frag_start +
3851 track->cluster[0].cts);
3852 avio_wb64(pb, track->end_pts -
3853 (track->cluster[0].dts + track->cluster[0].cts));
3854
3855 return update_size(pb, pos);
3856 }
3857
3858 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3859 MOVTrack *track, int entry)
3860 {
3861 int n = track->nb_frag_info - 1 - entry, i;
3862 int size = 8 + 16 + 4 + 1 + 16*n;
3863 static const uint8_t uuid[] = {
3864 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3865 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3866 };
3867
3868 if (entry < 0)
3869 return 0;
3870
3871 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3872 avio_wb32(pb, size);
3873 ffio_wfourcc(pb, "uuid");
3874 avio_write(pb, uuid, sizeof(uuid));
3875 avio_w8(pb, 1);
3876 avio_wb24(pb, 0);
3877 avio_w8(pb, n);
3878 for (i = 0; i < n; i++) {
3879 int index = entry + 1 + i;
3880 avio_wb64(pb, track->frag_info[index].time);
3881 avio_wb64(pb, track->frag_info[index].duration);
3882 }
3883 if (n < mov->ism_lookahead) {
3884 int free_size = 16 * (mov->ism_lookahead - n);
3885 avio_wb32(pb, free_size);
3886 ffio_wfourcc(pb, "free");
3887 ffio_fill(pb, 0, free_size - 8);
3888 }
3889
3890 return 0;
3891 }
3892
3893 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3894 MOVTrack *track)
3895 {
3896 int64_t pos = avio_tell(pb);
3897 int i;
3898 for (i = 0; i < mov->ism_lookahead; i++) {
3899 /* Update the tfrf tag for the last ism_lookahead fragments,
3900 * nb_frag_info - 1 is the next fragment to be written. */
3901 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3902 }
3903 avio_seek(pb, pos, SEEK_SET);
3904 return 0;
3905 }
3906
3907 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3908 int size)
3909 {
3910 int i;
3911 for (i = 0; i < mov->nb_streams; i++) {
3912 MOVTrack *track = &mov->tracks[i];
3913 MOVFragmentInfo *info;
3914 if ((tracks >= 0 && i != tracks) || !track->entry)
3915 continue;
3916 track->nb_frag_info++;
3917 if (track->nb_frag_info >= track->frag_info_capacity) {
3918 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3919 if (av_reallocp_array(&track->frag_info,
3920 new_capacity,
3921 sizeof(*track->frag_info)))
3922 return AVERROR(ENOMEM);
3923 track->frag_info_capacity = new_capacity;
3924 }
3925 info = &track->frag_info[track->nb_frag_info - 1];
3926 info->offset = avio_tell(pb);
3927 info->size = size;
3928 // Try to recreate the original pts for the first packet
3929 // from the fields we have stored
3930 info->time = track->start_dts + track->frag_start +
3931 track->cluster[0].cts;
3932 info->duration = track->end_pts -
3933 (track->cluster[0].dts + track->cluster[0].cts);
3934 // If the pts is less than zero, we will have trimmed
3935 // away parts of the media track using an edit list,
3936 // and the corresponding start presentation time is zero.
3937 if (info->time < 0) {
3938 info->duration += info->time;
3939 info->time = 0;
3940 }
3941 info->tfrf_offset = 0;
3942 mov_write_tfrf_tags(pb, mov, track);
3943 }
3944 return 0;
3945 }
3946
3947 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3948 {
3949 int64_t pos = avio_tell(pb);
3950
3951 avio_wb32(pb, 0); /* size */
3952 ffio_wfourcc(pb, "tfdt");
3953 avio_w8(pb, 1); /* version */
3954 avio_wb24(pb, 0);
3955 avio_wb64(pb, track->frag_start);
3956 return update_size(pb, pos);
3957 }
3958
3959 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3960 MOVTrack *track, int64_t moof_offset,
3961 int moof_size)
3962 {
3963 int64_t pos = avio_tell(pb);
3964 int i, start = 0;
3965 avio_wb32(pb, 0); /* size placeholder */
3966 ffio_wfourcc(pb, "traf");
3967
3968 mov_write_tfhd_tag(pb, mov, track, moof_offset);
3969 if (mov->mode != MODE_ISM)
3970 mov_write_tfdt_tag(pb, track);
3971 for (i = 1; i < track->entry; i++) {
3972 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
3973 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
3974 start = i;
3975 }
3976 }
3977 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
3978 if (mov->mode == MODE_ISM) {
3979 mov_write_tfxd_tag(pb, track);
3980
3981 if (mov->ism_lookahead) {
3982 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3983
3984 if (track->nb_frag_info > 0) {
3985 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3986 if (!info->tfrf_offset)
3987 info->tfrf_offset = avio_tell(pb);
3988 }
3989 avio_wb32(pb, 8 + size);
3990 ffio_wfourcc(pb, "free");
3991 for (i = 0; i < size; i++)
3992 avio_w8(pb, 0);
3993 }
3994 }
3995
3996 return update_size(pb, pos);
3997 }
3998
3999 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4000 int tracks, int moof_size)
4001 {
4002 int64_t pos = avio_tell(pb);
4003 int i;
4004
4005 avio_wb32(pb, 0); /* size placeholder */
4006 ffio_wfourcc(pb, "moof");
4007 mov->first_trun = 1;
4008
4009 mov_write_mfhd_tag(pb, mov);
4010 for (i = 0; i < mov->nb_streams; i++) {
4011 MOVTrack *track = &mov->tracks[i];
4012 if (tracks >= 0 && i != tracks)
4013 continue;
4014 if (!track->entry)
4015 continue;
4016 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4017 }
4018
4019 return update_size(pb, pos);
4020 }
4021
4022 static int mov_write_sidx_tag(AVIOContext *pb,
4023 MOVTrack *track, int ref_size, int total_sidx_size)
4024 {
4025 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4026 int64_t presentation_time, duration, offset;
4027 unsigned starts_with_SAP;
4028 int i, entries;
4029
4030 if (track->entry) {
4031 entries = 1;
4032 presentation_time = track->start_dts + track->frag_start +
4033 track->cluster[0].cts;
4034 duration = track->end_pts -
4035 (track->cluster[0].dts + track->cluster[0].cts);
4036 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4037
4038 // pts<0 should be cut away using edts
4039 if (presentation_time < 0) {
4040 duration += presentation_time;
4041 presentation_time = 0;
4042 }
4043 } else {
4044 entries = track->nb_frag_info;
4045 if (entries <= 0)
4046 return 0;
4047 presentation_time = track->frag_info[0].time;
4048 }
4049
4050 avio_wb32(pb, 0); /* size */
4051 ffio_wfourcc(pb, "sidx");
4052 avio_w8(pb, 1); /* version */
4053 avio_wb24(pb, 0);
4054 avio_wb32(pb, track->track_id); /* reference_ID */
4055 avio_wb32(pb, track->timescale); /* timescale */
4056 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4057 offset_pos = avio_tell(pb);
4058 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4059 avio_wb16(pb, 0); /* reserved */
4060
4061 avio_wb16(pb, entries); /* reference_count */
4062 for (i = 0; i < entries; i++) {
4063 if (!track->entry) {
4064 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4065 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4066 }
4067 duration = track->frag_info[i].duration;
4068 ref_size = track->frag_info[i].size;
4069 starts_with_SAP = 1;
4070 }
4071 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4072 avio_wb32(pb, duration); /* subsegment_duration */
4073 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4074 }
4075
4076 end_pos = avio_tell(pb);
4077 offset = pos + total_sidx_size - end_pos;
4078 avio_seek(pb, offset_pos, SEEK_SET);
4079 avio_wb64(pb, offset);
4080 avio_seek(pb, end_pos, SEEK_SET);
4081 return update_size(pb, pos);
4082 }
4083
4084 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4085 int tracks, int ref_size)
4086 {
4087 int i, round, ret;
4088 AVIOContext *avio_buf;
4089 int total_size = 0;
4090 for (round = 0; round < 2; round++) {
4091 // First run one round to calculate the total size of all
4092 // sidx atoms.
4093 // This would be much simpler if we'd only write one sidx
4094 // atom, for the first track in the moof.
4095 if (round == 0) {
4096 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4097 return ret;
4098 } else {
4099 avio_buf = pb;
4100 }
4101 for (i = 0; i < mov->nb_streams; i++) {
4102 MOVTrack *track = &mov->tracks[i];
4103 if (tracks >= 0 && i != tracks)
4104 continue;
4105 // When writing a sidx for the full file, entry is 0, but
4106 // we want to include all tracks. ref_size is 0 in this case,
4107 // since we read it from frag_info instead.
4108 if (!track->entry && ref_size > 0)
4109 continue;
4110 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4111 total_size);
4112 }
4113 if (round == 0)
4114 total_size = ffio_close_null_buf(avio_buf);
4115 }
4116 return 0;
4117 }
4118
4119 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4120 int64_t mdat_size)
4121 {
4122 AVIOContext *avio_buf;
4123 int ret, moof_size;
4124
4125 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4126 return ret;
4127 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4128 moof_size = ffio_close_null_buf(avio_buf);
4129
4130 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4131 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4132
4133 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4134 return ret;
4135
4136 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4137 }
4138
4139 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4140 {
4141 int64_t pos = avio_tell(pb);
4142 int i;
4143
4144 avio_wb32(pb, 0); /* size placeholder */
4145 ffio_wfourcc(pb, "tfra");
4146 avio_w8(pb, 1); /* version */
4147 avio_wb24(pb, 0);
4148
4149 avio_wb32(pb, track->track_id);
4150 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4151 avio_wb32(pb, track->nb_frag_info);
4152 for (i = 0; i < track->nb_frag_info; i++) {
4153 avio_wb64(pb, track->frag_info[i].time);
4154 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4155 avio_w8(pb, 1); /* traf number */
4156 avio_w8(pb, 1); /* trun number */
4157 avio_w8(pb, 1); /* sample number */
4158 }
4159
4160 return update_size(pb, pos);
4161 }
4162
4163 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4164 {
4165 int64_t pos = avio_tell(pb);
4166 int i;
4167
4168 avio_wb32(pb, 0); /* size placeholder */
4169 ffio_wfourcc(pb, "mfra");
4170 /* An empty mfra atom is enough to indicate to the publishing point that
4171 * the stream has ended. */
4172 if (mov->flags & FF_MOV_FLAG_ISML)
4173 return update_size(pb, pos);
4174
4175 for (i = 0; i < mov->nb_streams; i++) {
4176 MOVTrack *track = &mov->tracks[i];
4177 if (track->nb_frag_info)
4178 mov_write_tfra_tag(pb, track);
4179 }
4180
4181 avio_wb32(pb, 16);
4182 ffio_wfourcc(pb, "mfro");
4183 avio_wb32(pb, 0); /* version + flags */
4184 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4185
4186 return update_size(pb, pos);
4187 }
4188
4189 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4190 {
4191 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4192 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4193
4194 mov->mdat_pos = avio_tell(pb);
4195 avio_wb32(pb, 0); /* size placeholder*/
4196 ffio_wfourcc(pb, "mdat");
4197 return 0;
4198 }
4199
4200 /* TODO: This needs to be more general */
4201 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4202 {
4203 MOVMuxContext *mov = s->priv_data;
4204 int64_t pos = avio_tell(pb);
4205 int has_h264 = 0, has_video = 0;
4206 int minor = 0x200;
4207 int i;
4208
4209 for (i = 0; i < s->nb_streams; i++) {
4210 AVStream *st = s->streams[i];
4211 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4212 has_video = 1;
4213 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4214 has_h264 = 1;
4215 }
4216
4217 avio_wb32(pb, 0); /* size */
4218 ffio_wfourcc(pb, "ftyp");
4219
4220 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4221 ffio_wfourcc(pb, mov->major_brand);
4222 else if (mov->mode == MODE_3GP) {
4223 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4224 minor = has_h264 ? 0x100 : 0x200;
4225 } else if (mov->mode & MODE_3G2) {
4226 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4227 minor = has_h264 ? 0x20000 : 0x10000;
4228 } else if (mov->mode == MODE_PSP)
4229 ffio_wfourcc(pb, "MSNV");
4230 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4231 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4232 else if (mov->mode == MODE_MP4)
4233 ffio_wfourcc(pb, "isom");
4234 else if (mov->mode == MODE_IPOD)
4235 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4236 else if (mov->mode == MODE_ISM)
4237 ffio_wfourcc(pb, "isml");
4238 else if (mov->mode == MODE_F4V)
4239 ffio_wfourcc(pb, "f4v ");
4240 else
4241 ffio_wfourcc(pb, "qt ");
4242
4243 avio_wb32(pb, minor);
4244
4245 if (mov->mode == MODE_MOV)
4246 ffio_wfourcc(pb, "qt ");
4247 else if (mov->mode == MODE_ISM) {
4248 ffio_wfourcc(pb, "piff");
4249 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4250 ffio_wfourcc(pb, "isom");
4251 ffio_wfourcc(pb, "iso2");
4252 if (has_h264)
4253 ffio_wfourcc(pb, "avc1");
4254 }
4255
4256 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4257 // brand. This is compatible with users that don't understand tfdt.
4258 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4259 ffio_wfourcc(pb, "iso6");
4260
4261 if (mov->mode == MODE_3GP)
4262 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4263 else if (mov->mode & MODE_3G2)
4264 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4265 else if (mov->mode == MODE_PSP)
4266 ffio_wfourcc(pb, "MSNV");
4267 else if (mov->mode == MODE_MP4)
4268 ffio_wfourcc(pb, "mp41");
4269
4270 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4271 ffio_wfourcc(pb, "dash");
4272
4273 return update_size(pb, pos);
4274 }
4275
4276 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4277 {
4278 AVStream *video_st = s->streams[0];
4279 AVCodecParameters *video_par = s->streams[0]->codecpar;
4280 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4281 int audio_rate = audio_par->sample_rate;
4282 int64_t frame_rate = (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den;
4283 int audio_kbitrate = audio_par->bit_rate / 1000;
4284 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4285
4286 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4287 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4288 return AVERROR(EINVAL);
4289 }
4290
4291 avio_wb32(pb, 0x94); /* size */
4292 ffio_wfourcc(pb, "uuid");
4293 ffio_wfourcc(pb, "PROF");
4294
4295 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4296 avio_wb32(pb, 0xbb88695c);
4297 avio_wb32(pb, 0xfac9c740);
4298
4299 avio_wb32(pb, 0x0); /* ? */
4300 avio_wb32(pb, 0x3); /* 3 sections ? */
4301
4302 avio_wb32(pb, 0x14); /* size */
4303 ffio_wfourcc(pb, "FPRF");
4304 avio_wb32(pb, 0x0); /* ? */
4305 avio_wb32(pb, 0x0); /* ? */
4306 avio_wb32(pb, 0x0); /* ? */
4307
4308 avio_wb32(pb, 0x2c); /* size */
4309 ffio_wfourcc(pb, "APRF"); /* audio */
4310 avio_wb32(pb, 0x0);
4311 avio_wb32(pb, 0x2); /* TrackID */
4312 ffio_wfourcc(pb, "mp4a");
4313 avio_wb32(pb, 0x20f);
4314 avio_wb32(pb, 0x0);
4315 avio_wb32(pb, audio_kbitrate);
4316 avio_wb32(pb, audio_kbitrate);
4317 avio_wb32(pb, audio_rate);
4318 avio_wb32(pb, audio_par->channels);
4319
4320 avio_wb32(pb, 0x34); /* size */
4321 ffio_wfourcc(pb, "VPRF"); /* video */
4322 avio_wb32(pb, 0x0);
4323 avio_wb32(pb, 0x1); /* TrackID */
4324 if (video_par->codec_id == AV_CODEC_ID_H264) {
4325 ffio_wfourcc(pb, "avc1");
4326 avio_wb16(pb, 0x014D);
4327 avio_wb16(pb, 0x0015);
4328 } else {
4329 ffio_wfourcc(pb, "mp4v");
4330 avio_wb16(pb, 0x0000);
4331 avio_wb16(pb, 0x0103);
4332 }
4333 avio_wb32(pb, 0x0);
4334 avio_wb32(pb, video_kbitrate);
4335 avio_wb32(pb, video_kbitrate);
4336 avio_wb32(pb, frame_rate);
4337 avio_wb32(pb, frame_rate);
4338 avio_wb16(pb, video_par->width);
4339 avio_wb16(pb, video_par->height);
4340 avio_wb32(pb, 0x010001); /* ? */
4341
4342 return 0;
4343 }
4344
4345 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4346 {
4347 MOVMuxContext *mov = s->priv_data;
4348 int i;
4349
4350 mov_write_ftyp_tag(pb,s);
4351 if (mov->mode == MODE_PSP) {
4352 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4353 for (i = 0; i < s->nb_streams; i++) {
4354 AVStream *st = s->streams[i];
4355 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4356 video_streams_nb++;
4357 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4358 audio_streams_nb++;
4359 else
4360 other_streams_nb++;
4361 }
4362
4363 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4364 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4365 return AVERROR(EINVAL);
4366 }
4367 return mov_write_uuidprof_tag(pb, s);
4368 }
4369 return 0;
4370 }
4371
4372 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4373 {
4374 uint32_t c = -1;
4375 int i, closed_gop = 0;
4376
4377 for (i = 0; i < pkt->size - 4; i++) {
4378 c = (c << 8) + pkt->data[i];
4379 if (c == 0x1b8) { // gop
4380 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4381 } else if (c == 0x100) { // pic
4382 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4383 if (!temp_ref || closed_gop) // I picture is not reordered
4384 *flags = MOV_SYNC_SAMPLE;
4385 else
4386 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4387 break;
4388 }
4389 }
4390 return 0;
4391 }
4392
4393 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4394 {
4395 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4396 int seq = 0, entry = 0;
4397 int key = pkt->flags & AV_PKT_FLAG_KEY;
4398 start = find_next_marker(pkt->data, end);
4399 for (next = start; next < end; start = next) {
4400 next = find_next_marker(start + 4, end);
4401 switch (AV_RB32(start)) {
4402 case VC1_CODE_SEQHDR:
4403 seq = 1;
4404 break;
4405 case VC1_CODE_ENTRYPOINT:
4406 entry = 1;
4407 break;
4408 case VC1_CODE_SLICE:
4409 trk->vc1_info.slices = 1;
4410 break;
4411 }
4412 }
4413 if (!trk->entry && trk->vc1_info.first_packet_seen)
4414 trk->vc1_info.first_frag_written = 1;
4415 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4416 /* First packet in first fragment */
4417 trk->vc1_info.first_packet_seq = seq;
4418 trk->vc1_info.first_packet_entry = entry;
4419 trk->vc1_info.first_packet_seen = 1;
4420 } else if ((seq && !trk->vc1_info.packet_seq) ||
4421 (entry && !trk->vc1_info.packet_entry)) {
4422 int i;
4423 for (i = 0; i < trk->entry; i++)
4424 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4425 trk->has_keyframes = 0;
4426 if (seq)
4427 trk->vc1_info.packet_seq = 1;
4428 if (entry)
4429 trk->vc1_info.packet_entry = 1;
4430 if (!trk->vc1_info.first_frag_written) {
4431 /* First fragment */
4432 if ((!seq || trk->vc1_info.first_packet_seq) &&
4433 (!entry || trk->vc1_info.first_packet_entry)) {
4434 /* First packet had the same headers as this one, readd the
4435 * sync sample flag. */
4436 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4437 trk->has_keyframes = 1;
4438 }
4439 }
4440 }
4441 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4442 key = seq && entry;
4443 else if (trk->vc1_info.packet_seq)
4444 key = seq;
4445 else if (trk->vc1_info.packet_entry)
4446 key = entry;
4447 if (key) {
4448 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4449 trk->has_keyframes++;
4450 }
4451 }
4452
4453 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4454 {
4455 MOVMuxContext *mov = s->priv_data;
4456 int ret, buf_size;
4457 uint8_t *buf;
4458 int i, offset;
4459
4460 if (!track->mdat_buf)
4461 return 0;
4462 if (!mov->mdat_buf) {
4463 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4464 return ret;
4465 }
4466 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4467 track->mdat_buf = NULL;
4468
4469 offset = avio_tell(mov->mdat_buf);
4470 avio_write(mov->mdat_buf, buf, buf_size);
4471 av_free(buf);
4472
4473 for (i = track->entries_flushed; i < track->entry; i++)
4474 track->cluster[i].pos += offset;
4475 track->entries_flushed = track->entry;
4476 return 0;
4477 }
4478
4479 static int mov_flush_fragment(AVFormatContext *s, int force)
4480 {
4481 MOVMuxContext *mov = s->priv_data;
4482 int i, first_track = -1;
4483 int64_t mdat_size = 0;
4484 int ret;
4485 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4486
4487 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4488 return 0;
4489
4490 // Try to fill in the duration of the last packet in each stream
4491 // from queued packets in the interleave queues. If the flushing
4492 // of fragments was triggered automatically by an AVPacket, we
4493 // already have reliable info for the end of that track, but other
4494 // tracks may need to be filled in.
4495 for (i = 0; i < s->nb_streams; i++) {
4496 MOVTrack *track = &mov->tracks[i];
4497 if (!track->end_reliable) {
4498 int64_t ts_offset;
4499 const AVPacket *next = ff_interleaved_peek(s, i, &ts_offset);
4500 if (next) {
4501 track->track_duration = next->dts - track->start_dts + ts_offset;
4502 if (next->pts != AV_NOPTS_VALUE)
4503 track->end_pts = next->pts;
4504 else
4505 track->end_pts = next->dts;
4506 track->end_pts += ts_offset;
4507 }
4508 }
4509 }
4510
4511 for (i = 0; i < mov->nb_streams; i++) {
4512 MOVTrack *track = &mov->tracks[i];
4513 if (track->entry <= 1)
4514 continue;
4515 // Sample durations are calculated as the diff of dts values,
4516 // but for the last sample in a fragment, we don't know the dts
4517 // of the first sample in the next fragment, so we have to rely
4518 // on what was set as duration in the AVPacket. Not all callers
4519 // set this though, so we might want to replace it with an
4520 // estimate if it currently is zero.
4521 if (get_cluster_duration(track, track->entry - 1) != 0)
4522 continue;
4523 // Use the duration (i.e. dts diff) of the second last sample for
4524 // the last one. This is a wild guess (and fatal if it turns out
4525 // to be too long), but probably the best we can do - having a zero
4526 // duration is bad as well.
4527 track->track_duration += get_cluster_duration(track, track->entry - 2);
4528 track->end_pts += get_cluster_duration(track, track->entry - 2);
4529 if (!mov->missing_duration_warned) {
4530 av_log(s, AV_LOG_WARNING,
4531 "Estimating the duration of the last packet in a "
4532 "fragment, consider setting the duration field in "
4533 "AVPacket instead.\n");
4534 mov->missing_duration_warned = 1;
4535 }
4536 }
4537
4538 if (!mov->moov_written) {
4539 int64_t pos = avio_tell(s->pb);
4540 uint8_t *buf;
4541 int buf_size, moov_size;
4542
4543 for (i = 0; i < mov->nb_streams; i++)
4544 if (!mov->tracks[i].entry)
4545 break;
4546 /* Don't write the initial moov unless all tracks have data */
4547 if (i < mov->nb_streams && !force)
4548 return 0;
4549
4550 moov_size = get_moov_size(s);
4551 for (i = 0; i < mov->nb_streams; i++)
4552 mov->tracks[i].data_offset = pos + moov_size + 8;
4553
4554 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4555 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4556 mov_write_identification(s->pb, s);
4557 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4558 return ret;
4559
4560 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4561 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4562 mov->reserved_header_pos = avio_tell(s->pb);
4563 avio_flush(s->pb);
4564 mov->moov_written = 1;
4565 return 0;
4566 }
4567
4568 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4569 mov->mdat_buf = NULL;
4570 avio_wb32(s->pb, buf_size + 8);
4571 ffio_wfourcc(s->pb, "mdat");
4572 avio_write(s->pb, buf, buf_size);
4573 av_free(buf);
4574
4575 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4576 mov->reserved_header_pos = avio_tell(s->pb);
4577
4578 mov->moov_written = 1;
4579 mov->mdat_size = 0;
4580 for (i = 0; i < mov->nb_streams; i++) {
4581 if (mov->tracks[i].entry)
4582 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4583 mov->tracks[i].track_duration -
4584 mov->tracks[i].cluster[0].dts;
4585 mov->tracks[i].entry = 0;
4586 mov->tracks[i].end_reliable = 0;
4587 }
4588 avio_flush(s->pb);
4589 return 0;
4590 }
4591
4592 if (mov->frag_interleave) {
4593 for (i = 0; i < mov->nb_streams; i++) {
4594 MOVTrack *track = &mov->tracks[i];
4595 int ret;
4596 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4597 return ret;
4598 }
4599
4600 if (!mov->mdat_buf)
4601 return 0;
4602 mdat_size = avio_tell(mov->mdat_buf);
4603 }
4604
4605 for (i = 0; i < mov->nb_streams; i++) {
4606 MOVTrack *track = &mov->tracks[i];
4607 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4608 track->data_offset = 0;
4609 else
4610 track->data_offset = mdat_size;
4611 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4612 has_video = 1;
4613 if (first_video_track) {
4614 if (track->entry)
4615 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4616 first_video_track = 0;
4617 }
4618 }
4619 if (!track->entry)
4620 continue;
4621 if (track->mdat_buf)
4622 mdat_size += avio_tell(track->mdat_buf);
4623 if (first_track < 0)
4624 first_track = i;
4625 }
4626
4627 if (!mdat_size)
4628 return 0;
4629
4630 avio_write_marker(s->pb,
4631 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4632 (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
4633
4634 for (i = 0; i < mov->nb_streams; i++) {
4635 MOVTrack *track = &mov->tracks[i];
4636 int buf_size, write_moof = 1, moof_tracks = -1;
4637 uint8_t *buf;
4638 int64_t duration = 0;
4639
4640 if (track->entry)
4641 duration = track->start_dts + track->track_duration -
4642 track->cluster[0].dts;
4643 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4644 if (!track->mdat_buf)
4645 continue;
4646 mdat_size = avio_tell(track->mdat_buf);
4647 moof_tracks = i;
4648 } else {
4649 write_moof = i == first_track;
4650 }
4651
4652 if (write_moof) {
4653 avio_flush(s->pb);
4654
4655 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4656 mov->fragments++;
4657
4658 avio_wb32(s->pb, mdat_size + 8);
4659 ffio_wfourcc(s->pb, "mdat");
4660 }
4661
4662 if (track->entry)
4663 track->frag_start += duration;
4664 track->entry = 0;
4665 track->entries_flushed = 0;
4666 track->end_reliable = 0;
4667 if (!mov->frag_interleave) {
4668 if (!track->mdat_buf)
4669 continue;
4670 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4671 track->mdat_buf = NULL;
4672 } else {
4673 if (!mov->mdat_buf)
4674 continue;
4675 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4676 mov->mdat_buf = NULL;
4677 }
4678
4679 avio_write(s->pb, buf, buf_size);
4680 av_free(buf);
4681 }
4682
4683 mov->mdat_size = 0;
4684
4685 avio_flush(s->pb);
4686 return 0;
4687 }
4688
4689 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4690 {
4691 MOVMuxContext *mov = s->priv_data;
4692 int had_moov = mov->moov_written;
4693 int ret = mov_flush_fragment(s, force);
4694 if (ret < 0)
4695 return ret;
4696 // If using delay_moov, the first flush only wrote the moov,
4697 // not the actual moof+mdat pair, thus flush once again.
4698 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4699 ret = mov_flush_fragment(s, force);
4700 return ret;
4701 }
4702
4703 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4704 {
4705 MOVMuxContext *mov = s->priv_data;
4706 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4707 int64_t ref;
4708 uint64_t duration;
4709
4710 if (trk->entry) {
4711 ref = trk->cluster[trk->entry - 1].dts;
4712 } else if ( trk->start_dts != AV_NOPTS_VALUE
4713 && !trk->frag_discont) {
4714 ref = trk->start_dts + trk->track_duration;
4715 } else
4716 ref = pkt->dts; // Skip tests for the first packet
4717
4718 duration = pkt->dts - ref;
4719 if (pkt->dts < ref || duration >= INT_MAX) {
4720 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4721 duration, pkt->dts
4722 );
4723
4724 pkt->dts = ref + 1;
4725 pkt->pts = AV_NOPTS_VALUE;
4726 }
4727
4728 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
4729 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
4730 return AVERROR(EINVAL);
4731 }
4732 return 0;
4733 }
4734
4735 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4736 {
4737 MOVMuxContext *mov = s->priv_data;
4738 AVIOContext *pb = s->pb;
4739 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4740 AVCodecParameters *par = trk->par;
4741 unsigned int samples_in_chunk = 0;
4742 int size = pkt->size, ret = 0;
4743 uint8_t *reformatted_data = NULL;
4744
4745 ret = check_pkt(s, pkt);
4746 if (ret < 0)
4747 return ret;
4748
4749 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4750 int ret;
4751 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4752 if (mov->frag_interleave && mov->fragments > 0) {
4753 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
4754 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
4755 return ret;
4756 }
4757 }
4758
4759 if (!trk->mdat_buf) {
4760 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4761 return ret;
4762 }
4763 pb = trk->mdat_buf;
4764 } else {
4765 if (!mov->mdat_buf) {
4766 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4767 return ret;
4768 }
4769 pb = mov->mdat_buf;
4770 }
4771 }
4772
4773 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
4774 /* We must find out how many AMR blocks there are in one packet */
4775 static const uint16_t packed_size[16] =
4776 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4777 int len = 0;
4778
4779 while (len < size && samples_in_chunk < 100) {
4780 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4781 samples_in_chunk++;
4782 }
4783 if (samples_in_chunk > 1) {
4784 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4785 return -1;
4786 }
4787 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
4788 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4789 samples_in_chunk = trk->par->frame_size;
4790 } else if (trk->sample_size)
4791 samples_in_chunk = size / trk->sample_size;
4792 else
4793 samples_in_chunk = 1;
4794
4795 if (samples_in_chunk < 1) {
4796 av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
4797 return AVERROR_PATCHWELCOME;
4798 }
4799
4800 /* copy extradata if it exists */
4801 if (trk->vos_len == 0 && par->extradata_size > 0 &&
4802 !TAG_IS_AVCI(trk->tag) &&
4803 (par->codec_id != AV_CODEC_ID_DNXHD)) {
4804 trk->vos_len = par->extradata_size;
4805 trk->vos_data = av_malloc(trk->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
4806 if (!trk->vos_data) {
4807 ret = AVERROR(ENOMEM);
4808 goto err;
4809 }
4810 memcpy(trk->vos_data, par->extradata, trk->vos_len);
4811 memset(trk->vos_data + trk->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
4812 }
4813
4814 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4815 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4816 if (!s->streams[pkt->stream_index]->nb_frames) {
4817 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4818 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4819 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4820 return -1;
4821 }
4822 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4823 }
4824 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4825 /* from x264 or from bytestream H.264 */
4826 /* NAL reformatting needed */
4827 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4828 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4829 &size);
4830 avio_write(pb, reformatted_data, size);
4831 } else {
4832 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4833 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
4834 if (size < 0) {
4835 ret = size;
4836 goto err;
4837 }
4838 } else {
4839 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4840 }
4841 }
4842 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4843 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4844 /* extradata is Annex B, assume the bitstream is too and convert it */
4845 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4846 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4847 avio_write(pb, reformatted_data, size);
4848 } else {
4849 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4850 }
4851 #if CONFIG_AC3_PARSER
4852 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
4853 size = handle_eac3(mov, pkt, trk);
4854 if (size < 0)
4855 return size;
4856 else if (!size)
4857 goto end;
4858 avio_write(pb, pkt->data, size);
4859 #endif
4860 } else {
4861 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4862 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
4863 int nal_size_length = (par->extradata[4] & 0x3) + 1;
4864 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
4865 } else {
4866 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
4867 }
4868
4869 if (ret) {
4870 goto err;
4871 }
4872 } else {
4873 avio_write(pb, pkt->data, size);
4874 }
4875 }
4876
4877 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
4878 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4879 /* copy frame to create needed atoms */
4880 trk->vos_len = size;
4881 trk->vos_data = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
4882 if (!trk->vos_data) {
4883 ret = AVERROR(ENOMEM);
4884 goto err;
4885 }
4886 memcpy(trk->vos_data, pkt->data, size);
4887 memset(trk->vos_data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
4888 }
4889
4890 if (trk->entry >= trk->cluster_capacity) {
4891 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4892 void *cluster = av_realloc_array(trk->cluster, new_capacity, sizeof(*trk->cluster));
4893 if (!cluster) {
4894 ret = AVERROR(ENOMEM);
4895 goto err;
4896 }
4897 trk->cluster = cluster;
4898 trk->cluster_capacity = new_capacity;
4899 }
4900
4901 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
4902 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4903 trk->cluster[trk->entry].chunkNum = 0;
4904 trk->cluster[trk->entry].size = size;
4905 trk->cluster[trk->entry].entries = samples_in_chunk;
4906 trk->cluster[trk->entry].dts = pkt->dts;
4907 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4908 if (!trk->frag_discont) {
4909 /* First packet of a new fragment. We already wrote the duration
4910 * of the last packet of the previous fragment based on track_duration,
4911 * which might not exactly match our dts. Therefore adjust the dts
4912 * of this packet to be what the previous packets duration implies. */
4913 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4914 /* We also may have written the pts and the corresponding duration
4915 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
4916 * the next fragment. This means the cts of the first sample must
4917 * be the same in all fragments, unless end_pts was updated by
4918 * the packet causing the fragment to be written. */
4919 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
4920 mov->mode == MODE_ISM)
4921 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
4922 } else {
4923 /* New fragment, but discontinuous from previous fragments.
4924 * Pretend the duration sum of the earlier fragments is
4925 * pkt->dts - trk->start_dts. */
4926 trk->frag_start = pkt->dts - trk->start_dts;
4927 trk->end_pts = AV_NOPTS_VALUE;
4928 trk->frag_discont = 0;
4929 }
4930 }
4931
4932 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4933 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4934 /* Not using edit lists and shifting the first track to start from zero.
4935 * If the other streams start from a later timestamp, we won't be able
4936 * to signal the difference in starting time without an edit list.
4937 * Thus move the timestamp for this first sample to 0, increasing
4938 * its duration instead. */
4939 trk->cluster[trk->entry].dts = trk->start_dts = 0;
4940 }
4941 if (trk->start_dts == AV_NOPTS_VALUE) {
4942 trk->start_dts = pkt->dts;
4943 if (trk->frag_discont) {
4944 if (mov->use_editlist) {
4945 /* Pretend the whole stream started at pts=0, with earlier fragments
4946 * already written. If the stream started at pts=0, the duration sum
4947 * of earlier fragments would have been pkt->pts. */
4948 trk->frag_start = pkt->pts;
4949 trk->start_dts = pkt->dts - pkt->pts;
4950 } else {
4951 /* Pretend the whole stream started at dts=0, with earlier fragments
4952 * already written, with a duration summing up to pkt->dts. */
4953 trk->frag_start = pkt->dts;
4954 trk->start_dts = 0;
4955 }
4956 trk->frag_discont = 0;
4957 } else if (pkt->dts && mov->moov_written)
4958 av_log(s, AV_LOG_WARNING,
4959 "Track %d starts with a nonzero dts %"PRId64", while the moov "
4960 "already has been written. Set the delay_moov flag to handle "
4961 "this case.\n",
4962 pkt->stream_index, pkt->dts);
4963 }
4964 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4965 trk->last_sample_is_subtitle_end = 0;
4966
4967 if (pkt->pts == AV_NOPTS_VALUE) {
4968 av_log(s, AV_LOG_WARNING, "pts has no value\n");
4969 pkt->pts = pkt->dts;
4970 }
4971 if (pkt->dts != pkt->pts)
4972 trk->flags |= MOV_TRACK_CTTS;
4973 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
4974 trk->cluster[trk->entry].flags = 0;
4975 if (trk->start_cts == AV_NOPTS_VALUE)
4976 trk->start_cts = pkt->pts - pkt->dts;
4977 if (trk->end_pts == AV_NOPTS_VALUE)
4978 trk->end_pts = trk->cluster[trk->entry].dts +
4979 trk->cluster[trk->entry].cts + pkt->duration;
4980 else
4981 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
4982 trk->cluster[trk->entry].cts +
4983 pkt->duration);
4984
4985 if (par->codec_id == AV_CODEC_ID_VC1) {
4986 mov_parse_vc1_frame(pkt, trk);
4987 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4988 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4989 trk->entry > 0) { // force sync sample for the first key frame
4990 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4991 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4992 trk->flags |= MOV_TRACK_STPS;
4993 } else {
4994 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
4995 }
4996 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
4997 trk->has_keyframes++;
4998 }
4999 trk->entry++;
5000 trk->sample_count += samples_in_chunk;
5001 mov->mdat_size += size;
5002
5003 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5004 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5005 reformatted_data, size);
5006
5007 end:
5008 err:
5009
5010 av_free(reformatted_data);
5011 return ret;
5012 }
5013
5014 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5015 {
5016 MOVMuxContext *mov = s->priv_data;
5017 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5018 AVCodecParameters *par = trk->par;
5019 int64_t frag_duration = 0;
5020 int size = pkt->size;
5021
5022 int ret = check_pkt(s, pkt);
5023 if (ret < 0)
5024 return ret;
5025
5026 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5027 int i;
5028 for (i = 0; i < s->nb_streams; i++)
5029 mov->tracks[i].frag_discont = 1;
5030 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5031 }
5032
5033 if (!pkt->size) {
5034 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5035 trk->start_dts = pkt->dts;
5036 if (pkt->pts != AV_NOPTS_VALUE)
5037 trk->start_cts = pkt->pts - pkt->dts;
5038 else
5039 trk->start_cts = 0;
5040 }
5041
5042 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS) {
5043 int side_size = 0;
5044 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5045 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5046 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5047 if (!newextra)
5048 return AVERROR(ENOMEM);
5049 av_free(par->extradata);
5050 par->extradata = newextra;
5051 memcpy(par->extradata, side, side_size);
5052 par->extradata_size = side_size;
5053 mov->need_rewrite_extradata = 1;
5054 }
5055 }
5056
5057 return 0; /* Discard 0 sized packets */
5058 }
5059
5060 if (trk->entry && pkt->stream_index < s->nb_streams)
5061 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5062 s->streams[pkt->stream_index]->time_base,
5063 AV_TIME_BASE_Q);
5064 if ((mov->max_fragment_duration &&
5065 frag_duration >= mov->max_fragment_duration) ||
5066 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5067 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5068 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5069 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5070 if (frag_duration >= mov->min_fragment_duration) {
5071 // Set the duration of this track to line up with the next
5072 // sample in this track. This avoids relying on AVPacket
5073 // duration, but only helps for this particular track, not
5074 // for the other ones that are flushed at the same time.
5075 trk->track_duration = pkt->dts - trk->start_dts;
5076 if (pkt->pts != AV_NOPTS_VALUE)
5077 trk->end_pts = pkt->pts;
5078 else
5079 trk->end_pts = pkt->dts;
5080 trk->end_reliable = 1;
5081 mov_auto_flush_fragment(s, 0);
5082 }
5083 }
5084
5085 return ff_mov_write_packet(s, pkt);
5086 }
5087
5088 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5089 int stream_index,
5090 int64_t dts) {
5091 AVPacket end;
5092 uint8_t data[2] = {0};
5093 int ret;
5094
5095 av_init_packet(&end);
5096 end.size = sizeof(data);
5097 end.data = data;
5098 end.pts = dts;
5099 end.dts = dts;
5100 end.duration = 0;
5101 end.stream_index = stream_index;
5102
5103 ret = mov_write_single_packet(s, &end);
5104 av_packet_unref(&end);
5105
5106 return ret;
5107 }
5108
5109 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5110 {
5111 if (!pkt) {
5112 mov_flush_fragment(s, 1);
5113 return 1;
5114 } else {
5115 int i;
5116 MOVMuxContext *mov = s->priv_data;
5117 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5118
5119 if (!pkt->size)
5120 return mov_write_single_packet(s, pkt); /* Passthrough. */
5121
5122 /*
5123 * Subtitles require special handling.
5124 *
5125 * 1) For full complaince, every track must have a sample at
5126 * dts == 0, which is rarely true for subtitles. So, as soon
5127 * as we see any packet with dts > 0, write an empty subtitle
5128 * at dts == 0 for any subtitle track with no samples in it.
5129 *
5130 * 2) For each subtitle track, check if the current packet's
5131 * dts is past the duration of the last subtitle sample. If
5132 * so, we now need to write an end sample for that subtitle.
5133 *
5134 * This must be done conditionally to allow for subtitles that
5135 * immediately replace each other, in which case an end sample
5136 * is not needed, and is, in fact, actively harmful.
5137 *
5138 * 3) See mov_write_trailer for how the final end sample is
5139 * handled.
5140 */
5141 for (i = 0; i < mov->nb_streams; i++) {
5142 MOVTrack *trk = &mov->tracks[i];
5143 int ret;
5144
5145 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5146 trk->track_duration < pkt->dts &&
5147 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5148 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5149 if (ret < 0) return ret;
5150 trk->last_sample_is_subtitle_end = 1;
5151 }
5152 }
5153
5154 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5155 AVPacket *opkt = pkt;
5156 int reshuffle_ret, ret;
5157 if (trk->is_unaligned_qt_rgb) {
5158 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5159 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5160 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5161 if (reshuffle_ret < 0)
5162 return reshuffle_ret;
5163 } else
5164 reshuffle_ret = 0;
5165 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5166 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5167 if (ret < 0)
5168 goto fail;
5169 if (ret)
5170 trk->pal_done++;
5171 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5172 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5173 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5174 for (i = 0; i < pkt->size; i++)
5175 pkt->data[i] = ~pkt->data[i];
5176 }
5177 if (reshuffle_ret) {
5178 ret = mov_write_single_packet(s, pkt);
5179 fail:
5180 if (reshuffle_ret)
5181 av_packet_free(&pkt);
5182 return ret;
5183 }
5184 }
5185
5186 return mov_write_single_packet(s, pkt);
5187 }
5188 }
5189
5190 // QuickTime chapters involve an additional text track with the chapter names
5191 // as samples, and a tref pointing from the other tracks to the chapter one.
5192 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5193 {
5194 AVIOContext *pb;
5195
5196 MOVMuxContext *mov = s->priv_data;
5197 MOVTrack *track = &mov->tracks[tracknum];
5198 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5199 int i, len;
5200
5201 track->mode = mov->mode;
5202 track->tag = MKTAG('t','e','x','t');
5203 track->timescale = MOV_TIMESCALE;
5204 track->par = avcodec_parameters_alloc();
5205 if (!track->par)
5206 return AVERROR(ENOMEM);
5207 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5208 #if 0
5209 // These properties are required to make QT recognize the chapter track
5210 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5211 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5212 return AVERROR(ENOMEM);
5213 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5214 #else
5215 if (avio_open_dyn_buf(&pb) >= 0) {
5216 int size;
5217 uint8_t *buf;
5218
5219 /* Stub header (usually for Quicktime chapter track) */
5220 // TextSampleEntry
5221 avio_wb32(pb, 0x01); // displayFlags
5222 avio_w8(pb, 0x00); // horizontal justification
5223 avio_w8(pb, 0x00); // vertical justification
5224 avio_w8(pb, 0x00); // bgColourRed
5225 avio_w8(pb, 0x00); // bgColourGreen
5226 avio_w8(pb, 0x00); // bgColourBlue
5227 avio_w8(pb, 0x00); // bgColourAlpha
5228 // BoxRecord
5229 avio_wb16(pb, 0x00); // defTextBoxTop
5230 avio_wb16(pb, 0x00); // defTextBoxLeft
5231 avio_wb16(pb, 0x00); // defTextBoxBottom
5232 avio_wb16(pb, 0x00); // defTextBoxRight
5233 // StyleRecord
5234 avio_wb16(pb, 0x00); // startChar
5235 avio_wb16(pb, 0x00); // endChar
5236 avio_wb16(pb, 0x01); // fontID
5237 avio_w8(pb, 0x00); // fontStyleFlags
5238 avio_w8(pb, 0x00); // fontSize
5239 avio_w8(pb, 0x00); // fgColourRed
5240 avio_w8(pb, 0x00); // fgColourGreen
5241 avio_w8(pb, 0x00); // fgColourBlue
5242 avio_w8(pb, 0x00); // fgColourAlpha
5243 // FontTableBox
5244 avio_wb32(pb, 0x0D); // box size
5245 ffio_wfourcc(pb, "ftab"); // box atom name
5246 avio_wb16(pb, 0x01); // entry count
5247 // FontRecord
5248 avio_wb16(pb, 0x01); // font ID
5249 avio_w8(pb, 0x00); // font name length
5250
5251 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5252 track->par->extradata = buf;
5253 track->par->extradata_size = size;
5254 } else {
5255 av_freep(&buf);
5256 }
5257 }
5258 #endif
5259
5260 for (i = 0; i < s->nb_chapters; i++) {
5261 AVChapter *c = s->chapters[i];
5262 AVDictionaryEntry *t;
5263
5264 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5265 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5266 pkt.duration = end - pkt.dts;
5267
5268 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5269 static const char encd[12] = {
5270 0x00, 0x00, 0x00, 0x0C,
5271 'e', 'n', 'c', 'd',
5272 0x00, 0x00, 0x01, 0x00 };
5273 len = strlen(t->value);
5274 pkt.size = len + 2 + 12;
5275 pkt.data = av_malloc(pkt.size);
5276 if (!pkt.data)
5277 return AVERROR(ENOMEM);
5278 AV_WB16(pkt.data, len);
5279 memcpy(pkt.data + 2, t->value, len);
5280 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5281 ff_mov_write_packet(s, &pkt);
5282 av_freep(&pkt.data);
5283 }
5284 }
5285
5286 return 0;
5287 }
5288
5289
5290 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5291 {
5292 int ret;
5293
5294 /* compute the frame number */
5295 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5296 return ret;
5297 }
5298
5299 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5300 {
5301 int ret;
5302 MOVMuxContext *mov = s->priv_data;
5303 MOVTrack *track = &mov->tracks[index];
5304 AVStream *src_st = s->streams[src_index];
5305 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5306 AVRational rate = find_fps(s, src_st);
5307
5308 /* tmcd track based on video stream */
5309 track->mode = mov->mode;
5310 track->tag = MKTAG('t','m','c','d');
5311 track->src_track = src_index;
5312 track->timescale = mov->tracks[src_index].timescale;
5313 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5314 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5315
5316 /* set st to src_st for metadata access*/
5317 track->st = src_st;
5318
5319 /* encode context: tmcd data stream */
5320 track->par = avcodec_parameters_alloc();
5321 if (!track->par)
5322 return AVERROR(ENOMEM);
5323 track->par->codec_type = AVMEDIA_TYPE_DATA;
5324 track->par->codec_tag = track->tag;
5325 track->st->avg_frame_rate = av_inv_q(rate);
5326
5327 /* the tmcd track just contains one packet with the frame number */
5328 pkt.data = av_malloc(pkt.size);
5329 if (!pkt.data)
5330 return AVERROR(ENOMEM);
5331 AV_WB32(pkt.data, tc.start);
5332 ret = ff_mov_write_packet(s, &pkt);
5333 av_free(pkt.data);
5334 return ret;
5335 }
5336
5337 /*
5338 * st->disposition controls the "enabled" flag in the tkhd tag.
5339 * QuickTime will not play a track if it is not enabled. So make sure
5340 * that one track of each type (audio, video, subtitle) is enabled.
5341 *
5342 * Subtitles are special. For audio and video, setting "enabled" also
5343 * makes the track "default" (i.e. it is rendered when played). For
5344 * subtitles, an "enabled" subtitle is not rendered by default, but
5345 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5346 * empty!
5347 */
5348 static void enable_tracks(AVFormatContext *s)
5349 {
5350 MOVMuxContext *mov = s->priv_data;
5351 int i;
5352 int enabled[AVMEDIA_TYPE_NB];
5353 int first[AVMEDIA_TYPE_NB];
5354
5355 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5356 enabled[i] = 0;
5357 first[i] = -1;
5358 }
5359
5360 for (i = 0; i < s->nb_streams; i++) {
5361 AVStream *st = s->streams[i];
5362
5363 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5364 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5365 continue;
5366
5367 if (first[st->codecpar->codec_type] < 0)
5368 first[st->codecpar->codec_type] = i;
5369 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5370 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5371 enabled[st->codecpar->codec_type]++;
5372 }
5373 }
5374
5375 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5376 switch (i) {
5377 case AVMEDIA_TYPE_VIDEO:
5378 case AVMEDIA_TYPE_AUDIO:
5379 case AVMEDIA_TYPE_SUBTITLE:
5380 if (enabled[i] > 1)
5381 mov->per_stream_grouping = 1;
5382 if (!enabled[i] && first[i] >= 0)
5383 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5384 break;
5385 }
5386 }
5387 }
5388
5389 static void mov_free(AVFormatContext *s)
5390 {
5391 MOVMuxContext *mov = s->priv_data;
5392 int i;
5393
5394 if (mov->chapter_track) {
5395 if (mov->tracks[mov->chapter_track].par)
5396 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5397 av_freep(&mov->tracks[mov->chapter_track].par);
5398 }
5399
5400 for (i = 0; i < mov->nb_streams; i++) {
5401 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5402 ff_mov_close_hinting(&mov->tracks[i]);
5403 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5404 av_freep(&mov->tracks[i].par);
5405 av_freep(&mov->tracks[i].cluster);
5406 av_freep(&mov->tracks[i].frag_info);
5407
5408 if (mov->tracks[i].vos_len)
5409 av_freep(&mov->tracks[i].vos_data);
5410
5411 ff_mov_cenc_free(&mov->tracks[i].cenc);
5412 }
5413
5414 av_freep(&mov->tracks);
5415 }
5416
5417 static uint32_t rgb_to_yuv(uint32_t rgb)
5418 {
5419 uint8_t r, g, b;
5420 int y, cb, cr;
5421
5422 r = (rgb >> 16) & 0xFF;
5423 g = (rgb >> 8) & 0xFF;
5424 b = (rgb ) & 0xFF;
5425
5426 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5427 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5428 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5429
5430 return (y << 16) | (cr << 8) | cb;
5431 }
5432
5433 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5434 AVStream *st)
5435 {
5436 int i, width = 720, height = 480;
5437 int have_palette = 0, have_size = 0;
5438 uint32_t palette[16];
5439 char *cur = st->codecpar->extradata;
5440
5441 while (cur && *cur) {
5442 if (strncmp("palette:", cur, 8) == 0) {
5443 int i, count;
5444 count = sscanf(cur + 8,
5445 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5446 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5447 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5448 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5449 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5450 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5451 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5452 &palette[12], &palette[13], &palette[14], &palette[15]);
5453
5454 for (i = 0; i < count; i++) {
5455 palette[i] = rgb_to_yuv(palette[i]);
5456 }
5457 have_palette = 1;
5458 } else if (!strncmp("size:", cur, 5)) {
5459 sscanf(cur + 5, "%dx%d", &width, &height);
5460 have_size = 1;
5461 }
5462 if (have_palette && have_size)
5463 break;
5464 cur += strcspn(cur, "\n\r");
5465 cur += strspn(cur, "\n\r");
5466 }
5467 if (have_palette) {
5468 track->vos_data = av_malloc(16*4 + AV_INPUT_BUFFER_PADDING_SIZE);
5469 if (!track->vos_data)
5470 return AVERROR(ENOMEM);
5471 for (i = 0; i < 16; i++) {
5472 AV_WB32(track->vos_data + i * 4, palette[i]);
5473 }
5474 memset(track->vos_data + 16*4, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5475 track->vos_len = 16 * 4;
5476 }
5477 st->codecpar->width = width;
5478 st->codecpar->height = track->height = height;
5479
5480 return 0;
5481 }
5482
5483 static int mov_init(AVFormatContext *s)
5484 {
5485 MOVMuxContext *mov = s->priv_data;
5486 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5487 int i, ret, hint_track = 0, tmcd_track = 0;
5488
5489 mov->fc = s;
5490
5491 /* Default mode == MP4 */
5492 mov->mode = MODE_MP4;
5493
5494 if (s->oformat) {
5495 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5496 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5497 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5498 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5499 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5500 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5501 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5502 }
5503
5504 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5505 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5506
5507 /* Set the FRAGMENT flag if any of the fragmentation methods are
5508 * enabled. */
5509 if (mov->max_fragment_duration || mov->max_fragment_size ||
5510 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5511 FF_MOV_FLAG_FRAG_KEYFRAME |
5512 FF_MOV_FLAG_FRAG_CUSTOM))
5513 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5514
5515 /* Set other implicit flags immediately */
5516 if (mov->mode == MODE_ISM)
5517 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5518 FF_MOV_FLAG_FRAGMENT;
5519 if (mov->flags & FF_MOV_FLAG_DASH)
5520 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5521 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5522
5523 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5524 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5525 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5526 }
5527
5528 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5529 mov->reserved_moov_size = -1;
5530 }
5531
5532 if (mov->use_editlist < 0) {
5533 mov->use_editlist = 1;
5534 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5535 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5536 // If we can avoid needing an edit list by shifting the
5537 // tracks, prefer that over (trying to) write edit lists
5538 // in fragmented output.
5539 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5540 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5541 mov->use_editlist = 0;
5542 }
5543 }
5544 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5545 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5546 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5547
5548 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5549 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5550
5551 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5552 * if the latter is set that's enough and omit_tfhd_offset doesn't
5553 * add anything extra on top of that. */
5554 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5555 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5556 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5557
5558 if (mov->frag_interleave &&
5559 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5560 av_log(s, AV_LOG_ERROR,
5561 "Sample interleaving in fragments is mutually exclusive with "
5562 "omit_tfhd_offset and separate_moof\n");
5563 return AVERROR(EINVAL);
5564 }
5565
5566 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5567 * is enabled, we don't support non-seekable output at all. */
5568 if (!s->pb->seekable &&
5569 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5570 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5571 return AVERROR(EINVAL);
5572 }
5573
5574 mov->nb_streams = s->nb_streams;
5575 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5576 mov->chapter_track = mov->nb_streams++;
5577
5578 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5579 /* Add hint tracks for each audio and video stream */
5580 hint_track = mov->nb_streams;
5581 for (i = 0; i < s->nb_streams; i++) {
5582 AVStream *st = s->streams[i];
5583 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5584 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5585 mov->nb_streams++;
5586 }
5587 }
5588 }
5589
5590 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5591 || mov->write_tmcd == 1) {
5592 tmcd_track = mov->nb_streams;
5593
5594 /* +1 tmcd track for each video stream with a timecode */
5595 for (i = 0; i < s->nb_streams; i++) {
5596 AVStream *st = s->streams[i];
5597 AVDictionaryEntry *t = global_tcr;
5598 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5599 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5600 AVTimecode tc;
5601 ret = mov_check_timecode_track(s, &tc, i, t->value);
5602 if (ret >= 0)
5603 mov->nb_meta_tmcd++;
5604 }
5605 }
5606
5607 /* check if there is already a tmcd track to remux */
5608 if (mov->nb_meta_tmcd) {
5609 for (i = 0; i < s->nb_streams; i++) {
5610 AVStream *st = s->streams[i];
5611 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5612 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5613 "so timecode metadata are now ignored\n");
5614 mov->nb_meta_tmcd = 0;
5615 }
5616 }
5617 }
5618
5619 mov->nb_streams += mov->nb_meta_tmcd;
5620 }
5621
5622 // Reserve an extra stream for chapters for the case where chapters
5623 // are written in the trailer
5624 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5625 if (!mov->tracks)
5626 return AVERROR(ENOMEM);
5627
5628 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5629 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5630 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5631
5632 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5633 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5634 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5635 return AVERROR(EINVAL);
5636 }
5637
5638 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5639 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5640 mov->encryption_kid_len, CENC_KID_SIZE);
5641 return AVERROR(EINVAL);
5642 }
5643 } else {
5644 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5645 mov->encryption_scheme_str);
5646 return AVERROR(EINVAL);
5647 }
5648 }
5649
5650 for (i = 0; i < s->nb_streams; i++) {
5651 AVStream *st= s->streams[i];
5652 MOVTrack *track= &mov->tracks[i];
5653 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5654
5655 track->st = st;
5656 track->par = st->codecpar;
5657 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5658 if (track->language < 0)
5659 track->language = 0;
5660 track->mode = mov->mode;
5661 track->tag = mov_find_codec_tag(s, track);
5662 if (!track->tag) {
5663 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5664 "codec not currently supported in container\n",
5665 avcodec_get_name(st->codecpar->codec_id), i);
5666 return AVERROR(EINVAL);
5667 }
5668 /* If hinting of this track is enabled by a later hint track,
5669 * this is updated. */
5670 track->hint_track = -1;
5671 track->start_dts = AV_NOPTS_VALUE;
5672 track->start_cts = AV_NOPTS_VALUE;
5673 track->end_pts = AV_NOPTS_VALUE;
5674 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5675 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5676 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5677 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5678 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5679 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5680 return AVERROR(EINVAL);
5681 }
5682 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5683 }
5684 if (mov->video_track_timescale) {
5685 track->timescale = mov->video_track_timescale;
5686 } else {
5687 track->timescale = st->time_base.den;
5688 while(track->timescale < 10000)
5689 track->timescale *= 2;
5690 }
5691 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5692 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5693 return AVERROR(EINVAL);
5694 }
5695 if (track->mode == MODE_MOV && track->timescale > 100000)
5696 av_log(s, AV_LOG_WARNING,
5697 "WARNING codec timebase is very high. If duration is too long,\n"
5698 "file may not be playable by quicktime. Specify a shorter timebase\n"
5699 "or choose different container.\n");
5700 if (track->mode == MODE_MOV &&
5701 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5702 track->tag == MKTAG('r','a','w',' ')) {
5703 enum AVPixelFormat pix_fmt = track->par->format;
5704 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5705 pix_fmt = AV_PIX_FMT_MONOWHITE;
5706 track->is_unaligned_qt_rgb =
5707 pix_fmt == AV_PIX_FMT_RGB24 ||
5708 pix_fmt == AV_PIX_FMT_BGR24 ||
5709 pix_fmt == AV_PIX_FMT_PAL8 ||
5710 pix_fmt == AV_PIX_FMT_GRAY8 ||
5711 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5712 pix_fmt == AV_PIX_FMT_MONOBLACK;
5713 }
5714 if (track->mode == MODE_MP4 &&
5715 track->par->codec_id == AV_CODEC_ID_VP9) {
5716 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
5717 av_log(s, AV_LOG_ERROR,
5718 "VP9 in MP4 support is experimental, add "
5719 "'-strict %d' if you want to use it.\n",
5720 FF_COMPLIANCE_EXPERIMENTAL);
5721 return AVERROR_EXPERIMENTAL;
5722 }
5723 }
5724 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5725 track->timescale = st->codecpar->sample_rate;
5726 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
5727 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
5728 track->audio_vbr = 1;
5729 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
5730 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
5731 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
5732 if (!st->codecpar->block_align) {
5733 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
5734 return AVERROR(EINVAL);
5735 }
5736 track->sample_size = st->codecpar->block_align;
5737 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
5738 track->audio_vbr = 1;
5739 }else{
5740 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
5741 }
5742 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
5743 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
5744 track->audio_vbr = 1;
5745 }
5746 if (track->mode != MODE_MOV &&
5747 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
5748 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
5749 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
5750 i, track->par->sample_rate);
5751 return AVERROR(EINVAL);
5752 } else {
5753 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
5754 i, track->par->sample_rate);
5755 }
5756 }
5757 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5758 track->timescale = st->time_base.den;
5759 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
5760 track->timescale = st->time_base.den;
5761 } else {
5762 track->timescale = MOV_TIMESCALE;
5763 }
5764 if (!track->height)
5765 track->height = st->codecpar->height;
5766 /* The ism specific timescale isn't mandatory, but is assumed by
5767 * some tools, such as mp4split. */
5768 if (mov->mode == MODE_ISM)
5769 track->timescale = 10000000;
5770
5771 avpriv_set_pts_info(st, 64, 1, track->timescale);
5772
5773 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5774 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
5775 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
5776 if (ret)
5777 return ret;
5778 }
5779 }
5780
5781 enable_tracks(s);
5782 return 0;
5783 }
5784
5785 static int mov_write_header(AVFormatContext *s)
5786 {
5787 AVIOContext *pb = s->pb;
5788 MOVMuxContext *mov = s->priv_data;
5789 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5790 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
5791
5792 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5793 nb_tracks++;
5794
5795 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5796 /* Add hint tracks for each audio and video stream */
5797 hint_track = nb_tracks;
5798 for (i = 0; i < s->nb_streams; i++) {
5799 AVStream *st = s->streams[i];
5800 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5801 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5802 nb_tracks++;
5803 }
5804 }
5805 }
5806
5807 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5808 tmcd_track = nb_tracks;
5809
5810 for (i = 0; i < s->nb_streams; i++) {
5811 int j;
5812 AVStream *st= s->streams[i];
5813 MOVTrack *track= &mov->tracks[i];
5814
5815 /* copy extradata if it exists */
5816 if (st->codecpar->extradata_size) {
5817 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
5818 mov_create_dvd_sub_decoder_specific_info(track, st);
5819 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
5820 track->vos_len = st->codecpar->extradata_size;
5821 track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
5822 if (!track->vos_data) {
5823 return AVERROR(ENOMEM);
5824 }
5825 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
5826 memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5827 }
5828 }
5829
5830 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5831 track->par->channel_layout != AV_CH_LAYOUT_MONO)
5832 continue;
5833
5834 for (j = 0; j < s->nb_streams; j++) {
5835 AVStream *stj= s->streams[j];
5836 MOVTrack *trackj= &mov->tracks[j];
5837 if (j == i)
5838 continue;
5839
5840 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5841 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
5842 trackj->language != track->language ||
5843 trackj->tag != track->tag
5844 )
5845 continue;
5846 track->multichannel_as_mono++;
5847 }
5848 }
5849
5850 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5851 if ((ret = mov_write_identification(pb, s)) < 0)
5852 return ret;
5853 }
5854
5855 if (mov->reserved_moov_size){
5856 mov->reserved_header_pos = avio_tell(pb);
5857 if (mov->reserved_moov_size > 0)
5858 avio_skip(pb, mov->reserved_moov_size);
5859 }
5860
5861 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5862 /* If no fragmentation options have been set, set a default. */
5863 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
5864 FF_MOV_FLAG_FRAG_CUSTOM)) &&
5865 !mov->max_fragment_duration && !mov->max_fragment_size)
5866 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
5867 } else {
5868 if (mov->flags & FF_MOV_FLAG_FASTSTART)
5869 mov->reserved_header_pos = avio_tell(pb);
5870 mov_write_mdat_tag(pb, mov);
5871 }
5872
5873 ff_parse_creation_time_metadata(s, &mov->time, 1);
5874 if (mov->time)
5875 mov->time += 0x7C25B080; // 1970 based -> 1904 based
5876
5877 if (mov->chapter_track)
5878 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5879 return ret;
5880
5881 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5882 /* Initialize the hint tracks for each audio and video stream */
5883 for (i = 0; i < s->nb_streams; i++) {
5884 AVStream *st = s->streams[i];
5885 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5886 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5887 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
5888 return ret;
5889 hint_track++;
5890 }
5891 }
5892 }
5893
5894 if (mov->nb_meta_tmcd) {
5895 /* Initialize the tmcd tracks */
5896 for (i = 0; i < s->nb_streams; i++) {
5897 AVStream *st = s->streams[i];
5898 t = global_tcr;
5899
5900 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5901 AVTimecode tc;
5902 if (!t)
5903 t = av_dict_get(st->metadata, "timecode", NULL, 0);
5904 if (!t)
5905 continue;
5906 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
5907 continue;
5908 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
5909 return ret;
5910 tmcd_track++;
5911 }
5912 }
5913 }
5914
5915 avio_flush(pb);
5916
5917 if (mov->flags & FF_MOV_FLAG_ISML)
5918 mov_write_isml_manifest(pb, mov, s);
5919
5920 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5921 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5922 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
5923 return ret;
5924 avio_flush(pb);
5925 mov->moov_written = 1;
5926 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5927 mov->reserved_header_pos = avio_tell(pb);
5928 }
5929
5930 return 0;
5931 }
5932
5933 static int get_moov_size(AVFormatContext *s)
5934 {
5935 int ret;
5936 AVIOContext *moov_buf;
5937 MOVMuxContext *mov = s->priv_data;
5938
5939 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
5940 return ret;
5941 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
5942 return ret;
5943 return ffio_close_null_buf(moov_buf);
5944 }
5945
5946 static int get_sidx_size(AVFormatContext *s)
5947 {
5948 int ret;
5949 AVIOContext *buf;
5950 MOVMuxContext *mov = s->priv_data;
5951
5952 if ((ret = ffio_open_null_buf(&buf)) < 0)
5953 return ret;
5954 mov_write_sidx_tags(buf, mov, -1, 0);
5955 return ffio_close_null_buf(buf);
5956 }
5957
5958 /*
5959 * This function gets the moov size if moved to the top of the file: the chunk
5960 * offset table can switch between stco (32-bit entries) to co64 (64-bit
5961 * entries) when the moov is moved to the beginning, so the size of the moov
5962 * would change. It also updates the chunk offset tables.
5963 */
5964 static int compute_moov_size(AVFormatContext *s)
5965 {
5966 int i, moov_size, moov_size2;
5967 MOVMuxContext *mov = s->priv_data;
5968
5969 moov_size = get_moov_size(s);
5970 if (moov_size < 0)
5971 return moov_size;
5972
5973 for (i = 0; i < mov->nb_streams; i++)
5974 mov->tracks[i].data_offset += moov_size;
5975
5976 moov_size2 = get_moov_size(s);
5977 if (moov_size2 < 0)
5978 return moov_size2;
5979
5980 /* if the size changed, we just switched from stco to co64 and need to
5981 * update the offsets */
5982 if (moov_size2 != moov_size)
5983 for (i = 0; i < mov->nb_streams; i++)
5984 mov->tracks[i].data_offset += moov_size2 - moov_size;
5985
5986 return moov_size2;
5987 }
5988
5989 static int compute_sidx_size(AVFormatContext *s)
5990 {
5991 int i, sidx_size;
5992 MOVMuxContext *mov = s->priv_data;
5993
5994 sidx_size = get_sidx_size(s);
5995 if (sidx_size < 0)
5996 return sidx_size;
5997
5998 for (i = 0; i < mov->nb_streams; i++)
5999 mov->tracks[i].data_offset += sidx_size;
6000
6001 return sidx_size;
6002 }
6003
6004 static int shift_data(AVFormatContext *s)
6005 {
6006 int ret = 0, moov_size;
6007 MOVMuxContext *mov = s->priv_data;
6008 int64_t pos, pos_end = avio_tell(s->pb);
6009 uint8_t *buf, *read_buf[2];
6010 int read_buf_id = 0;
6011 int read_size[2];
6012 AVIOContext *read_pb;
6013
6014 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6015 moov_size = compute_sidx_size(s);
6016 else
6017 moov_size = compute_moov_size(s);
6018 if (moov_size < 0)
6019 return moov_size;
6020
6021 buf = av_malloc(moov_size * 2);
6022 if (!buf)
6023 return AVERROR(ENOMEM);
6024 read_buf[0] = buf;
6025 read_buf[1] = buf + moov_size;
6026
6027 /* Shift the data: the AVIO context of the output can only be used for
6028 * writing, so we re-open the same output, but for reading. It also avoids
6029 * a read/seek/write/seek back and forth. */
6030 avio_flush(s->pb);
6031 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6032 if (ret < 0) {
6033 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6034 "the second pass (faststart)\n", s->filename);
6035 goto end;
6036 }
6037
6038 /* mark the end of the shift to up to the last data we wrote, and get ready
6039 * for writing */
6040 pos_end = avio_tell(s->pb);
6041 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6042
6043 /* start reading at where the new moov will be placed */
6044 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6045 pos = avio_tell(read_pb);
6046
6047 #define READ_BLOCK do { \
6048 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6049 read_buf_id ^= 1; \
6050 } while (0)
6051
6052 /* shift data by chunk of at most moov_size */
6053 READ_BLOCK;
6054 do {
6055 int n;
6056 READ_BLOCK;
6057 n = read_size[read_buf_id];
6058 if (n <= 0)
6059 break;
6060 avio_write(s->pb, read_buf[read_buf_id], n);
6061 pos += n;
6062 } while (pos < pos_end);
6063 ff_format_io_close(s, &read_pb);
6064
6065 end:
6066 av_free(buf);
6067 return ret;
6068 }
6069
6070 static int mov_write_trailer(AVFormatContext *s)
6071 {
6072 MOVMuxContext *mov = s->priv_data;
6073 AVIOContext *pb = s->pb;
6074 int res = 0;
6075 int i;
6076 int64_t moov_pos;
6077
6078 if (mov->need_rewrite_extradata) {
6079 for (i = 0; i < s->nb_streams; i++) {
6080 MOVTrack *track = &mov->tracks[i];
6081 AVCodecParameters *par = track->par;
6082
6083 track->vos_len = par->extradata_size;
6084 track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
6085 if (!track->vos_data)
6086 return AVERROR(ENOMEM);
6087 memcpy(track->vos_data, par->extradata, track->vos_len);
6088 memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6089 }
6090 mov->need_rewrite_extradata = 0;
6091 }
6092
6093 /*
6094 * Before actually writing the trailer, make sure that there are no
6095 * dangling subtitles, that need a terminating sample.
6096 */
6097 for (i = 0; i < mov->nb_streams; i++) {
6098 MOVTrack *trk = &mov->tracks[i];
6099 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6100 !trk->last_sample_is_subtitle_end) {
6101 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6102 trk->last_sample_is_subtitle_end = 1;
6103 }
6104 }
6105
6106 // If there were no chapters when the header was written, but there
6107 // are chapters now, write them in the trailer. This only works
6108 // when we are not doing fragments.
6109 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6110 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6111 mov->chapter_track = mov->nb_streams++;
6112 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6113 return res;
6114 }
6115 }
6116
6117 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6118 moov_pos = avio_tell(pb);
6119
6120 /* Write size of mdat tag */
6121 if (mov->mdat_size + 8 <= UINT32_MAX) {
6122 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6123 avio_wb32(pb, mov->mdat_size + 8);
6124 } else {
6125 /* overwrite 'wide' placeholder atom */
6126 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6127 /* special value: real atom size will be 64 bit value after
6128 * tag field */
6129 avio_wb32(pb, 1);
6130 ffio_wfourcc(pb, "mdat");
6131 avio_wb64(pb, mov->mdat_size + 16);
6132 }
6133 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6134
6135 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6136 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6137 res = shift_data(s);
6138 if (res < 0)
6139 return res;
6140 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6141 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6142 return res;
6143 } else if (mov->reserved_moov_size > 0) {
6144 int64_t size;
6145 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6146 return res;
6147 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6148 if (size < 8){
6149 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6150 return AVERROR(EINVAL);
6151 }
6152 avio_wb32(pb, size);
6153 ffio_wfourcc(pb, "free");
6154 ffio_fill(pb, 0, size - 8);
6155 avio_seek(pb, moov_pos, SEEK_SET);
6156 } else {
6157 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6158 return res;
6159 }
6160 res = 0;
6161 } else {
6162 mov_auto_flush_fragment(s, 1);
6163 for (i = 0; i < mov->nb_streams; i++)
6164 mov->tracks[i].data_offset = 0;
6165 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6166 int64_t end;
6167 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6168 res = shift_data(s);
6169 if (res < 0)
6170 return res;
6171 end = avio_tell(pb);
6172 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6173 mov_write_sidx_tags(pb, mov, -1, 0);
6174 avio_seek(pb, end, SEEK_SET);
6175 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6176 mov_write_mfra_tag(pb, mov);
6177 } else {
6178 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6179 mov_write_mfra_tag(pb, mov);
6180 }
6181 }
6182
6183 return res;
6184 }
6185
6186 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6187 {
6188 int ret = 1;
6189 AVStream *st = s->streams[pkt->stream_index];
6190
6191 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6192 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6193 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6194 }
6195
6196 return ret;
6197 }
6198
6199 #if CONFIG_MOV_MUXER
6200 MOV_CLASS(mov)
6201 AVOutputFormat ff_mov_muxer = {
6202 .name = "mov",
6203 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6204 .extensions = "mov",
6205 .priv_data_size = sizeof(MOVMuxContext),
6206 .audio_codec = AV_CODEC_ID_AAC,
6207 .video_codec = CONFIG_LIBX264_ENCODER ?
6208 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6209 .init = mov_init,
6210 .write_header = mov_write_header,
6211 .write_packet = mov_write_packet,
6212 .write_trailer = mov_write_trailer,
6213 .deinit = mov_free,
6214 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6215 .codec_tag = (const AVCodecTag* const []){
6216 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6217 },
6218 .check_bitstream = mov_check_bitstream,
6219 .priv_class = &mov_muxer_class,
6220 };
6221 #endif
6222 #if CONFIG_TGP_MUXER
6223 MOV_CLASS(tgp)
6224 AVOutputFormat ff_tgp_muxer = {
6225 .name = "3gp",
6226 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6227 .extensions = "3gp",
6228 .priv_data_size = sizeof(MOVMuxContext),
6229 .audio_codec = AV_CODEC_ID_AMR_NB,
6230 .video_codec = AV_CODEC_ID_H263,
6231 .init = mov_init,
6232 .write_header = mov_write_header,
6233 .write_packet = mov_write_packet,
6234 .write_trailer = mov_write_trailer,
6235 .deinit = mov_free,
6236 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6237 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6238 .check_bitstream = mov_check_bitstream,
6239 .priv_class = &tgp_muxer_class,
6240 };
6241 #endif
6242 #if CONFIG_MP4_MUXER
6243 MOV_CLASS(mp4)
6244 AVOutputFormat ff_mp4_muxer = {
6245 .name = "mp4",
6246 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6247 .mime_type = "video/mp4",
6248 .extensions = "mp4",
6249 .priv_data_size = sizeof(MOVMuxContext),
6250 .audio_codec = AV_CODEC_ID_AAC,
6251 .video_codec = CONFIG_LIBX264_ENCODER ?
6252 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6253 .init = mov_init,
6254 .write_header = mov_write_header,
6255 .write_packet = mov_write_packet,
6256 .write_trailer = mov_write_trailer,
6257 .deinit = mov_free,
6258 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6259 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6260 .check_bitstream = mov_check_bitstream,
6261 .priv_class = &mp4_muxer_class,
6262 };
6263 #endif
6264 #if CONFIG_PSP_MUXER
6265 MOV_CLASS(psp)
6266 AVOutputFormat ff_psp_muxer = {
6267 .name = "psp",
6268 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6269 .extensions = "mp4,psp",
6270 .priv_data_size = sizeof(MOVMuxContext),
6271 .audio_codec = AV_CODEC_ID_AAC,
6272 .video_codec = CONFIG_LIBX264_ENCODER ?
6273 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6274 .init = mov_init,
6275 .write_header = mov_write_header,
6276 .write_packet = mov_write_packet,
6277 .write_trailer = mov_write_trailer,
6278 .deinit = mov_free,
6279 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6280 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6281 .check_bitstream = mov_check_bitstream,
6282 .priv_class = &psp_muxer_class,
6283 };
6284 #endif
6285 #if CONFIG_TG2_MUXER
6286 MOV_CLASS(tg2)
6287 AVOutputFormat ff_tg2_muxer = {
6288 .name = "3g2",
6289 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6290 .extensions = "3g2",
6291 .priv_data_size = sizeof(MOVMuxContext),
6292 .audio_codec = AV_CODEC_ID_AMR_NB,
6293 .video_codec = AV_CODEC_ID_H263,
6294 .init = mov_init,
6295 .write_header = mov_write_header,
6296 .write_packet = mov_write_packet,
6297 .write_trailer = mov_write_trailer,
6298 .deinit = mov_free,
6299 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6300 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6301 .check_bitstream = mov_check_bitstream,
6302 .priv_class = &tg2_muxer_class,
6303 };
6304 #endif
6305 #if CONFIG_IPOD_MUXER
6306 MOV_CLASS(ipod)
6307 AVOutputFormat ff_ipod_muxer = {
6308 .name = "ipod",
6309 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6310 .mime_type = "video/mp4",
6311 .extensions = "m4v,m4a",
6312 .priv_data_size = sizeof(MOVMuxContext),
6313 .audio_codec = AV_CODEC_ID_AAC,
6314 .video_codec = AV_CODEC_ID_H264,
6315 .init = mov_init,
6316 .write_header = mov_write_header,
6317 .write_packet = mov_write_packet,
6318 .write_trailer = mov_write_trailer,
6319 .deinit = mov_free,
6320 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6321 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6322 .check_bitstream = mov_check_bitstream,
6323 .priv_class = &ipod_muxer_class,
6324 };
6325 #endif
6326 #if CONFIG_ISMV_MUXER
6327 MOV_CLASS(ismv)
6328 AVOutputFormat ff_ismv_muxer = {
6329 .name = "ismv",
6330 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6331 .mime_type = "video/mp4",
6332 .extensions = "ismv,isma",
6333 .priv_data_size = sizeof(MOVMuxContext),
6334 .audio_codec = AV_CODEC_ID_AAC,
6335 .video_codec = AV_CODEC_ID_H264,
6336 .init = mov_init,
6337 .write_header = mov_write_header,
6338 .write_packet = mov_write_packet,
6339 .write_trailer = mov_write_trailer,
6340 .deinit = mov_free,
6341 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6342 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6343 .check_bitstream = mov_check_bitstream,
6344 .priv_class = &ismv_muxer_class,
6345 };
6346 #endif
6347 #if CONFIG_F4V_MUXER
6348 MOV_CLASS(f4v)
6349 AVOutputFormat ff_f4v_muxer = {
6350 .name = "f4v",
6351 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6352 .mime_type = "application/f4v",
6353 .extensions = "f4v",
6354 .priv_data_size = sizeof(MOVMuxContext),
6355 .audio_codec = AV_CODEC_ID_AAC,
6356 .video_codec = AV_CODEC_ID_H264,
6357 .init = mov_init,
6358 .write_header = mov_write_header,
6359 .write_packet = mov_write_packet,
6360 .write_trailer = mov_write_trailer,
6361 .deinit = mov_free,
6362 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6363 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6364 .check_bitstream = mov_check_bitstream,
6365 .priv_class = &f4v_muxer_class,
6366 };
6367 #endif