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