Use bitstream_init8() where appropriate
[libav.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 Libav.
8 *
9 * Libav 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 * Libav 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 Libav; 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
35 #include "libavcodec/bitstream.h"
36 #include "libavcodec/put_bits.h"
37 #include "libavcodec/vc1_common.h"
38 #include "internal.h"
39 #include "libavutil/avstring.h"
40 #include "libavutil/intfloat.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/opt.h"
43 #include "libavutil/dict.h"
44 #include "hevc.h"
45 #include "rtpenc.h"
46 #include "mov_chan.h"
47
48 static const AVOption options[] = {
49 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
50 { "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" },
51 { "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" },
52 { "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" },
53 { "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" },
54 { "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" },
55 { "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" },
56 { "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" },
57 { "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" },
58 { "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" },
59 { "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" },
60 { "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" },
61 { "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" },
62 { "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" },
63 { "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" },
64 { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
66 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
67 { "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},
68 { "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},
69 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
70 { "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},
71 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
72 { "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},
73 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
74 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
75 { "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},
76 { "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 },
77 { NULL },
78 };
79
80 #define MOV_CLASS(flavor)\
81 static const AVClass flavor ## _muxer_class = {\
82 .class_name = #flavor " muxer",\
83 .item_name = av_default_item_name,\
84 .option = options,\
85 .version = LIBAVUTIL_VERSION_INT,\
86 };
87
88 static int utf8len(const uint8_t *b)
89 {
90 int len = 0;
91 int val;
92 while (*b) {
93 GET_UTF8(val, *b++, return -1;)
94 len++;
95 }
96 return len;
97 }
98
99 //FIXME support 64 bit variant with wide placeholders
100 static int64_t update_size(AVIOContext *pb, int64_t pos)
101 {
102 int64_t curpos = avio_tell(pb);
103 avio_seek(pb, pos, SEEK_SET);
104 avio_wb32(pb, curpos - pos); /* rewrite size */
105 avio_seek(pb, curpos, SEEK_SET);
106
107 return curpos - pos;
108 }
109
110 static int co64_required(const MOVTrack *track)
111 {
112 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
113 return 1;
114 return 0;
115 }
116
117 /* Chunk offset atom */
118 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
119 {
120 int i;
121 int mode64 = co64_required(track); // use 32 bit size variant if possible
122 int64_t pos = avio_tell(pb);
123 avio_wb32(pb, 0); /* size */
124 if (mode64) {
125 ffio_wfourcc(pb, "co64");
126 } else
127 ffio_wfourcc(pb, "stco");
128 avio_wb32(pb, 0); /* version & flags */
129 avio_wb32(pb, track->entry); /* entry count */
130 for (i = 0; i < track->entry; i++) {
131 if (mode64 == 1)
132 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
133 else
134 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
135 }
136 return update_size(pb, pos);
137 }
138
139 /* Sample size atom */
140 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
141 {
142 int equalChunks = 1;
143 int i, j, entries = 0, tst = -1, oldtst = -1;
144
145 int64_t pos = avio_tell(pb);
146 avio_wb32(pb, 0); /* size */
147 ffio_wfourcc(pb, "stsz");
148 avio_wb32(pb, 0); /* version & flags */
149
150 for (i = 0; i < track->entry; i++) {
151 tst = track->cluster[i].size / track->cluster[i].entries;
152 if (oldtst != -1 && tst != oldtst)
153 equalChunks = 0;
154 oldtst = tst;
155 entries += track->cluster[i].entries;
156 }
157 if (equalChunks && track->entry) {
158 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
159 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
160 avio_wb32(pb, sSize); // sample size
161 avio_wb32(pb, entries); // sample count
162 } else {
163 avio_wb32(pb, 0); // sample size
164 avio_wb32(pb, entries); // sample count
165 for (i = 0; i < track->entry; i++) {
166 for (j = 0; j < track->cluster[i].entries; j++) {
167 avio_wb32(pb, track->cluster[i].size /
168 track->cluster[i].entries);
169 }
170 }
171 }
172 return update_size(pb, pos);
173 }
174
175 /* Sample to chunk atom */
176 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
177 {
178 int index = 0, oldval = -1, i;
179 int64_t entryPos, curpos;
180
181 int64_t pos = avio_tell(pb);
182 avio_wb32(pb, 0); /* size */
183 ffio_wfourcc(pb, "stsc");
184 avio_wb32(pb, 0); // version & flags
185 entryPos = avio_tell(pb);
186 avio_wb32(pb, track->entry); // entry count
187 for (i = 0; i < track->entry; i++) {
188 if (oldval != track->cluster[i].samples_in_chunk) {
189 avio_wb32(pb, i + 1); // first chunk
190 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
191 avio_wb32(pb, 0x1); // sample description index
192 oldval = track->cluster[i].samples_in_chunk;
193 index++;
194 }
195 }
196 curpos = avio_tell(pb);
197 avio_seek(pb, entryPos, SEEK_SET);
198 avio_wb32(pb, index); // rewrite size
199 avio_seek(pb, curpos, SEEK_SET);
200
201 return update_size(pb, pos);
202 }
203
204 /* Sync sample atom */
205 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
206 {
207 int64_t curpos, entryPos;
208 int i, index = 0;
209 int64_t pos = avio_tell(pb);
210 avio_wb32(pb, 0); // size
211 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
212 avio_wb32(pb, 0); // version & flags
213 entryPos = avio_tell(pb);
214 avio_wb32(pb, track->entry); // entry count
215 for (i = 0; i < track->entry; i++) {
216 if (track->cluster[i].flags & flag) {
217 avio_wb32(pb, i + 1);
218 index++;
219 }
220 }
221 curpos = avio_tell(pb);
222 avio_seek(pb, entryPos, SEEK_SET);
223 avio_wb32(pb, index); // rewrite size
224 avio_seek(pb, curpos, SEEK_SET);
225 return update_size(pb, pos);
226 }
227
228 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
229 {
230 avio_wb32(pb, 0x11); /* size */
231 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
232 else ffio_wfourcc(pb, "damr");
233 ffio_wfourcc(pb, "FFMP");
234 avio_w8(pb, 0); /* decoder version */
235
236 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
237 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
238 avio_w8(pb, 0x01); /* Frames per sample */
239 return 0x11;
240 }
241
242 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
243 {
244 BitstreamContext bc;
245 PutBitContext pbc;
246 uint8_t buf[3];
247 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
248
249 if (track->vos_len < 7)
250 return -1;
251
252 avio_wb32(pb, 11);
253 ffio_wfourcc(pb, "dac3");
254
255 bitstream_init8(&bc, track->vos_data + 4, track->vos_len - 4);
256 fscod = bitstream_read(&bc, 2);
257 frmsizecod = bitstream_read(&bc, 6);
258 bsid = bitstream_read(&bc, 5);
259 bsmod = bitstream_read(&bc, 3);
260 acmod = bitstream_read(&bc, 3);
261 if (acmod == 2) {
262 bitstream_skip(&bc, 2); // dsurmod
263 } else {
264 if ((acmod & 1) && acmod != 1)
265 bitstream_skip(&bc, 2); // cmixlev
266 if (acmod & 4)
267 bitstream_skip(&bc, 2); // surmixlev
268 }
269 lfeon = bitstream_read_bit(&bc);
270
271 init_put_bits(&pbc, buf, sizeof(buf));
272 put_bits(&pbc, 2, fscod);
273 put_bits(&pbc, 5, bsid);
274 put_bits(&pbc, 3, bsmod);
275 put_bits(&pbc, 3, acmod);
276 put_bits(&pbc, 1, lfeon);
277 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
278 put_bits(&pbc, 5, 0); // reserved
279
280 flush_put_bits(&pbc);
281 avio_write(pb, buf, sizeof(buf));
282
283 return 11;
284 }
285
286 /**
287 * This function writes extradata "as is".
288 * Extradata must be formatted like a valid atom (with size and tag).
289 */
290 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
291 {
292 avio_write(pb, track->par->extradata, track->par->extradata_size);
293 return track->par->extradata_size;
294 }
295
296 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
297 {
298 int i = 3;
299 avio_w8(pb, tag);
300 for (; i > 0; i--)
301 avio_w8(pb, (size >> (7 * i)) | 0x80);
302 avio_w8(pb, size & 0x7F);
303 }
304
305 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
306 {
307 AVCPBProperties *props;
308 int64_t pos = avio_tell(pb);
309 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
310
311 avio_wb32(pb, 0); // size
312 ffio_wfourcc(pb, "esds");
313 avio_wb32(pb, 0); // Version
314
315 // ES descriptor
316 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
317 avio_wb16(pb, track->track_id);
318 avio_w8(pb, 0x00); // flags (= no flags)
319
320 // DecoderConfig descriptor
321 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
322
323 // Object type indication
324 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
325 track->par->codec_id == AV_CODEC_ID_MP3) &&
326 track->par->sample_rate > 24000)
327 avio_w8(pb, 0x6B); // 11172-3
328 else
329 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
330
331 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
332 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
333 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
334 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
335 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
336 avio_w8(pb, 0x15); // flags (= Audiostream)
337 else
338 avio_w8(pb, 0x11); // flags (= Visualstream)
339
340 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
341 NULL);
342
343 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
344
345 avio_wb32(pb, props ? FFMAX(props->max_bitrate, props->avg_bitrate) : track->par->bit_rate); // maxbitrate (FIXME should be max rate in any 1 sec window)
346 if (!props || !props->min_bitrate || props->max_bitrate != props->min_bitrate)
347 avio_wb32(pb, 0); // vbr
348 else
349 avio_wb32(pb, props->max_bitrate); // avg bitrate
350
351 if (track->vos_len) {
352 // DecoderSpecific info descriptor
353 put_descr(pb, 0x05, track->vos_len);
354 avio_write(pb, track->vos_data, track->vos_len);
355 }
356
357 // SL descriptor
358 put_descr(pb, 0x06, 1);
359 avio_w8(pb, 0x02);
360 return update_size(pb, pos);
361 }
362
363 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
364 {
365 int64_t pos = avio_tell(pb);
366 avio_wb32(pb, 0);
367 avio_wl32(pb, track->tag); // store it byteswapped
368 track->par->codec_tag = av_bswap16(track->tag >> 16);
369 ff_put_wav_header(s, pb, track->st->codecpar);
370 return update_size(pb, pos);
371 }
372
373 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
374 {
375 int64_t pos = avio_tell(pb);
376 avio_wb32(pb, 0);
377 ffio_wfourcc(pb, "wfex");
378 ff_put_wav_header(s, pb, track->st->codecpar);
379 return update_size(pb, pos);
380 }
381
382 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
383 {
384 uint32_t layout_tag, bitmap;
385 int64_t pos = avio_tell(pb);
386
387 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
388 track->par->channel_layout,
389 &bitmap);
390 if (!layout_tag) {
391 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
392 "lack of channel information\n");
393 return 0;
394 }
395
396 avio_wb32(pb, 0); // Size
397 ffio_wfourcc(pb, "chan"); // Type
398 avio_w8(pb, 0); // Version
399 avio_wb24(pb, 0); // Flags
400 avio_wb32(pb, layout_tag); // mChannelLayoutTag
401 avio_wb32(pb, bitmap); // mChannelBitmap
402 avio_wb32(pb, 0); // mNumberChannelDescriptions
403
404 return update_size(pb, pos);
405 }
406
407 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
408 {
409 int64_t pos = avio_tell(pb);
410
411 avio_wb32(pb, 0); /* size */
412 ffio_wfourcc(pb, "wave");
413
414 avio_wb32(pb, 12); /* size */
415 ffio_wfourcc(pb, "frma");
416 avio_wl32(pb, track->tag);
417
418 if (track->par->codec_id == AV_CODEC_ID_AAC) {
419 /* useless atom needed by mplayer, ipod, not needed by quicktime */
420 avio_wb32(pb, 12); /* size */
421 ffio_wfourcc(pb, "mp4a");
422 avio_wb32(pb, 0);
423 mov_write_esds_tag(pb, track);
424 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
425 mov_write_amr_tag(pb, track);
426 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
427 mov_write_ac3_tag(pb, track);
428 } else if (track->par->codec_id == AV_CODEC_ID_ALAC) {
429 mov_write_extradata_tag(pb, track);
430 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
431 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
432 mov_write_ms_tag(s, pb, track);
433 }
434
435 avio_wb32(pb, 8); /* size */
436 avio_wb32(pb, 0); /* null tag */
437
438 return update_size(pb, pos);
439 }
440
441 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
442 {
443 uint8_t *unescaped;
444 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
445 int unescaped_size, seq_found = 0;
446 int level = 0, interlace = 0;
447 int packet_seq = track->vc1_info.packet_seq;
448 int packet_entry = track->vc1_info.packet_entry;
449 int slices = track->vc1_info.slices;
450 PutBitContext pbc;
451
452 if (track->start_dts == AV_NOPTS_VALUE) {
453 /* No packets written yet, vc1_info isn't authoritative yet. */
454 /* Assume inline sequence and entry headers. */
455 packet_seq = packet_entry = 1;
456 av_log(NULL, AV_LOG_WARNING,
457 "moov atom written before any packets, unable to write correct "
458 "dvc1 atom. Set the delay_moov flag to fix this.\n");
459 }
460
461 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
462 if (!unescaped)
463 return AVERROR(ENOMEM);
464 start = find_next_marker(track->vos_data, end);
465 for (next = start; next < end; start = next) {
466 BitstreamContext bc;
467 int size;
468 next = find_next_marker(start + 4, end);
469 size = next - start - 4;
470 if (size <= 0)
471 continue;
472 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
473 bitstream_init8(&bc, unescaped, unescaped_size);
474 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
475 int profile = bitstream_read(&bc, 2);
476 if (profile != PROFILE_ADVANCED) {
477 av_free(unescaped);
478 return AVERROR(ENOSYS);
479 }
480 seq_found = 1;
481 level = bitstream_read(&bc, 3);
482 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
483 * width, height */
484 bitstream_skip(&bc, 2 + 3 + 5 + 1 + 2 * 12);
485 bitstream_skip(&bc, 1); /* broadcast */
486 interlace = bitstream_read_bit(&bc);
487 bitstream_skip(&bc, 4); /* tfcntrflag, finterpflag, reserved, psf */
488 }
489 }
490 if (!seq_found) {
491 av_free(unescaped);
492 return AVERROR(ENOSYS);
493 }
494
495 init_put_bits(&pbc, buf, 7);
496 /* VC1DecSpecStruc */
497 put_bits(&pbc, 4, 12); /* profile - advanced */
498 put_bits(&pbc, 3, level);
499 put_bits(&pbc, 1, 0); /* reserved */
500 /* VC1AdvDecSpecStruc */
501 put_bits(&pbc, 3, level);
502 put_bits(&pbc, 1, 0); /* cbr */
503 put_bits(&pbc, 6, 0); /* reserved */
504 put_bits(&pbc, 1, !interlace); /* no interlace */
505 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
506 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
507 put_bits(&pbc, 1, !slices); /* no slice code */
508 put_bits(&pbc, 1, 0); /* no bframe */
509 put_bits(&pbc, 1, 0); /* reserved */
510
511 /* framerate */
512 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
513 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
514 else
515 put_bits32(&pbc, 0xffffffff);
516
517 flush_put_bits(&pbc);
518
519 av_free(unescaped);
520
521 return 0;
522 }
523
524 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
525 {
526 uint8_t buf[7] = { 0 };
527 int ret;
528
529 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
530 return ret;
531
532 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
533 ffio_wfourcc(pb, "dvc1");
534 avio_write(pb, buf, sizeof(buf));
535 avio_write(pb, track->vos_data, track->vos_len);
536
537 return 0;
538 }
539
540 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
541 {
542 avio_wb32(pb, track->vos_len + 8);
543 ffio_wfourcc(pb, "glbl");
544 avio_write(pb, track->vos_data, track->vos_len);
545 return 8 + track->vos_len;
546 }
547
548 /**
549 * Compute flags for 'lpcm' tag.
550 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
551 */
552 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
553 {
554 switch (codec_id) {
555 case AV_CODEC_ID_PCM_F32BE:
556 case AV_CODEC_ID_PCM_F64BE:
557 return 11;
558 case AV_CODEC_ID_PCM_F32LE:
559 case AV_CODEC_ID_PCM_F64LE:
560 return 9;
561 case AV_CODEC_ID_PCM_U8:
562 return 10;
563 case AV_CODEC_ID_PCM_S16BE:
564 case AV_CODEC_ID_PCM_S24BE:
565 case AV_CODEC_ID_PCM_S32BE:
566 return 14;
567 case AV_CODEC_ID_PCM_S8:
568 case AV_CODEC_ID_PCM_S16LE:
569 case AV_CODEC_ID_PCM_S24LE:
570 case AV_CODEC_ID_PCM_S32LE:
571 return 12;
572 default:
573 return 0;
574 }
575 }
576
577 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
578 {
579 int64_t next_dts;
580
581 if (cluster_idx >= track->entry)
582 return 0;
583
584 if (cluster_idx + 1 == track->entry)
585 next_dts = track->track_duration + track->start_dts;
586 else
587 next_dts = track->cluster[cluster_idx + 1].dts;
588
589 return next_dts - track->cluster[cluster_idx].dts;
590 }
591
592 static int get_samples_per_packet(MOVTrack *track)
593 {
594 int i, first_duration;
595
596 /* use 1 for raw PCM */
597 if (!track->audio_vbr)
598 return 1;
599
600 /* check to see if duration is constant for all clusters */
601 if (!track->entry)
602 return 0;
603 first_duration = get_cluster_duration(track, 0);
604 for (i = 1; i < track->entry; i++) {
605 if (get_cluster_duration(track, i) != first_duration)
606 return 0;
607 }
608 return first_duration;
609 }
610
611 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
612 {
613 int64_t pos = avio_tell(pb);
614 int version = 0;
615 uint32_t tag = track->tag;
616
617 if (track->mode == MODE_MOV) {
618 if (mov_get_lpcm_flags(track->par->codec_id))
619 tag = AV_RL32("lpcm");
620 version = 2;
621 }
622
623 avio_wb32(pb, 0); /* size */
624 avio_wl32(pb, tag); // store it byteswapped
625 avio_wb32(pb, 0); /* Reserved */
626 avio_wb16(pb, 0); /* Reserved */
627 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
628
629 /* SoundDescription */
630 avio_wb16(pb, version); /* Version */
631 avio_wb16(pb, 0); /* Revision level */
632 avio_wb32(pb, 0); /* Reserved */
633
634 if (version == 2) {
635 avio_wb16(pb, 3);
636 avio_wb16(pb, 16);
637 avio_wb16(pb, 0xfffe);
638 avio_wb16(pb, 0);
639 avio_wb32(pb, 0x00010000);
640 avio_wb32(pb, 72);
641 avio_wb64(pb, av_double2int(track->par->sample_rate));
642 avio_wb32(pb, track->par->channels);
643 avio_wb32(pb, 0x7F000000);
644 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
645 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
646 avio_wb32(pb, track->sample_size);
647 avio_wb32(pb, get_samples_per_packet(track));
648 } else {
649 /* reserved for mp4/3gp */
650 avio_wb16(pb, 2);
651 avio_wb16(pb, 16);
652 avio_wb16(pb, 0);
653
654 avio_wb16(pb, 0); /* packet size (= 0) */
655 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
656 track->par->sample_rate : 0);
657 avio_wb16(pb, 0); /* Reserved */
658 }
659
660 if (track->mode == MODE_MOV &&
661 (track->par->codec_id == AV_CODEC_ID_AAC ||
662 track->par->codec_id == AV_CODEC_ID_AC3 ||
663 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
664 track->par->codec_id == AV_CODEC_ID_ALAC ||
665 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
666 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV))
667 mov_write_wave_tag(s, pb, track);
668 else if (track->tag == MKTAG('m','p','4','a'))
669 mov_write_esds_tag(pb, track);
670 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
671 mov_write_amr_tag(pb, track);
672 else if (track->par->codec_id == AV_CODEC_ID_AC3)
673 mov_write_ac3_tag(pb, track);
674 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
675 mov_write_extradata_tag(pb, track);
676 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
677 mov_write_wfex_tag(s, pb, track);
678 else if (track->vos_len > 0)
679 mov_write_glbl_tag(pb, track);
680
681 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
682 mov_write_chan_tag(s, pb, track);
683
684 return update_size(pb, pos);
685 }
686
687 static int mov_write_d263_tag(AVIOContext *pb)
688 {
689 avio_wb32(pb, 0xf); /* size */
690 ffio_wfourcc(pb, "d263");
691 ffio_wfourcc(pb, "FFMP");
692 avio_w8(pb, 0); /* decoder version */
693 /* FIXME use AVCodecContext level/profile, when encoder will set values */
694 avio_w8(pb, 0xa); /* level */
695 avio_w8(pb, 0); /* profile */
696 return 0xf;
697 }
698
699 /* TODO: No idea about these values */
700 static int mov_write_svq3_tag(AVIOContext *pb)
701 {
702 avio_wb32(pb, 0x15);
703 ffio_wfourcc(pb, "SMI ");
704 ffio_wfourcc(pb, "SEQH");
705 avio_wb32(pb, 0x5);
706 avio_wb32(pb, 0xe2c0211d);
707 avio_wb32(pb, 0xc0000000);
708 avio_w8(pb, 0);
709 return 0x15;
710 }
711
712 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
713 {
714 int64_t pos = avio_tell(pb);
715
716 avio_wb32(pb, 0);
717 ffio_wfourcc(pb, "avcC");
718 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
719 return update_size(pb, pos);
720 }
721
722 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
723 {
724 int64_t pos = avio_tell(pb);
725
726 avio_wb32(pb, 0);
727 ffio_wfourcc(pb, "hvcC");
728 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
729 return update_size(pb, pos);
730 }
731
732 /* also used by all avid codecs (dv, imx, meridien) and their variants */
733 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
734 {
735 int i;
736 avio_wb32(pb, 24); /* size */
737 ffio_wfourcc(pb, "ACLR");
738 ffio_wfourcc(pb, "ACLR");
739 ffio_wfourcc(pb, "0001");
740 avio_wb32(pb, 2); /* yuv range: full 1 / normal 2 */
741 avio_wb32(pb, 0); /* unknown */
742
743 avio_wb32(pb, 24); /* size */
744 ffio_wfourcc(pb, "APRG");
745 ffio_wfourcc(pb, "APRG");
746 ffio_wfourcc(pb, "0001");
747 avio_wb32(pb, 1); /* unknown */
748 avio_wb32(pb, 0); /* unknown */
749
750 avio_wb32(pb, 120); /* size */
751 ffio_wfourcc(pb, "ARES");
752 ffio_wfourcc(pb, "ARES");
753 ffio_wfourcc(pb, "0001");
754 avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
755 avio_wb32(pb, track->par->width);
756 /* values below are based on samples created with quicktime and avid codecs */
757 if (track->vos_data[5] & 2) { // interlaced
758 avio_wb32(pb, track->par->height / 2);
759 avio_wb32(pb, 2); /* unknown */
760 avio_wb32(pb, 0); /* unknown */
761 avio_wb32(pb, 4); /* unknown */
762 } else {
763 avio_wb32(pb, track->par->height);
764 avio_wb32(pb, 1); /* unknown */
765 avio_wb32(pb, 0); /* unknown */
766 if (track->par->height == 1080)
767 avio_wb32(pb, 5); /* unknown */
768 else
769 avio_wb32(pb, 6); /* unknown */
770 }
771 /* padding */
772 for (i = 0; i < 10; i++)
773 avio_wb64(pb, 0);
774
775 /* extra padding for stsd needed */
776 avio_wb32(pb, 0);
777 return 0;
778 }
779
780 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
781 {
782 int tag = track->par->codec_tag;
783
784 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
785 return 0;
786
787 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
788 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
789 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
790 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
791 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
792 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
793 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
794 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
795 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
796
797 return tag;
798 }
799
800 static const AVCodecTag codec_ipod_tags[] = {
801 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
802 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
803 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
804 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
805 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
806 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
807 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
808 { AV_CODEC_ID_NONE, 0 },
809 };
810
811 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
812 {
813 int tag = track->par->codec_tag;
814
815 // keep original tag for subs, ipod supports both formats
816 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
817 (tag == MKTAG('t', 'x', '3', 'g') ||
818 tag == MKTAG('t', 'e', 'x', 't'))))
819 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
820
821 if (!av_match_ext(s->filename, "m4a") && !av_match_ext(s->filename, "m4v"))
822 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
823 "Quicktime/Ipod might not play the file\n");
824
825 return tag;
826 }
827
828 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
829 {
830 int tag;
831
832 if (track->par->width == 720) /* SD */
833 if (track->par->height == 480) /* NTSC */
834 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
835 else tag = MKTAG('d','v','c',' ');
836 else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
837 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
838 else tag = MKTAG('d','v','p','p');
839 else if (track->par->height == 720) /* HD 720 line */
840 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
841 else tag = MKTAG('d','v','h','p');
842 else if (track->par->height == 1080) /* HD 1080 line */
843 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
844 else tag = MKTAG('d','v','h','6');
845 else {
846 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
847 return 0;
848 }
849
850 return tag;
851 }
852
853 static const struct {
854 enum AVPixelFormat pix_fmt;
855 uint32_t tag;
856 unsigned bps;
857 } mov_pix_fmt_tags[] = {
858 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
859 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
860 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
861 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
862 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
863 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
864 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
865 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
866 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
867 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
868 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
869 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
870 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
871 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
872 };
873
874 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
875 {
876 int tag = track->par->codec_tag;
877 int i;
878
879 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
880 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
881 tag = mov_pix_fmt_tags[i].tag;
882 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
883 break;
884 }
885 }
886
887 return tag;
888 }
889
890 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
891 {
892 int tag = track->par->codec_tag;
893
894 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
895 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
896 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
897 track->par->codec_id == AV_CODEC_ID_H263 ||
898 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
899 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
900 tag = mov_get_dv_codec_tag(s, track);
901 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
902 tag = mov_get_rawvideo_codec_tag(s, track);
903 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
904 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
905 if (!tag) { // if no mac fcc found, try with Microsoft tags
906 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
907 if (tag)
908 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
909 "the file may be unplayable!\n");
910 }
911 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
912 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
913 if (!tag) { // if no mac fcc found, try with Microsoft tags
914 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
915 if (ms_tag) {
916 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
917 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
918 "the file may be unplayable!\n");
919 }
920 }
921 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
922 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
923 }
924
925 return tag;
926 }
927
928 static const AVCodecTag codec_3gp_tags[] = {
929 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
930 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
931 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
932 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
933 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
934 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
935 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
936 { AV_CODEC_ID_NONE, 0 },
937 };
938
939 static const AVCodecTag codec_f4v_tags[] = {
940 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
941 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
942 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
943 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
944 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
945 { AV_CODEC_ID_NONE, 0 },
946 };
947
948 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
949 {
950 int tag;
951
952 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
953 tag = mp4_get_codec_tag(s, track);
954 else if (track->mode == MODE_ISM) {
955 tag = mp4_get_codec_tag(s, track);
956 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
957 tag = MKTAG('w', 'm', 'a', ' ');
958 } else if (track->mode == MODE_IPOD)
959 tag = ipod_get_codec_tag(s, track);
960 else if (track->mode & MODE_3GP)
961 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
962 else if (track->mode == MODE_F4V)
963 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
964 else
965 tag = mov_get_codec_tag(s, track);
966
967 return tag;
968 }
969
970 /** Write uuid atom.
971 * Needed to make file play in iPods running newest firmware
972 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
973 */
974 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
975 {
976 avio_wb32(pb, 28);
977 ffio_wfourcc(pb, "uuid");
978 avio_wb32(pb, 0x6b6840f2);
979 avio_wb32(pb, 0x5f244fc5);
980 avio_wb32(pb, 0xba39a51b);
981 avio_wb32(pb, 0xcf0323f3);
982 avio_wb32(pb, 0x0);
983 return 28;
984 }
985
986 static const uint16_t fiel_data[] = {
987 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
988 };
989
990 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
991 {
992 unsigned mov_field_order = 0;
993 if (track->par->field_order < FF_ARRAY_ELEMS(fiel_data))
994 mov_field_order = fiel_data[track->par->field_order];
995 else
996 return 0;
997 avio_wb32(pb, 10);
998 ffio_wfourcc(pb, "fiel");
999 avio_wb16(pb, mov_field_order);
1000 return 10;
1001 }
1002
1003 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1004 {
1005 int64_t pos = avio_tell(pb);
1006 avio_wb32(pb, 0); /* size */
1007 avio_wl32(pb, track->tag); // store it byteswapped
1008 avio_wb32(pb, 0); /* Reserved */
1009 avio_wb16(pb, 0); /* Reserved */
1010 avio_wb16(pb, 1); /* Data-reference index */
1011
1012 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1013 mov_write_esds_tag(pb, track);
1014 else if (track->par->extradata_size)
1015 avio_write(pb, track->par->extradata, track->par->extradata_size);
1016
1017 return update_size(pb, pos);
1018 }
1019
1020 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1021 {
1022 AVRational sar;
1023 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1024 track->par->sample_aspect_ratio.den, INT_MAX);
1025
1026 avio_wb32(pb, 16);
1027 ffio_wfourcc(pb, "pasp");
1028 avio_wb32(pb, sar.num);
1029 avio_wb32(pb, sar.den);
1030 return 16;
1031 }
1032
1033 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1034 {
1035 AVDictionaryEntry *encoder;
1036 int64_t pos = avio_tell(pb);
1037 char compressor_name[32] = { 0 };
1038
1039 avio_wb32(pb, 0); /* size */
1040 avio_wl32(pb, track->tag); // store it byteswapped
1041 avio_wb32(pb, 0); /* Reserved */
1042 avio_wb16(pb, 0); /* Reserved */
1043 avio_wb16(pb, 1); /* Data-reference index */
1044
1045 avio_wb16(pb, 0); /* Codec stream version */
1046 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1047 if (track->mode == MODE_MOV) {
1048 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1049 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1050 avio_wb32(pb, 0); /* Temporal Quality */
1051 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1052 } else {
1053 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1054 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1055 }
1056 } else {
1057 avio_wb32(pb, 0); /* Reserved */
1058 avio_wb32(pb, 0); /* Reserved */
1059 avio_wb32(pb, 0); /* Reserved */
1060 }
1061 avio_wb16(pb, track->par->width); /* Video width */
1062 avio_wb16(pb, track->height); /* Video height */
1063 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1064 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1065 avio_wb32(pb, 0); /* Data size (= 0) */
1066 avio_wb16(pb, 1); /* Frame count (= 1) */
1067
1068 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1069 if (track->mode == MODE_MOV &&
1070 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0)))
1071 av_strlcpy(compressor_name, encoder->value, 32);
1072 avio_w8(pb, strlen(compressor_name));
1073 avio_write(pb, compressor_name, 31);
1074
1075 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1076 avio_wb16(pb, track->par->bits_per_coded_sample);
1077 else
1078 avio_wb16(pb, 0x18); /* Reserved */
1079 avio_wb16(pb, 0xffff); /* Reserved */
1080 if (track->tag == MKTAG('m','p','4','v'))
1081 mov_write_esds_tag(pb, track);
1082 else if (track->par->codec_id == AV_CODEC_ID_H263)
1083 mov_write_d263_tag(pb);
1084 else if (track->par->codec_id == AV_CODEC_ID_SVQ3)
1085 mov_write_svq3_tag(pb);
1086 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1087 mov_write_avid_tag(pb, track);
1088 else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1089 mov_write_hvcc_tag(pb, track);
1090 else if (track->par->codec_id == AV_CODEC_ID_H264) {
1091 mov_write_avcc_tag(pb, track);
1092 if (track->mode == MODE_IPOD)
1093 mov_write_uuid_tag_ipod(pb);
1094 } else if (track->par->field_order != AV_FIELD_UNKNOWN)
1095 mov_write_fiel_tag(pb, track);
1096 else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1097 mov_write_dvc1_tag(pb, track);
1098 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1099 track->par->codec_id == AV_CODEC_ID_VP6A) {
1100 /* Don't write any potential extradata here - the cropping
1101 * is signalled via the normal width/height fields. */
1102 } else if (track->vos_len > 0)
1103 mov_write_glbl_tag(pb, track);
1104
1105 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num &&
1106 track->par->sample_aspect_ratio.den != track->par->sample_aspect_ratio.num) {
1107 mov_write_pasp_tag(pb, track);
1108 }
1109
1110 return update_size(pb, pos);
1111 }
1112
1113 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1114 {
1115 int64_t pos = avio_tell(pb);
1116 avio_wb32(pb, 0); /* size */
1117 ffio_wfourcc(pb, "rtp ");
1118 avio_wb32(pb, 0); /* Reserved */
1119 avio_wb16(pb, 0); /* Reserved */
1120 avio_wb16(pb, 1); /* Data-reference index */
1121
1122 avio_wb16(pb, 1); /* Hint track version */
1123 avio_wb16(pb, 1); /* Highest compatible version */
1124 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1125
1126 avio_wb32(pb, 12); /* size */
1127 ffio_wfourcc(pb, "tims");
1128 avio_wb32(pb, track->timescale);
1129
1130 return update_size(pb, pos);
1131 }
1132
1133 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1134 {
1135 int64_t pos = avio_tell(pb);
1136
1137 avio_wb32(pb, 0); /* size */
1138 ffio_wfourcc(pb, "tmcd"); /* Data format */
1139 avio_wb32(pb, 0); /* Reserved */
1140 avio_wb32(pb, 1); /* Data reference index */
1141 if (track->par->extradata_size)
1142 avio_write(pb, track->par->extradata, track->par->extradata_size);
1143 return update_size(pb, pos);
1144 }
1145
1146 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1147 {
1148 int64_t pos = avio_tell(pb);
1149 avio_wb32(pb, 0); /* size */
1150 ffio_wfourcc(pb, "stsd");
1151 avio_wb32(pb, 0); /* version & flags */
1152 avio_wb32(pb, 1); /* entry count */
1153 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
1154 mov_write_video_tag(pb, track);
1155 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1156 mov_write_audio_tag(s, pb, track);
1157 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1158 mov_write_subtitle_tag(pb, track);
1159 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
1160 mov_write_rtp_tag(pb, track);
1161 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
1162 mov_write_tmcd_tag(pb, track);
1163 return update_size(pb, pos);
1164 }
1165
1166 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1167 {
1168 MOVStts *ctts_entries;
1169 uint32_t entries = 0;
1170 uint32_t atom_size;
1171 int i;
1172
1173 ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
1174 if (!ctts_entries)
1175 return AVERROR(ENOMEM);
1176 ctts_entries[0].count = 1;
1177 ctts_entries[0].duration = track->cluster[0].cts;
1178 for (i = 1; i < track->entry; i++) {
1179 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1180 ctts_entries[entries].count++; /* compress */
1181 } else {
1182 entries++;
1183 ctts_entries[entries].duration = track->cluster[i].cts;
1184 ctts_entries[entries].count = 1;
1185 }
1186 }
1187 entries++; /* last one */
1188 atom_size = 16 + (entries * 8);
1189 avio_wb32(pb, atom_size); /* size */
1190 ffio_wfourcc(pb, "ctts");
1191 avio_wb32(pb, 0); /* version & flags */
1192 avio_wb32(pb, entries); /* entry count */
1193 for (i = 0; i < entries; i++) {
1194 avio_wb32(pb, ctts_entries[i].count);
1195 avio_wb32(pb, ctts_entries[i].duration);
1196 }
1197 av_free(ctts_entries);
1198 return atom_size;
1199 }
1200
1201 /* Time to sample atom */
1202 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1203 {
1204 MOVStts *stts_entries = NULL;
1205 uint32_t entries = -1;
1206 uint32_t atom_size;
1207 int i;
1208
1209 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1210 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1211 if (!stts_entries)
1212 return AVERROR(ENOMEM);
1213 stts_entries[0].count = track->sample_count;
1214 stts_entries[0].duration = 1;
1215 entries = 1;
1216 } else {
1217 if (track->entry) {
1218 stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
1219 if (!stts_entries)
1220 return AVERROR(ENOMEM);
1221 }
1222 for (i = 0; i < track->entry; i++) {
1223 int duration = get_cluster_duration(track, i);
1224 if (i && duration == stts_entries[entries].duration) {
1225 stts_entries[entries].count++; /* compress */
1226 } else {
1227 entries++;
1228 stts_entries[entries].duration = duration;
1229 stts_entries[entries].count = 1;
1230 }
1231 }
1232 entries++; /* last one */
1233 }
1234 atom_size = 16 + (entries * 8);
1235 avio_wb32(pb, atom_size); /* size */
1236 ffio_wfourcc(pb, "stts");
1237 avio_wb32(pb, 0); /* version & flags */
1238 avio_wb32(pb, entries); /* entry count */
1239 for (i = 0; i < entries; i++) {
1240 avio_wb32(pb, stts_entries[i].count);
1241 avio_wb32(pb, stts_entries[i].duration);
1242 }
1243 av_free(stts_entries);
1244 return atom_size;
1245 }
1246
1247 static int mov_write_dref_tag(AVIOContext *pb)
1248 {
1249 avio_wb32(pb, 28); /* size */
1250 ffio_wfourcc(pb, "dref");
1251 avio_wb32(pb, 0); /* version & flags */
1252 avio_wb32(pb, 1); /* entry count */
1253
1254 avio_wb32(pb, 0xc); /* size */
1255 ffio_wfourcc(pb, "url ");
1256 avio_wb32(pb, 1); /* version & flags */
1257
1258 return 28;
1259 }
1260
1261 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1262 {
1263 int64_t pos = avio_tell(pb);
1264 avio_wb32(pb, 0); /* size */
1265 ffio_wfourcc(pb, "stbl");
1266 mov_write_stsd_tag(s, pb, track);
1267 mov_write_stts_tag(pb, track);
1268 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
1269 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
1270 track->has_keyframes && track->has_keyframes < track->entry)
1271 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1272 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1273 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1274 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
1275 track->flags & MOV_TRACK_CTTS && track->entry)
1276 mov_write_ctts_tag(pb, track);
1277 mov_write_stsc_tag(pb, track);
1278 mov_write_stsz_tag(pb, track);
1279 mov_write_stco_tag(pb, track);
1280 return update_size(pb, pos);
1281 }
1282
1283 static int mov_write_dinf_tag(AVIOContext *pb)
1284 {
1285 int64_t pos = avio_tell(pb);
1286 avio_wb32(pb, 0); /* size */
1287 ffio_wfourcc(pb, "dinf");
1288 mov_write_dref_tag(pb);
1289 return update_size(pb, pos);
1290 }
1291
1292 static int mov_write_nmhd_tag(AVIOContext *pb)
1293 {
1294 avio_wb32(pb, 12);
1295 ffio_wfourcc(pb, "nmhd");
1296 avio_wb32(pb, 0);
1297 return 12;
1298 }
1299
1300 static int mov_write_gmhd_tag(AVIOContext *pb)
1301 {
1302 avio_wb32(pb, 0x20); /* size */
1303 ffio_wfourcc(pb, "gmhd");
1304 avio_wb32(pb, 0x18); /* gmin size */
1305 ffio_wfourcc(pb, "gmin");/* generic media info */
1306 avio_wb32(pb, 0); /* version & flags */
1307 avio_wb16(pb, 0x40); /* graphics mode = */
1308 avio_wb16(pb, 0x8000); /* opColor (r?) */
1309 avio_wb16(pb, 0x8000); /* opColor (g?) */
1310 avio_wb16(pb, 0x8000); /* opColor (b?) */
1311 avio_wb16(pb, 0); /* balance */
1312 avio_wb16(pb, 0); /* reserved */
1313 return 0x20;
1314 }
1315
1316 static int mov_write_smhd_tag(AVIOContext *pb)
1317 {
1318 avio_wb32(pb, 16); /* size */
1319 ffio_wfourcc(pb, "smhd");
1320 avio_wb32(pb, 0); /* version & flags */
1321 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1322 avio_wb16(pb, 0); /* reserved */
1323 return 16;
1324 }
1325
1326 static int mov_write_vmhd_tag(AVIOContext *pb)
1327 {
1328 avio_wb32(pb, 0x14); /* size (always 0x14) */
1329 ffio_wfourcc(pb, "vmhd");
1330 avio_wb32(pb, 0x01); /* version & flags */
1331 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1332 return 0x14;
1333 }
1334
1335 static int is_clcp_track(MOVTrack *track)
1336 {
1337 return track->tag == MKTAG('c','7','0','8') ||
1338 track->tag == MKTAG('c','6','0','8');
1339 }
1340
1341 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1342 {
1343 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1344 int64_t pos = avio_tell(pb);
1345
1346 hdlr = "dhlr";
1347 hdlr_type = "url ";
1348 descr = "DataHandler";
1349
1350 if (track) {
1351 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1352 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1353 hdlr_type = "vide";
1354 descr = "VideoHandler";
1355 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1356 hdlr_type = "soun";
1357 descr = "SoundHandler";
1358 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1359 if (track->tag == MKTAG('t','x','3','g')) {
1360 hdlr_type = "sbtl";
1361 } else if (track->tag == MKTAG('m','p','4','s')) {
1362 hdlr_type = "subp";
1363 } else if (is_clcp_track(track)) {
1364 hdlr_type = "clcp";
1365 } else {
1366 hdlr_type = "text";
1367 }
1368 descr = "SubtitleHandler";
1369 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
1370 hdlr_type = "hint";
1371 descr = "HintHandler";
1372 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
1373 hdlr_type = "tmcd";
1374 descr = "TimeCodeHandler";
1375 } else {
1376 char tag_buf[32];
1377 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
1378 track->par->codec_tag);
1379
1380 av_log(s, AV_LOG_WARNING,
1381 "Unknown hldr_type for %s / 0x%04"PRIX32", writing dummy values\n",
1382 tag_buf, track->par->codec_tag);
1383 }
1384 if (track->st) {
1385 // hdlr.name is used by some players to identify the content title
1386 // of the track. So if an alternate handler description is
1387 // specified, use it.
1388 AVDictionaryEntry *t;
1389 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
1390 if (t && utf8len(t->value))
1391 descr = t->value;
1392 }
1393 }
1394
1395 avio_wb32(pb, 0); /* size */
1396 ffio_wfourcc(pb, "hdlr");
1397 avio_wb32(pb, 0); /* Version & flags */
1398 avio_write(pb, hdlr, 4); /* handler */
1399 ffio_wfourcc(pb, hdlr_type); /* handler type */
1400 avio_wb32(pb, 0); /* reserved */
1401 avio_wb32(pb, 0); /* reserved */
1402 avio_wb32(pb, 0); /* reserved */
1403 if (!track || track->mode == MODE_MOV)
1404 avio_w8(pb, strlen(descr)); /* pascal string */
1405 avio_write(pb, descr, strlen(descr)); /* handler description */
1406 if (track && track->mode != MODE_MOV)
1407 avio_w8(pb, 0); /* c string */
1408 return update_size(pb, pos);
1409 }
1410
1411 static int mov_write_hmhd_tag(AVIOContext *pb)
1412 {
1413 /* This atom must be present, but leaving the values at zero
1414 * seems harmless. */
1415 avio_wb32(pb, 28); /* size */
1416 ffio_wfourcc(pb, "hmhd");
1417 avio_wb32(pb, 0); /* version, flags */
1418 avio_wb16(pb, 0); /* maxPDUsize */
1419 avio_wb16(pb, 0); /* avgPDUsize */
1420 avio_wb32(pb, 0); /* maxbitrate */
1421 avio_wb32(pb, 0); /* avgbitrate */
1422 avio_wb32(pb, 0); /* reserved */
1423 return 28;
1424 }
1425
1426 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1427 {
1428 int64_t pos = avio_tell(pb);
1429 avio_wb32(pb, 0); /* size */
1430 ffio_wfourcc(pb, "minf");
1431 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
1432 mov_write_vmhd_tag(pb);
1433 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1434 mov_write_smhd_tag(pb);
1435 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1436 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
1437 mov_write_gmhd_tag(pb);
1438 } else {
1439 mov_write_nmhd_tag(pb);
1440 }
1441 } else if (track->tag == MKTAG('r','t','p',' ')) {
1442 mov_write_hmhd_tag(pb);
1443 } else if (track->tag == MKTAG('t','m','c','d')) {
1444 mov_write_gmhd_tag(pb);
1445 }
1446 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1447 mov_write_hdlr_tag(s, pb, NULL);
1448 mov_write_dinf_tag(pb);
1449 mov_write_stbl_tag(s, pb, track);
1450 return update_size(pb, pos);
1451 }
1452
1453 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
1454 MOVTrack *track)
1455 {
1456 int version = track->track_duration < INT32_MAX ? 0 : 1;
1457
1458 if (track->mode == MODE_ISM)
1459 version = 1;
1460
1461 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1462 ffio_wfourcc(pb, "mdhd");
1463 avio_w8(pb, version);
1464 avio_wb24(pb, 0); /* flags */
1465 if (version == 1) {
1466 avio_wb64(pb, track->time);
1467 avio_wb64(pb, track->time);
1468 } else {
1469 avio_wb32(pb, track->time); /* creation time */
1470 avio_wb32(pb, track->time); /* modification time */
1471 }
1472 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1473 if (!track->entry && mov->mode == MODE_ISM)
1474 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1475 else if (!track->entry)
1476 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
1477 else
1478 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
1479 avio_wb16(pb, track->language); /* language */
1480 avio_wb16(pb, 0); /* reserved (quality) */
1481
1482 if (version != 0 && track->mode == MODE_MOV) {
1483 av_log(NULL, AV_LOG_ERROR,
1484 "FATAL error, file duration too long for timebase, this file will not be\n"
1485 "playable with quicktime. Choose a different timebase or a different\n"
1486 "container format\n");
1487 }
1488
1489 return 32;
1490 }
1491
1492 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
1493 MOVMuxContext *mov, MOVTrack *track)
1494 {
1495 int64_t pos = avio_tell(pb);
1496 avio_wb32(pb, 0); /* size */
1497 ffio_wfourcc(pb, "mdia");
1498 mov_write_mdhd_tag(pb, mov, track);
1499 mov_write_hdlr_tag(s, pb, track);
1500 mov_write_minf_tag(s, pb, track);
1501 return update_size(pb, pos);
1502 }
1503
1504 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
1505 MOVTrack *track, AVStream *st)
1506 {
1507 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1508 track->timescale, AV_ROUND_UP);
1509 int version = duration < INT32_MAX ? 0 : 1;
1510 int flags = MOV_TKHD_FLAG_IN_MOVIE;
1511 int group = 0;
1512
1513 uint32_t *display_matrix = NULL;
1514 int display_matrix_size, i;
1515
1516 if (st) {
1517 if (mov->per_stream_grouping)
1518 group = st->index;
1519 else
1520 group = st->codecpar->codec_type;
1521
1522 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
1523 &display_matrix_size);
1524 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
1525 display_matrix = NULL;
1526 }
1527
1528 if (track->flags & MOV_TRACK_ENABLED)
1529 flags |= MOV_TKHD_FLAG_ENABLED;
1530
1531 if (track->mode == MODE_ISM)
1532 version = 1;
1533
1534 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1535 ffio_wfourcc(pb, "tkhd");
1536 avio_w8(pb, version);
1537 avio_wb24(pb, flags);
1538 if (version == 1) {
1539 avio_wb64(pb, track->time);
1540 avio_wb64(pb, track->time);
1541 } else {
1542 avio_wb32(pb, track->time); /* creation time */
1543 avio_wb32(pb, track->time); /* modification time */
1544 }
1545 avio_wb32(pb, track->track_id); /* track-id */
1546 avio_wb32(pb, 0); /* reserved */
1547 if (!track->entry && mov->mode == MODE_ISM)
1548 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1549 else if (!track->entry)
1550 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
1551 else
1552 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1553
1554 avio_wb32(pb, 0); /* reserved */
1555 avio_wb32(pb, 0); /* reserved */
1556 avio_wb16(pb, 0); /* layer */
1557 avio_wb16(pb, group); /* alternate group) */
1558 /* Volume, only for audio */
1559 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1560 avio_wb16(pb, 0x0100);
1561 else
1562 avio_wb16(pb, 0);
1563 avio_wb16(pb, 0); /* reserved */
1564
1565 /* Matrix structure */
1566 if (display_matrix) {
1567 for (i = 0; i < 9; i++)
1568 avio_wb32(pb, display_matrix[i]);
1569 } else {
1570 avio_wb32(pb, 0x00010000); /* reserved */
1571 avio_wb32(pb, 0x0); /* reserved */
1572 avio_wb32(pb, 0x0); /* reserved */
1573 avio_wb32(pb, 0x0); /* reserved */
1574 avio_wb32(pb, 0x00010000); /* reserved */
1575 avio_wb32(pb, 0x0); /* reserved */
1576 avio_wb32(pb, 0x0); /* reserved */
1577 avio_wb32(pb, 0x0); /* reserved */
1578 avio_wb32(pb, 0x40000000); /* reserved */
1579 }
1580
1581 /* Track width and height, for visual only */
1582 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
1583 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1584 if (track->mode == MODE_MOV) {
1585 avio_wb32(pb, track->par->width << 16);
1586 avio_wb32(pb, track->height << 16);
1587 } else {
1588 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1589 if (!sample_aspect_ratio || track->height != track->par->height)
1590 sample_aspect_ratio = 1;
1591 avio_wb32(pb, sample_aspect_ratio * track->par->width * 0x10000);
1592 avio_wb32(pb, track->height * 0x10000);
1593 }
1594 } else {
1595 avio_wb32(pb, 0);
1596 avio_wb32(pb, 0);
1597 }
1598 return 0x5c;
1599 }
1600
1601 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1602 {
1603 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
1604 track->par->sample_aspect_ratio.den);
1605
1606 int64_t pos = avio_tell(pb);
1607
1608 avio_wb32(pb, 0); /* size */
1609 ffio_wfourcc(pb, "tapt");
1610
1611 avio_wb32(pb, 20);
1612 ffio_wfourcc(pb, "clef");
1613 avio_wb32(pb, 0);
1614 avio_wb32(pb, width << 16);
1615 avio_wb32(pb, track->par->height << 16);
1616
1617 avio_wb32(pb, 20);
1618 ffio_wfourcc(pb, "prof");
1619 avio_wb32(pb, 0);
1620 avio_wb32(pb, width << 16);
1621 avio_wb32(pb, track->par->height << 16);
1622
1623 avio_wb32(pb, 20);
1624 ffio_wfourcc(pb, "enof");
1625 avio_wb32(pb, 0);
1626 avio_wb32(pb, track->par->width << 16);
1627 avio_wb32(pb, track->par->height << 16);
1628
1629 return update_size(pb, pos);
1630 }
1631
1632 // This box seems important for the psp playback ... without it the movie seems to hang
1633 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
1634 MOVTrack *track)
1635 {
1636 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1637 track->timescale, AV_ROUND_UP);
1638 int version = duration < INT32_MAX ? 0 : 1;
1639 int entry_size, entry_count, size;
1640 int64_t delay, start_ct = track->start_cts;
1641 delay = av_rescale_rnd(track->start_dts + start_ct, MOV_TIMESCALE,
1642 track->timescale, AV_ROUND_DOWN);
1643 version |= delay < INT32_MAX ? 0 : 1;
1644
1645 entry_size = (version == 1) ? 20 : 12;
1646 entry_count = 1 + (delay > 0);
1647 size = 24 + entry_count * entry_size;
1648
1649 /* write the atom data */
1650 avio_wb32(pb, size);
1651 ffio_wfourcc(pb, "edts");
1652 avio_wb32(pb, size - 8);
1653 ffio_wfourcc(pb, "elst");
1654 avio_w8(pb, version);
1655 avio_wb24(pb, 0); /* flags */
1656
1657 avio_wb32(pb, entry_count);
1658 if (delay > 0) { /* add an empty edit to delay presentation */
1659 /* In the positive delay case, the delay includes the cts
1660 * offset, and the second edit list entry below trims out
1661 * the same amount from the actual content. This makes sure
1662 * that the offset last sample is included in the edit
1663 * list duration as well. */
1664 if (version == 1) {
1665 avio_wb64(pb, delay);
1666 avio_wb64(pb, -1);
1667 } else {
1668 avio_wb32(pb, delay);
1669 avio_wb32(pb, -1);
1670 }
1671 avio_wb32(pb, 0x00010000);
1672 } else {
1673 /* Avoid accidentally ending up with start_ct = -1 which has got a
1674 * special meaning. Normally start_ct should end up positive or zero
1675 * here, but use FFMIN in case dts is a a small positive integer
1676 * rounded to 0 when represented in MOV_TIMESCALE units. */
1677 start_ct = -FFMIN(track->start_dts, 0);
1678 /* Note, this delay is calculated from the pts of the first sample,
1679 * ensuring that we don't reduce the duration for cases with
1680 * dts<0 pts=0. */
1681 duration += delay;
1682 }
1683
1684 /* For fragmented files, we don't know the full length yet. Setting
1685 * duration to 0 allows us to only specify the offset, including
1686 * the rest of the content (from all future fragments) without specifying
1687 * an explicit duration. */
1688 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
1689 duration = 0;
1690
1691 /* duration */
1692 if (version == 1) {
1693 avio_wb64(pb, duration);
1694 avio_wb64(pb, start_ct);
1695 } else {
1696 avio_wb32(pb, duration);
1697 avio_wb32(pb, start_ct);
1698 }
1699 avio_wb32(pb, 0x00010000);
1700 return size;
1701 }
1702
1703 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1704 {
1705 avio_wb32(pb, 20); // size
1706 ffio_wfourcc(pb, "tref");
1707 avio_wb32(pb, 12); // size (subatom)
1708 avio_wl32(pb, track->tref_tag);
1709 avio_wb32(pb, track->tref_id);
1710 return 20;
1711 }
1712
1713 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
1714 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1715 {
1716 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1717 ffio_wfourcc(pb, "uuid");
1718 ffio_wfourcc(pb, "USMT");
1719 avio_wb32(pb, 0x21d24fce);
1720 avio_wb32(pb, 0xbb88695c);
1721 avio_wb32(pb, 0xfac9c740);
1722 avio_wb32(pb, 0x1c); // another size here!
1723 ffio_wfourcc(pb, "MTDT");
1724 avio_wb32(pb, 0x00010012);
1725 avio_wb32(pb, 0x0a);
1726 avio_wb32(pb, 0x55c40000);
1727 avio_wb32(pb, 0x1);
1728 avio_wb32(pb, 0x0);
1729 return 0x34;
1730 }
1731
1732 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
1733 {
1734 AVFormatContext *ctx = track->rtp_ctx;
1735 char buf[1000] = "";
1736 int len;
1737
1738 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
1739 NULL, NULL, 0, 0, ctx);
1740 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
1741 len = strlen(buf);
1742
1743 avio_wb32(pb, len + 24);
1744 ffio_wfourcc(pb, "udta");
1745 avio_wb32(pb, len + 16);
1746 ffio_wfourcc(pb, "hnti");
1747 avio_wb32(pb, len + 8);
1748 ffio_wfourcc(pb, "sdp ");
1749 avio_write(pb, buf, len);
1750 return len + 24;
1751 }
1752
1753 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
1754 const char *tag, const char *str)
1755 {
1756 int64_t pos = avio_tell(pb);
1757 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
1758 if (!t || !utf8len(t->value))
1759 return 0;
1760
1761 avio_wb32(pb, 0); /* size */
1762 ffio_wfourcc(pb, tag); /* type */
1763 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
1764 return update_size(pb, pos);
1765 }
1766
1767 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
1768 AVStream *st)
1769 {
1770 AVIOContext *pb_buf;
1771 int ret, size;
1772 uint8_t *buf;
1773
1774 if (!st)
1775 return 0;
1776
1777 ret = avio_open_dyn_buf(&pb_buf);
1778 if (ret < 0)
1779 return ret;
1780
1781 if (mov->mode & MODE_MP4)
1782 mov_write_track_metadata(pb_buf, st, "name", "title");
1783
1784 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
1785 avio_wb32(pb, size + 8);
1786 ffio_wfourcc(pb, "udta");
1787 avio_write(pb, buf, size);
1788 }
1789 av_free(buf);
1790
1791 return 0;
1792 }
1793
1794 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
1795 MOVTrack *track, AVStream *st)
1796 {
1797 int64_t pos = avio_tell(pb);
1798 int entry_backup = track->entry;
1799 /* If we want to have an empty moov, but some samples already have been
1800 * buffered (delay_moov), pretend that no samples have been written yet. */
1801 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
1802 track->entry = 0;
1803
1804 avio_wb32(pb, 0); /* size */
1805 ffio_wfourcc(pb, "trak");
1806 mov_write_tkhd_tag(pb, mov, track, st);
1807 if (track->start_dts != AV_NOPTS_VALUE &&
1808 (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS ||
1809 track->start_dts || is_clcp_track(track))) {
1810 if (mov->use_editlist)
1811 mov_write_edts_tag(pb, mov, track); // PSP Movies require edts box
1812 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
1813 av_log(mov->fc, AV_LOG_WARNING,
1814 "Not writing any edit list even though one would have been required\n");
1815 }
1816 if (track->tref_tag)
1817 mov_write_tref_tag(pb, track);
1818 mov_write_mdia_tag(mov->fc, pb, mov, track);
1819 if (track->mode == MODE_PSP)
1820 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
1821 if (track->tag == MKTAG('r','t','p',' '))
1822 mov_write_udta_sdp(pb, track);
1823 if (track->mode == MODE_MOV) {
1824 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1825 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1826 if ((0.0 != sample_aspect_ratio && 1.0 != sample_aspect_ratio)) {
1827 mov_write_tapt_tag(pb, track);
1828 }
1829 }
1830 if (is_clcp_track(track)) {
1831 mov_write_tapt_tag(pb, track);
1832 }
1833 }
1834 mov_write_track_udta_tag(pb, mov, st);
1835 track->entry = entry_backup;
1836 return update_size(pb, pos);
1837 }
1838
1839 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1840 {
1841 int i, has_audio = 0, has_video = 0;
1842 int64_t pos = avio_tell(pb);
1843 int audio_profile = mov->iods_audio_profile;
1844 int video_profile = mov->iods_video_profile;
1845 for (i = 0; i < mov->nb_streams; i++) {
1846 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
1847 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
1848 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
1849 }
1850 }
1851 if (audio_profile < 0)
1852 audio_profile = 0xFF - has_audio;
1853 if (video_profile < 0)
1854 video_profile = 0xFF - has_video;
1855 avio_wb32(pb, 0x0); /* size */
1856 ffio_wfourcc(pb, "iods");
1857 avio_wb32(pb, 0); /* version & flags */
1858 put_descr(pb, 0x10, 7);
1859 avio_wb16(pb, 0x004f);
1860 avio_w8(pb, 0xff);
1861 avio_w8(pb, 0xff);
1862 avio_w8(pb, audio_profile);
1863 avio_w8(pb, video_profile);
1864 avio_w8(pb, 0xff);
1865 return update_size(pb, pos);
1866 }
1867
1868 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
1869 {
1870 avio_wb32(pb, 0x20); /* size */
1871 ffio_wfourcc(pb, "trex");
1872 avio_wb32(pb, 0); /* version & flags */
1873 avio_wb32(pb, track->track_id); /* track ID */
1874 avio_wb32(pb, 1); /* default sample description index */
1875 avio_wb32(pb, 0); /* default sample duration */
1876 avio_wb32(pb, 0); /* default sample size */
1877 avio_wb32(pb, 0); /* default sample flags */
1878 return 0;
1879 }
1880
1881 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
1882 {
1883 int64_t pos = avio_tell(pb);
1884 int i;
1885 avio_wb32(pb, 0x0); /* size */
1886 ffio_wfourcc(pb, "mvex");
1887 for (i = 0; i < mov->nb_streams; i++)
1888 mov_write_trex_tag(pb, &mov->tracks[i]);
1889 return update_size(pb, pos);
1890 }
1891
1892 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
1893 {
1894 int max_track_id = 1, i;
1895 int64_t max_track_len_temp, max_track_len = 0;
1896 int version;
1897
1898 for (i = 0; i < mov->nb_streams; i++) {
1899 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
1900 max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
1901 MOV_TIMESCALE,
1902 mov->tracks[i].timescale,
1903 AV_ROUND_UP);
1904 if (max_track_len < max_track_len_temp)
1905 max_track_len = max_track_len_temp;
1906 if (max_track_id < mov->tracks[i].track_id)
1907 max_track_id = mov->tracks[i].track_id;
1908 }
1909 }
1910 /* If using delay_moov, make sure the output is the same as if no
1911 * samples had been written yet. */
1912 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
1913 max_track_len = 0;
1914 max_track_id = 1;
1915 }
1916
1917 version = max_track_len < UINT32_MAX ? 0 : 1;
1918 (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
1919 ffio_wfourcc(pb, "mvhd");
1920 avio_w8(pb, version);
1921 avio_wb24(pb, 0); /* flags */
1922 if (version == 1) {
1923 avio_wb64(pb, mov->time);
1924 avio_wb64(pb, mov->time);
1925 } else {
1926 avio_wb32(pb, mov->time); /* creation time */
1927 avio_wb32(pb, mov->time); /* modification time */
1928 }
1929 avio_wb32(pb, MOV_TIMESCALE);
1930 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
1931
1932 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1933 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1934 avio_wb16(pb, 0); /* reserved */
1935 avio_wb32(pb, 0); /* reserved */
1936 avio_wb32(pb, 0); /* reserved */
1937
1938 /* Matrix structure */
1939 avio_wb32(pb, 0x00010000); /* reserved */
1940 avio_wb32(pb, 0x0); /* reserved */
1941 avio_wb32(pb, 0x0); /* reserved */
1942 avio_wb32(pb, 0x0); /* reserved */
1943 avio_wb32(pb, 0x00010000); /* reserved */
1944 avio_wb32(pb, 0x0); /* reserved */
1945 avio_wb32(pb, 0x0); /* reserved */
1946 avio_wb32(pb, 0x0); /* reserved */
1947 avio_wb32(pb, 0x40000000); /* reserved */
1948
1949 avio_wb32(pb, 0); /* reserved (preview time) */
1950 avio_wb32(pb, 0); /* reserved (preview duration) */
1951 avio_wb32(pb, 0); /* reserved (poster time) */
1952 avio_wb32(pb, 0); /* reserved (selection time) */
1953 avio_wb32(pb, 0); /* reserved (selection duration) */
1954 avio_wb32(pb, 0); /* reserved (current time) */
1955 avio_wb32(pb, max_track_id + 1); /* Next track id */
1956 return 0x6c;
1957 }
1958
1959 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
1960 AVFormatContext *s)
1961 {
1962 avio_wb32(pb, 33); /* size */
1963 ffio_wfourcc(pb, "hdlr");
1964 avio_wb32(pb, 0);
1965 avio_wb32(pb, 0);
1966 ffio_wfourcc(pb, "mdir");
1967 ffio_wfourcc(pb, "appl");
1968 avio_wb32(pb, 0);
1969 avio_wb32(pb, 0);
1970 avio_w8(pb, 0);
1971 return 33;
1972 }
1973
1974 /* helper function to write a data tag with the specified string as data */
1975 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
1976 {
1977 if (long_style) {
1978 int size = 16 + strlen(data);
1979 avio_wb32(pb, size); /* size */
1980 ffio_wfourcc(pb, "data");
1981 avio_wb32(pb, 1);
1982 avio_wb32(pb, 0);
1983 avio_write(pb, data, strlen(data));
1984 return size;
1985 } else {
1986 if (!lang)
1987 lang = ff_mov_iso639_to_lang("und", 1);
1988 avio_wb16(pb, strlen(data)); /* string length */
1989 avio_wb16(pb, lang);
1990 avio_write(pb, data, strlen(data));
1991 return strlen(data) + 4;
1992 }
1993 }
1994
1995 static int mov_write_string_tag(AVIOContext *pb, const char *name,
1996 const char *value, int lang, int long_style)
1997 {
1998 int size = 0;
1999 if (value && value[0]) {
2000 int64_t pos = avio_tell(pb);
2001 avio_wb32(pb, 0); /* size */
2002 ffio_wfourcc(pb, name);
2003 mov_write_string_data_tag(pb, value, lang, long_style);
2004 size = update_size(pb, pos);
2005 }
2006 return size;
2007 }
2008
2009 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
2010 const char *tag, int *lang)
2011 {
2012 int l, len, len2;
2013 AVDictionaryEntry *t, *t2 = NULL;
2014 char tag2[16];
2015
2016 *lang = 0;
2017
2018 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2019 return NULL;
2020
2021 len = strlen(t->key);
2022 snprintf(tag2, sizeof(tag2), "%s-", tag);
2023 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2024 len2 = strlen(t2->key);
2025 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2026 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2027 *lang = l;
2028 return t;
2029 }
2030 }
2031 return t;
2032 }
2033
2034 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2035 const char *name, const char *tag,
2036 int long_style)
2037 {
2038 int lang;
2039 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
2040 if (!t)
2041 return 0;
2042 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2043 }
2044
2045 /* 3GPP TS 26.244 */
2046 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
2047 {
2048 int lang;
2049 int64_t pos = avio_tell(pb);
2050 double latitude, longitude, altitude;
2051 int32_t latitude_fix, longitude_fix, altitude_fix;
2052 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
2053 const char *ptr, *place = "";
2054 char *end;
2055 const char *astronomical_body = "earth";
2056 if (!t)
2057 return 0;
2058
2059 ptr = t->value;
2060 longitude = strtod(ptr, &end);
2061 if (end == ptr) {
2062 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
2063 return 0;
2064 }
2065 ptr = end;
2066 latitude = strtod(ptr, &end);
2067 if (end == ptr) {
2068 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
2069 return 0;
2070 }
2071 ptr = end;
2072 altitude = strtod(ptr, &end);
2073 /* If no altitude was present, the default 0 should be fine */
2074 if (*end == '/')
2075 place = end + 1;
2076
2077 latitude_fix = (int32_t) ((1 << 16) * latitude);
2078 longitude_fix = (int32_t) ((1 << 16) * longitude);
2079 altitude_fix = (int32_t) ((1 << 16) * altitude);
2080
2081 avio_wb32(pb, 0); /* size */
2082 ffio_wfourcc(pb, "loci"); /* type */
2083 avio_wb32(pb, 0); /* version + flags */
2084 avio_wb16(pb, lang);
2085 avio_write(pb, place, strlen(place) + 1);
2086 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
2087 avio_wb32(pb, latitude_fix);
2088 avio_wb32(pb, longitude_fix);
2089 avio_wb32(pb, altitude_fix);
2090 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
2091 avio_w8(pb, 0); /* additional notes, null terminated string */
2092
2093 return update_size(pb, pos);
2094 }
2095
2096 /* iTunes track number */
2097 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2098 AVFormatContext *s)
2099 {
2100 AVDictionaryEntry *t = av_dict_get(s->metadata, "track", NULL, 0);
2101 int size = 0, track = t ? atoi(t->value) : 0;
2102 if (track) {
2103 avio_wb32(pb, 32); /* size */
2104 ffio_wfourcc(pb, "trkn");
2105 avio_wb32(pb, 24); /* size */
2106 ffio_wfourcc(pb, "data");
2107 avio_wb32(pb, 0); // 8 bytes empty
2108 avio_wb32(pb, 0);
2109 avio_wb16(pb, 0); // empty
2110 avio_wb16(pb, track); // track number
2111 avio_wb16(pb, 0); // total track number
2112 avio_wb16(pb, 0); // empty
2113 size = 32;
2114 }
2115 return size;
2116 }
2117
2118 /* iTunes meta data list */
2119 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2120 AVFormatContext *s)
2121 {
2122 int64_t pos = avio_tell(pb);
2123 avio_wb32(pb, 0); /* size */
2124 ffio_wfourcc(pb, "ilst");
2125 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
2126 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
2127 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2128 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2129 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
2130 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
2131 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
2132 if (!(s->flags & AVFMT_FLAG_BITEXACT))
2133 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2134 }
2135 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
2136 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
2137 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2138 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2139 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
2140 mov_write_string_metadata(s, pb, "desc", "description",1);
2141 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
2142 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
2143 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
2144 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
2145 mov_write_trkn_tag(pb, mov, s);
2146 return update_size(pb, pos);
2147 }
2148
2149 /* iTunes meta data tag */
2150 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2151 AVFormatContext *s)
2152 {
2153 int size = 0;
2154 int64_t pos = avio_tell(pb);
2155 avio_wb32(pb, 0); /* size */
2156 ffio_wfourcc(pb, "meta");
2157 avio_wb32(pb, 0);
2158 mov_write_itunes_hdlr_tag(pb, mov, s);
2159 mov_write_ilst_tag(pb, mov, s);
2160 size = update_size(pb, pos);
2161 return size;
2162 }
2163
2164 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2165 {
2166 int val;
2167 while (*b) {
2168 GET_UTF8(val, *b++, return -1;)
2169 avio_wb16(pb, val);
2170 }
2171 avio_wb16(pb, 0x00);
2172 return 0;
2173 }
2174
2175 static uint16_t language_code(const char *str)
2176 {
2177 return (((str[0] - 0x60) & 0x1F) << 10) +
2178 (((str[1] - 0x60) & 0x1F) << 5) +
2179 (( str[2] - 0x60) & 0x1F);
2180 }
2181
2182 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2183 const char *tag, const char *str)
2184 {
2185 int64_t pos = avio_tell(pb);
2186 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2187 if (!t || !utf8len(t->value))
2188 return 0;
2189 avio_wb32(pb, 0); /* size */
2190 ffio_wfourcc(pb, tag); /* type */
2191 avio_wb32(pb, 0); /* version + flags */
2192 if (!strcmp(tag, "yrrc"))
2193 avio_wb16(pb, atoi(t->value));
2194 else {
2195 avio_wb16(pb, language_code("eng")); /* language */
2196 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2197 if (!strcmp(tag, "albm") &&
2198 (t = av_dict_get(s->metadata, "track", NULL, 0)))
2199 avio_w8(pb, atoi(t->value));
2200 }
2201 return update_size(pb, pos);
2202 }
2203
2204 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2205 {
2206 int64_t pos = avio_tell(pb);
2207 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2208
2209 avio_wb32(pb, 0); // size
2210 ffio_wfourcc(pb, "chpl");
2211 avio_wb32(pb, 0x01000000); // version + flags
2212 avio_wb32(pb, 0); // unknown
2213 avio_w8(pb, nb_chapters);
2214
2215 for (i = 0; i < nb_chapters; i++) {
2216 AVChapter *c = s->chapters[i];
2217 AVDictionaryEntry *t;
2218 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2219
2220 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2221 int len = FFMIN(strlen(t->value), 255);
2222 avio_w8(pb, len);
2223 avio_write(pb, t->value, len);
2224 } else
2225 avio_w8(pb, 0);
2226 }
2227 return update_size(pb, pos);
2228 }
2229
2230 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2231 AVFormatContext *s)
2232 {
2233 AVIOContext *pb_buf;
2234 int ret, size;
2235 uint8_t *buf;
2236
2237 ret = avio_open_dyn_buf(&pb_buf);
2238 if (ret < 0)
2239 return ret;
2240
2241 if (mov->mode & MODE_3GP) {
2242 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2243 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2244 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2245 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2246 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2247 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2248 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2249 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2250 mov_write_loci_tag(s, pb_buf);
2251 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2252 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
2253 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
2254 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
2255 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
2256 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
2257 if (!(s->flags & AVFMT_FLAG_BITEXACT))
2258 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
2259 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
2260 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
2261 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
2262 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
2263 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
2264 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
2265 } else {
2266 /* iTunes meta data */
2267 mov_write_meta_tag(pb_buf, mov, s);
2268 mov_write_loci_tag(s, pb_buf);
2269 }
2270
2271 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
2272 mov_write_chpl_tag(pb_buf, s);
2273
2274 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2275 avio_wb32(pb, size + 8);
2276 ffio_wfourcc(pb, "udta");
2277 avio_write(pb, buf, size);
2278 }
2279 av_free(buf);
2280
2281 return 0;
2282 }
2283
2284 static void mov_write_psp_udta_tag(AVIOContext *pb,
2285 const char *str, const char *lang, int type)
2286 {
2287 int len = utf8len(str) + 1;
2288 if (len <= 0)
2289 return;
2290 avio_wb16(pb, len * 2 + 10); /* size */
2291 avio_wb32(pb, type); /* type */
2292 avio_wb16(pb, language_code(lang)); /* language */
2293 avio_wb16(pb, 0x01); /* ? */
2294 ascii_to_wc(pb, str);
2295 }
2296
2297 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2298 {
2299 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2300 int64_t pos, pos2;
2301
2302 if (title) {
2303 pos = avio_tell(pb);
2304 avio_wb32(pb, 0); /* size placeholder*/
2305 ffio_wfourcc(pb, "uuid");
2306 ffio_wfourcc(pb, "USMT");
2307 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2308 avio_wb32(pb, 0xbb88695c);
2309 avio_wb32(pb, 0xfac9c740);
2310
2311 pos2 = avio_tell(pb);
2312 avio_wb32(pb, 0); /* size placeholder*/
2313 ffio_wfourcc(pb, "MTDT");
2314 avio_wb16(pb, 4);
2315
2316 // ?
2317 avio_wb16(pb, 0x0C); /* size */
2318 avio_wb32(pb, 0x0B); /* type */
2319 avio_wb16(pb, language_code("und")); /* language */
2320 avio_wb16(pb, 0x0); /* ? */
2321 avio_wb16(pb, 0x021C); /* data */
2322
2323 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
2324 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
2325 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2326
2327 update_size(pb, pos2);
2328 return update_size(pb, pos);
2329 }
2330
2331 return 0;
2332 }
2333
2334 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2335 AVFormatContext *s)
2336 {
2337 int i;
2338 int64_t pos = avio_tell(pb);
2339 avio_wb32(pb, 0); /* size placeholder*/
2340 ffio_wfourcc(pb, "moov");
2341
2342 for (i = 0; i < mov->nb_streams; i++) {
2343 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2344 continue;
2345
2346 mov->tracks[i].time = mov->time;
2347 mov->tracks[i].track_id = i + 1;
2348 }
2349
2350 if (mov->chapter_track)
2351 for (i = 0; i < s->nb_streams; i++) {
2352 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2353 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
2354 }
2355 for (i = 0; i < mov->nb_streams; i++) {
2356 MOVTrack *track = &mov->tracks[i];
2357 if (track->tag == MKTAG('r','t','p',' ')) {
2358 track->tref_tag = MKTAG('h','i','n','t');
2359 track->tref_id = mov->tracks[track->src_track].track_id;
2360 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2361 int * fallback, size;
2362 fallback = (int*)av_stream_get_side_data(track->st,
2363 AV_PKT_DATA_FALLBACK_TRACK,
2364 &size);
2365 if (fallback != NULL && size == sizeof(int)) {
2366 if (*fallback >= 0 && *fallback < mov->nb_streams) {
2367 track->tref_tag = MKTAG('f','a','l','l');
2368 track->tref_id = mov->tracks[*fallback].track_id;
2369 }
2370 }
2371 }
2372 }
2373
2374 mov_write_mvhd_tag(pb, mov);
2375 if (mov->mode != MODE_MOV && !mov->iods_skip)
2376 mov_write_iods_tag(pb, mov);
2377 for (i = 0; i < mov->nb_streams; i++) {
2378 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2379 mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2380 }
2381 }
2382 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2383 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2384
2385 if (mov->mode == MODE_PSP)
2386 mov_write_uuidusmt_tag(pb, s);
2387 else
2388 mov_write_udta_tag(pb, mov, s);
2389
2390 return update_size(pb, pos);
2391 }
2392
2393 static void param_write_int(AVIOContext *pb, const char *name, int value)
2394 {
2395 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2396 }
2397
2398 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2399 {
2400 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2401 }
2402
2403 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2404 {
2405 char buf[150];
2406 len = FFMIN(sizeof(buf) / 2 - 1, len);
2407 ff_data_to_hex(buf, value, len, 0);
2408 buf[2 * len] = '\0';
2409 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2410 }
2411
2412 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2413 {
2414 int64_t pos = avio_tell(pb);
2415 int i;
2416 static const uint8_t uuid[] = {
2417 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2418 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2419 };
2420
2421 avio_wb32(pb, 0);
2422 ffio_wfourcc(pb, "uuid");
2423 avio_write(pb, uuid, sizeof(uuid));
2424 avio_wb32(pb, 0);
2425
2426 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2427 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2428 avio_printf(pb, "<head>\n");
2429 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2430 LIBAVFORMAT_IDENT);
2431 avio_printf(pb, "</head>\n");
2432 avio_printf(pb, "<body>\n");
2433 avio_printf(pb, "<switch>\n");
2434 for (i = 0; i < mov->nb_streams; i++) {
2435 MOVTrack *track = &mov->tracks[i];
2436 const char *type;
2437 /* track->track_id is initialized in write_moov, and thus isn't known
2438 * here yet */
2439 int track_id = i + 1;
2440
2441 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2442 type = "video";
2443 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2444 type = "audio";
2445 } else {
2446 continue;
2447 }
2448 avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
2449 track->par->bit_rate);
2450 param_write_int(pb, "systemBitrate", track->par->bit_rate);
2451 param_write_int(pb, "trackID", track_id);
2452 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2453 if (track->par->codec_id == AV_CODEC_ID_H264) {
2454 uint8_t *ptr;
2455 int size = track->par->extradata_size;
2456 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
2457 &size)) {
2458 param_write_hex(pb, "CodecPrivateData",
2459 ptr ? ptr : track->par->extradata,
2460 size);
2461 av_free(ptr);
2462 }
2463 param_write_string(pb, "FourCC", "H264");
2464 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
2465 param_write_string(pb, "FourCC", "WVC1");
2466 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
2467 track->par->extradata_size);
2468 }
2469 param_write_int(pb, "MaxWidth", track->par->width);
2470 param_write_int(pb, "MaxHeight", track->par->height);
2471 param_write_int(pb, "DisplayWidth", track->par->width);
2472 param_write_int(pb, "DisplayHeight", track->par->height);
2473 } else {
2474 if (track->par->codec_id == AV_CODEC_ID_AAC) {
2475 param_write_string(pb, "FourCC", "AACL");
2476 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
2477 param_write_string(pb, "FourCC", "WMAP");
2478 }
2479 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
2480 track->par->extradata_size);
2481 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
2482 track->par->codec_id));
2483 param_write_int(pb, "Channels", track->par->channels);
2484 param_write_int(pb, "SamplingRate", track->par->sample_rate);
2485 param_write_int(pb, "BitsPerSample", 16);
2486 param_write_int(pb, "PacketSize", track->par->block_align ?
2487 track->par->block_align : 4);
2488 }
2489 avio_printf(pb, "</%s>\n", type);
2490 }
2491 avio_printf(pb, "</switch>\n");
2492 avio_printf(pb, "</body>\n");
2493 avio_printf(pb, "</smil>\n");
2494
2495 return update_size(pb, pos);
2496 }
2497
2498 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2499 {
2500 avio_wb32(pb, 16);
2501 ffio_wfourcc(pb, "mfhd");
2502 avio_wb32(pb, 0);
2503 avio_wb32(pb, mov->fragments);
2504 return 0;
2505 }
2506
2507 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2508 {
2509 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2510 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2511 }
2512
2513 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2514 MOVTrack *track, int64_t moof_offset)
2515 {
2516 int64_t pos = avio_tell(pb);
2517 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2518 MOV_TFHD_BASE_DATA_OFFSET;
2519 if (!track->entry) {
2520 flags |= MOV_TFHD_DURATION_IS_EMPTY;
2521 } else {
2522 flags |= MOV_TFHD_DEFAULT_FLAGS;
2523 }
2524 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
2525 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
2526 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
2527 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
2528 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
2529 }
2530
2531 /* Don't set a default sample size, the silverlight player refuses
2532 * to play files with that set. Don't set a default sample duration,
2533 * WMP freaks out if it is set. Don't set a base data offset, PIFF
2534 * file format says it MUST NOT be set. */
2535 if (track->mode == MODE_ISM)
2536 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2537 MOV_TFHD_BASE_DATA_OFFSET);
2538
2539 avio_wb32(pb, 0); /* size placeholder */
2540 ffio_wfourcc(pb, "tfhd");
2541 avio_w8(pb, 0); /* version */
2542 avio_wb24(pb, flags);
2543
2544 avio_wb32(pb, track->track_id); /* track-id */
2545 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
2546 avio_wb64(pb, moof_offset);
2547 if (flags & MOV_TFHD_DEFAULT_DURATION) {
2548 track->default_duration = get_cluster_duration(track, 0);
2549 avio_wb32(pb, track->default_duration);
2550 }
2551 if (flags & MOV_TFHD_DEFAULT_SIZE) {
2552 track->default_size = track->entry ? track->cluster[0].size : 1;
2553 avio_wb32(pb, track->default_size);
2554 } else
2555 track->default_size = -1;
2556
2557 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
2558 /* Set the default flags based on the second sample, if available.
2559 * If the first sample is different, that can be signaled via a separate field. */
2560 if (track->entry > 1)
2561 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
2562 else
2563 track->default_sample_flags =
2564 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
2565 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2566 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
2567 avio_wb32(pb, track->default_sample_flags);
2568 }
2569
2570 return update_size(pb, pos);
2571 }
2572
2573 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
2574 MOVTrack *track, int moof_size,
2575 int first, int end)
2576 {
2577 int64_t pos = avio_tell(pb);
2578 uint32_t flags = MOV_TRUN_DATA_OFFSET;
2579 int i;
2580
2581 for (i = first; i < end; i++) {
2582 if (get_cluster_duration(track, i) != track->default_duration)
2583 flags |= MOV_TRUN_SAMPLE_DURATION;
2584 if (track->cluster[i].size != track->default_size)
2585 flags |= MOV_TRUN_SAMPLE_SIZE;
2586 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
2587 flags |= MOV_TRUN_SAMPLE_FLAGS;
2588 }
2589 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
2590 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
2591 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
2592 if (track->flags & MOV_TRACK_CTTS)
2593 flags |= MOV_TRUN_SAMPLE_CTS;
2594
2595 avio_wb32(pb, 0); /* size placeholder */
2596 ffio_wfourcc(pb, "trun");
2597 avio_w8(pb, 0); /* version */
2598 avio_wb24(pb, flags);
2599
2600 avio_wb32(pb, end - first); /* sample count */
2601 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
2602 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
2603 !mov->first_trun)
2604 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
2605 else
2606 avio_wb32(pb, moof_size + 8 + track->data_offset +
2607 track->cluster[first].pos); /* data offset */
2608 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
2609 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
2610
2611 for (i = first; i < end; i++) {
2612 if (flags & MOV_TRUN_SAMPLE_DURATION)
2613 avio_wb32(pb, get_cluster_duration(track, i));
2614 if (flags & MOV_TRUN_SAMPLE_SIZE)
2615 avio_wb32(pb, track->cluster[i].size);
2616 if (flags & MOV_TRUN_SAMPLE_FLAGS)
2617 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
2618 if (flags & MOV_TRUN_SAMPLE_CTS)
2619 avio_wb32(pb, track->cluster[i].cts);
2620 }
2621
2622 mov->first_trun = 0;
2623 return update_size(pb, pos);
2624 }
2625
2626 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2627 {
2628 int64_t pos = avio_tell(pb);
2629 static const uint8_t uuid[] = {
2630 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2631 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2632 };
2633
2634 avio_wb32(pb, 0); /* size placeholder */
2635 ffio_wfourcc(pb, "uuid");
2636 avio_write(pb, uuid, sizeof(uuid));
2637 avio_w8(pb, 1);
2638 avio_wb24(pb, 0);
2639 avio_wb64(pb, track->start_dts + track->frag_start +
2640 track->cluster[0].cts);
2641 avio_wb64(pb, track->end_pts -
2642 (track->cluster[0].dts + track->cluster[0].cts));
2643
2644 return update_size(pb, pos);
2645 }
2646
2647 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2648 MOVTrack *track, int entry)
2649 {
2650 int n = track->nb_frag_info - 1 - entry, i;
2651 int size = 8 + 16 + 4 + 1 + 16*n;
2652 static const uint8_t uuid[] = {
2653 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2654 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2655 };
2656
2657 if (entry < 0)
2658 return 0;
2659
2660 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2661 avio_wb32(pb, size);
2662 ffio_wfourcc(pb, "uuid");
2663 avio_write(pb, uuid, sizeof(uuid));
2664 avio_w8(pb, 1);
2665 avio_wb24(pb, 0);
2666 avio_w8(pb, n);
2667 for (i = 0; i < n; i++) {
2668 int index = entry + 1 + i;
2669 avio_wb64(pb, track->frag_info[index].time);
2670 avio_wb64(pb, track->frag_info[index].duration);
2671 }
2672 if (n < mov->ism_lookahead) {
2673 int free_size = 16 * (mov->ism_lookahead - n);
2674 avio_wb32(pb, free_size);
2675 ffio_wfourcc(pb, "free");
2676 for (i = 0; i < free_size - 8; i++)
2677 avio_w8(pb, 0);
2678 }
2679
2680 return 0;
2681 }
2682
2683 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2684 MOVTrack *track)
2685 {
2686 int64_t pos = avio_tell(pb);
2687 int i;
2688 for (i = 0; i < mov->ism_lookahead; i++) {
2689 /* Update the tfrf tag for the last ism_lookahead fragments,
2690 * nb_frag_info - 1 is the next fragment to be written. */
2691 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2692 }
2693 avio_seek(pb, pos, SEEK_SET);
2694 return 0;
2695 }
2696
2697 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
2698 int size)
2699 {
2700 int i;
2701 for (i = 0; i < mov->nb_streams; i++) {
2702 MOVTrack *track = &mov->tracks[i];
2703 MOVFragmentInfo *info;
2704 if ((tracks >= 0 && i != tracks) || !track->entry)
2705 continue;
2706 track->nb_frag_info++;
2707 if (track->nb_frag_info >= track->frag_info_capacity) {
2708 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
2709 if (av_reallocp_array(&track->frag_info,
2710 new_capacity,
2711 sizeof(*track->frag_info)))
2712 return AVERROR(ENOMEM);
2713 track->frag_info_capacity = new_capacity;
2714 }
2715 info = &track->frag_info[track->nb_frag_info - 1];
2716 info->offset = avio_tell(pb);
2717 info->size = size;
2718 // Try to recreate the original pts for the first packet
2719 // from the fields we have stored
2720 info->time = track->start_dts + track->frag_start +
2721 track->cluster[0].cts;
2722 info->duration = track->end_pts -
2723 (track->cluster[0].dts + track->cluster[0].cts);
2724 // If the pts is less than zero, we will have trimmed
2725 // away parts of the media track using an edit list,
2726 // and the corresponding start presentation time is zero.
2727 if (info->time < 0) {
2728 info->duration += info->time;
2729 info->time = 0;
2730 }
2731 info->tfrf_offset = 0;
2732 mov_write_tfrf_tags(pb, mov, track);
2733 }
2734 return 0;
2735 }
2736
2737 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
2738 {
2739 int i;
2740 for (i = 0; i < mov->nb_streams; i++) {
2741 MOVTrack *track = &mov->tracks[i];
2742 if ((tracks >= 0 && i != tracks) || !track->entry)
2743 continue;
2744 if (track->nb_frag_info > max) {
2745 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
2746 track->nb_frag_info = max;
2747 }
2748 }
2749 }
2750
2751 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
2752 {
2753 int64_t pos = avio_tell(pb);
2754
2755 avio_wb32(pb, 0); /* size */
2756 ffio_wfourcc(pb, "tfdt");
2757 avio_w8(pb, 1); /* version */
2758 avio_wb24(pb, 0);
2759 avio_wb64(pb, track->frag_start);
2760 return update_size(pb, pos);
2761 }
2762
2763 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
2764 MOVTrack *track, int64_t moof_offset,
2765 int moof_size)
2766 {
2767 int64_t pos = avio_tell(pb);
2768 int i, start = 0;
2769 avio_wb32(pb, 0); /* size placeholder */
2770 ffio_wfourcc(pb, "traf");
2771
2772 mov_write_tfhd_tag(pb, mov, track, moof_offset);
2773 if (mov->mode != MODE_ISM)
2774 mov_write_tfdt_tag(pb, track);
2775 for (i = 1; i < track->entry; i++) {
2776 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
2777 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
2778 start = i;
2779 }
2780 }
2781 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
2782 if (mov->mode == MODE_ISM) {
2783 mov_write_tfxd_tag(pb, track);
2784
2785 if (mov->ism_lookahead) {
2786 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
2787
2788 if (track->nb_frag_info > 0) {
2789 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
2790 if (!info->tfrf_offset)
2791 info->tfrf_offset = avio_tell(pb);
2792 }
2793 avio_wb32(pb, 8 + size);
2794 ffio_wfourcc(pb, "free");
2795 for (i = 0; i < size; i++)
2796 avio_w8(pb, 0);
2797 }
2798 }
2799
2800 return update_size(pb, pos);
2801 }
2802
2803 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
2804 int tracks, int moof_size)
2805 {
2806 int64_t pos = avio_tell(pb);
2807 int i;
2808
2809 avio_wb32(pb, 0); /* size placeholder */
2810 ffio_wfourcc(pb, "moof");
2811 mov->first_trun = 1;
2812
2813 mov_write_mfhd_tag(pb, mov);
2814 for (i = 0; i < mov->nb_streams; i++) {
2815 MOVTrack *track = &mov->tracks[i];
2816 if (tracks >= 0 && i != tracks)
2817 continue;
2818 if (!track->entry)
2819 continue;
2820 mov_write_traf_tag(pb, mov, track, pos, moof_size);
2821 }
2822