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