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