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