]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
Merge commit '5fccedaa67390ccddd6347c8e1c71b7664558bcd'
[ffmpeg] / 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 FFmpeg.
8  *
9  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include <stdint.h>
25 #include <inttypes.h>
26
27 #include "movenc.h"
28 #include "avformat.h"
29 #include "avio_internal.h"
30 #include "riff.h"
31 #include "avio.h"
32 #include "isom.h"
33 #include "avc.h"
34 #include "libavcodec/get_bits.h"
35 #include "libavcodec/put_bits.h"
36 #include "libavcodec/vc1.h"
37 #include "libavcodec/raw.h"
38 #include "internal.h"
39 #include "libavutil/avstring.h"
40 #include "libavutil/intfloat.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/opt.h"
43 #include "libavutil/dict.h"
44 #include "libavutil/pixdesc.h"
45 #include "hevc.h"
46 #include "rtpenc.h"
47 #include "mov_chan.h"
48
49 #undef NDEBUG
50 #include <assert.h>
51
52 static const AVOption options[] = {
53     { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
54     { "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" },
55     { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
56     { "empty_moov", "Make the initial moov atom empty (not supported by QuickTime)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
57     { "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" },
58     { "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" },
59     { "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" },
60     { "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" },
61     { "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" },
62     { "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" },
63     FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
64     { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
65     { "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},
66     { "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},
67     { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
68     { "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},
69     { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
70     { "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},
71     { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
72     { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
73     { "brand",    "Override major brand", offsetof(MOVMuxContext, major_brand),   AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
74     { NULL },
75 };
76
77 #define MOV_CLASS(flavor)\
78 static const AVClass flavor ## _muxer_class = {\
79     .class_name = #flavor " muxer",\
80     .item_name  = av_default_item_name,\
81     .option     = options,\
82     .version    = LIBAVUTIL_VERSION_INT,\
83 };
84
85 static int get_moov_size(AVFormatContext *s);
86
87 //FIXME support 64 bit variant with wide placeholders
88 static int64_t update_size(AVIOContext *pb, int64_t pos)
89 {
90     int64_t curpos = avio_tell(pb);
91     avio_seek(pb, pos, SEEK_SET);
92     avio_wb32(pb, curpos - pos); /* rewrite size */
93     avio_seek(pb, curpos, SEEK_SET);
94
95     return curpos - pos;
96 }
97
98 static int supports_edts(MOVMuxContext *mov)
99 {
100     // EDTS with fragments is tricky as we don't know the duration when its written
101     return (mov->use_editlist<0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) || mov->use_editlist>0;
102 }
103
104 static int co64_required(const MOVTrack *track)
105 {
106     if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
107         return 1;
108     return 0;
109 }
110
111 /* Chunk offset atom */
112 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
113 {
114     int i;
115     int mode64 = co64_required(track); // use 32 bit size variant if possible
116     int64_t pos = avio_tell(pb);
117     avio_wb32(pb, 0); /* size */
118     if (mode64)
119         ffio_wfourcc(pb, "co64");
120     else
121         ffio_wfourcc(pb, "stco");
122     avio_wb32(pb, 0); /* version & flags */
123     avio_wb32(pb, track->chunkCount); /* entry count */
124     for (i = 0; i < track->entry; i++) {
125         if (!track->cluster[i].chunkNum)
126             continue;
127         if (mode64 == 1)
128             avio_wb64(pb, track->cluster[i].pos + track->data_offset);
129         else
130             avio_wb32(pb, track->cluster[i].pos + track->data_offset);
131     }
132     return update_size(pb, pos);
133 }
134
135 /* Sample size atom */
136 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
137 {
138     int equalChunks = 1;
139     int i, j, entries = 0, tst = -1, oldtst = -1;
140
141     int64_t pos = avio_tell(pb);
142     avio_wb32(pb, 0); /* size */
143     ffio_wfourcc(pb, "stsz");
144     avio_wb32(pb, 0); /* version & flags */
145
146     for (i = 0; i < track->entry; i++) {
147         tst = track->cluster[i].size / track->cluster[i].entries;
148         if (oldtst != -1 && tst != oldtst)
149             equalChunks = 0;
150         oldtst = tst;
151         entries += track->cluster[i].entries;
152     }
153     if (equalChunks && track->entry) {
154         int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
155         sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
156         avio_wb32(pb, sSize); // sample size
157         avio_wb32(pb, entries); // sample count
158     } else {
159         avio_wb32(pb, 0); // sample size
160         avio_wb32(pb, entries); // sample count
161         for (i = 0; i < track->entry; i++) {
162             for (j = 0; j < track->cluster[i].entries; j++) {
163                 avio_wb32(pb, track->cluster[i].size /
164                           track->cluster[i].entries);
165             }
166         }
167     }
168     return update_size(pb, pos);
169 }
170
171 /* Sample to chunk atom */
172 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
173 {
174     int index = 0, oldval = -1, i;
175     int64_t entryPos, curpos;
176
177     int64_t pos = avio_tell(pb);
178     avio_wb32(pb, 0); /* size */
179     ffio_wfourcc(pb, "stsc");
180     avio_wb32(pb, 0); // version & flags
181     entryPos = avio_tell(pb);
182     avio_wb32(pb, track->chunkCount); // entry count
183     for (i = 0; i < track->entry; i++) {
184         if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
185             avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
186             avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
187             avio_wb32(pb, 0x1); // sample description index
188             oldval = track->cluster[i].samples_in_chunk;
189             index++;
190         }
191     }
192     curpos = avio_tell(pb);
193     avio_seek(pb, entryPos, SEEK_SET);
194     avio_wb32(pb, index); // rewrite size
195     avio_seek(pb, curpos, SEEK_SET);
196
197     return update_size(pb, pos);
198 }
199
200 /* Sync sample atom */
201 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
202 {
203     int64_t curpos, entryPos;
204     int i, index = 0;
205     int64_t pos = avio_tell(pb);
206     avio_wb32(pb, 0); // size
207     ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
208     avio_wb32(pb, 0); // version & flags
209     entryPos = avio_tell(pb);
210     avio_wb32(pb, track->entry); // entry count
211     for (i = 0; i < track->entry; i++) {
212         if (track->cluster[i].flags & flag) {
213             avio_wb32(pb, i + 1);
214             index++;
215         }
216     }
217     curpos = avio_tell(pb);
218     avio_seek(pb, entryPos, SEEK_SET);
219     avio_wb32(pb, index); // rewrite size
220     avio_seek(pb, curpos, SEEK_SET);
221     return update_size(pb, pos);
222 }
223
224 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
225 {
226     avio_wb32(pb, 0x11); /* size */
227     if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
228     else                         ffio_wfourcc(pb, "damr");
229     ffio_wfourcc(pb, "FFMP");
230     avio_w8(pb, 0); /* decoder version */
231
232     avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
233     avio_w8(pb, 0x00); /* Mode change period (no restriction) */
234     avio_w8(pb, 0x01); /* Frames per sample */
235     return 0x11;
236 }
237
238 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
239 {
240     GetBitContext gbc;
241     PutBitContext pbc;
242     uint8_t buf[3];
243     int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
244
245     if (track->vos_len < 7)
246         return -1;
247
248     avio_wb32(pb, 11);
249     ffio_wfourcc(pb, "dac3");
250
251     init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
252     fscod      = get_bits(&gbc, 2);
253     frmsizecod = get_bits(&gbc, 6);
254     bsid       = get_bits(&gbc, 5);
255     bsmod      = get_bits(&gbc, 3);
256     acmod      = get_bits(&gbc, 3);
257     if (acmod == 2) {
258         skip_bits(&gbc, 2); // dsurmod
259     } else {
260         if ((acmod & 1) && acmod != 1)
261             skip_bits(&gbc, 2); // cmixlev
262         if (acmod & 4)
263             skip_bits(&gbc, 2); // surmixlev
264     }
265     lfeon = get_bits1(&gbc);
266
267     init_put_bits(&pbc, buf, sizeof(buf));
268     put_bits(&pbc, 2, fscod);
269     put_bits(&pbc, 5, bsid);
270     put_bits(&pbc, 3, bsmod);
271     put_bits(&pbc, 3, acmod);
272     put_bits(&pbc, 1, lfeon);
273     put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
274     put_bits(&pbc, 5, 0); // reserved
275
276     flush_put_bits(&pbc);
277     avio_write(pb, buf, sizeof(buf));
278
279     return 11;
280 }
281
282 /**
283  * This function writes extradata "as is".
284  * Extradata must be formatted like a valid atom (with size and tag).
285  */
286 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
287 {
288     avio_write(pb, track->enc->extradata, track->enc->extradata_size);
289     return track->enc->extradata_size;
290 }
291
292 static int mov_write_enda_tag(AVIOContext *pb)
293 {
294     avio_wb32(pb, 10);
295     ffio_wfourcc(pb, "enda");
296     avio_wb16(pb, 1); /* little endian */
297     return 10;
298 }
299
300 static int mov_write_enda_tag_be(AVIOContext *pb)
301 {
302   avio_wb32(pb, 10);
303   ffio_wfourcc(pb, "enda");
304   avio_wb16(pb, 0); /* big endian */
305   return 10;
306 }
307
308 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
309 {
310     int i = 3;
311     avio_w8(pb, tag);
312     for (; i > 0; i--)
313         avio_w8(pb, (size >> (7 * i)) | 0x80);
314     avio_w8(pb, size & 0x7F);
315 }
316
317 static unsigned compute_avg_bitrate(MOVTrack *track)
318 {
319     uint64_t size = 0;
320     int i;
321     if (!track->track_duration)
322         return 0;
323     for (i = 0; i < track->entry; i++)
324         size += track->cluster[i].size;
325     return size * 8 * track->timescale / track->track_duration;
326 }
327
328 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
329 {
330     int64_t pos = avio_tell(pb);
331     int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
332     unsigned avg_bitrate;
333
334     avio_wb32(pb, 0); // size
335     ffio_wfourcc(pb, "esds");
336     avio_wb32(pb, 0); // Version
337
338     // ES descriptor
339     put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
340     avio_wb16(pb, track->track_id);
341     avio_w8(pb, 0x00); // flags (= no flags)
342
343     // DecoderConfig descriptor
344     put_descr(pb, 0x04, 13 + decoder_specific_info_len);
345
346     // Object type indication
347     if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
348          track->enc->codec_id == AV_CODEC_ID_MP3) &&
349         track->enc->sample_rate > 24000)
350         avio_w8(pb, 0x6B); // 11172-3
351     else
352         avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
353
354     // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
355     // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
356     if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
357         avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
358     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
359         avio_w8(pb, 0x15); // flags (= Audiostream)
360     else
361         avio_w8(pb, 0x11); // flags (= Visualstream)
362
363     avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
364
365     avg_bitrate = compute_avg_bitrate(track);
366     // maxbitrate (FIXME should be max rate in any 1 sec window)
367     avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
368     avio_wb32(pb, avg_bitrate);
369
370     if (track->vos_len) {
371         // DecoderSpecific info descriptor
372         put_descr(pb, 0x05, track->vos_len);
373         avio_write(pb, track->vos_data, track->vos_len);
374     }
375
376     // SL descriptor
377     put_descr(pb, 0x06, 1);
378     avio_w8(pb, 0x02);
379     return update_size(pb, pos);
380 }
381
382 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
383 {
384     return codec_id == AV_CODEC_ID_PCM_S24LE ||
385            codec_id == AV_CODEC_ID_PCM_S32LE ||
386            codec_id == AV_CODEC_ID_PCM_F32LE ||
387            codec_id == AV_CODEC_ID_PCM_F64LE;
388 }
389
390 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
391 {
392     return codec_id == AV_CODEC_ID_PCM_S24BE ||
393            codec_id == AV_CODEC_ID_PCM_S32BE ||
394            codec_id == AV_CODEC_ID_PCM_F32BE ||
395            codec_id == AV_CODEC_ID_PCM_F64BE;
396 }
397
398 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
399 {
400     int64_t pos = avio_tell(pb);
401     avio_wb32(pb, 0);
402     avio_wl32(pb, track->tag); // store it byteswapped
403     track->enc->codec_tag = av_bswap16(track->tag >> 16);
404     ff_put_wav_header(pb, track->enc, 0);
405     return update_size(pb, pos);
406 }
407
408 static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
409 {
410     int64_t pos = avio_tell(pb);
411     avio_wb32(pb, 0);
412     ffio_wfourcc(pb, "wfex");
413     ff_put_wav_header(pb, track->enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);
414     return update_size(pb, pos);
415 }
416
417 static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
418 {
419     uint32_t layout_tag, bitmap;
420     int64_t pos = avio_tell(pb);
421
422     layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
423                                                track->enc->channel_layout,
424                                                &bitmap);
425     if (!layout_tag) {
426         av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
427                "lack of channel information\n");
428         return 0;
429     }
430
431     avio_wb32(pb, 0);           // Size
432     ffio_wfourcc(pb, "chan");   // Type
433     avio_w8(pb, 0);             // Version
434     avio_wb24(pb, 0);           // Flags
435     avio_wb32(pb, layout_tag);  // mChannelLayoutTag
436     avio_wb32(pb, bitmap);      // mChannelBitmap
437     avio_wb32(pb, 0);           // mNumberChannelDescriptions
438
439     return update_size(pb, pos);
440 }
441
442 static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
443 {
444     int64_t pos = avio_tell(pb);
445
446     avio_wb32(pb, 0);     /* size */
447     ffio_wfourcc(pb, "wave");
448
449     if (track->enc->codec_id != AV_CODEC_ID_QDM2) {
450     avio_wb32(pb, 12);    /* size */
451     ffio_wfourcc(pb, "frma");
452     avio_wl32(pb, track->tag);
453     }
454
455     if (track->enc->codec_id == AV_CODEC_ID_AAC) {
456         /* useless atom needed by mplayer, ipod, not needed by quicktime */
457         avio_wb32(pb, 12); /* size */
458         ffio_wfourcc(pb, "mp4a");
459         avio_wb32(pb, 0);
460         mov_write_esds_tag(pb, track);
461     } else if (mov_pcm_le_gt16(track->enc->codec_id))  {
462       mov_write_enda_tag(pb);
463     } else if (mov_pcm_be_gt16(track->enc->codec_id))  {
464       mov_write_enda_tag_be(pb);
465     } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
466         mov_write_amr_tag(pb, track);
467     } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
468         mov_write_ac3_tag(pb, track);
469     } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||
470                track->enc->codec_id == AV_CODEC_ID_QDM2) {
471         mov_write_extradata_tag(pb, track);
472     } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
473                track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
474         mov_write_ms_tag(pb, track);
475     }
476
477     avio_wb32(pb, 8);     /* size */
478     avio_wb32(pb, 0);     /* null tag */
479
480     return update_size(pb, pos);
481 }
482
483 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
484 {
485     uint8_t *unescaped;
486     const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
487     int unescaped_size, seq_found = 0;
488     int level = 0, interlace = 0;
489     int packet_seq   = track->vc1_info.packet_seq;
490     int packet_entry = track->vc1_info.packet_entry;
491     int slices       = track->vc1_info.slices;
492     PutBitContext pbc;
493
494     if (track->start_dts == AV_NOPTS_VALUE) {
495         /* No packets written yet, vc1_info isn't authoritative yet. */
496         /* Assume inline sequence and entry headers. This will be
497          * overwritten at the end if the file is seekable. */
498         packet_seq = packet_entry = 1;
499     }
500
501     unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
502     if (!unescaped)
503         return AVERROR(ENOMEM);
504     start = find_next_marker(track->vos_data, end);
505     for (next = start; next < end; start = next) {
506         GetBitContext gb;
507         int size;
508         next = find_next_marker(start + 4, end);
509         size = next - start - 4;
510         if (size <= 0)
511             continue;
512         unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
513         init_get_bits(&gb, unescaped, 8 * unescaped_size);
514         if (AV_RB32(start) == VC1_CODE_SEQHDR) {
515             int profile = get_bits(&gb, 2);
516             if (profile != PROFILE_ADVANCED) {
517                 av_free(unescaped);
518                 return AVERROR(ENOSYS);
519             }
520             seq_found = 1;
521             level = get_bits(&gb, 3);
522             /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
523              * width, height */
524             skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
525             skip_bits(&gb, 1); /* broadcast */
526             interlace = get_bits1(&gb);
527             skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
528         }
529     }
530     if (!seq_found) {
531         av_free(unescaped);
532         return AVERROR(ENOSYS);
533     }
534
535     init_put_bits(&pbc, buf, 7);
536     /* VC1DecSpecStruc */
537     put_bits(&pbc, 4, 12); /* profile - advanced */
538     put_bits(&pbc, 3, level);
539     put_bits(&pbc, 1, 0); /* reserved */
540     /* VC1AdvDecSpecStruc */
541     put_bits(&pbc, 3, level);
542     put_bits(&pbc, 1, 0); /* cbr */
543     put_bits(&pbc, 6, 0); /* reserved */
544     put_bits(&pbc, 1, !interlace); /* no interlace */
545     put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
546     put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
547     put_bits(&pbc, 1, !slices); /* no slice code */
548     put_bits(&pbc, 1, 0); /* no bframe */
549     put_bits(&pbc, 1, 0); /* reserved */
550     put_bits32(&pbc, track->enc->time_base.den); /* framerate */
551     flush_put_bits(&pbc);
552
553     av_free(unescaped);
554
555     return 0;
556 }
557
558 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
559 {
560     uint8_t buf[7] = { 0 };
561     int ret;
562
563     if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
564         return ret;
565
566     avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
567     ffio_wfourcc(pb, "dvc1");
568     track->vc1_info.struct_offset = avio_tell(pb);
569     avio_write(pb, buf, sizeof(buf));
570     avio_write(pb, track->vos_data, track->vos_len);
571
572     return 0;
573 }
574
575 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
576 {
577     avio_wb32(pb, track->vos_len + 8);
578     ffio_wfourcc(pb, "glbl");
579     avio_write(pb, track->vos_data, track->vos_len);
580     return 8 + track->vos_len;
581 }
582
583 /**
584  * Compute flags for 'lpcm' tag.
585  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
586  */
587 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
588 {
589     switch (codec_id) {
590     case AV_CODEC_ID_PCM_F32BE:
591     case AV_CODEC_ID_PCM_F64BE:
592         return 11;
593     case AV_CODEC_ID_PCM_F32LE:
594     case AV_CODEC_ID_PCM_F64LE:
595         return 9;
596     case AV_CODEC_ID_PCM_U8:
597         return 10;
598     case AV_CODEC_ID_PCM_S16BE:
599     case AV_CODEC_ID_PCM_S24BE:
600     case AV_CODEC_ID_PCM_S32BE:
601         return 14;
602     case AV_CODEC_ID_PCM_S8:
603     case AV_CODEC_ID_PCM_S16LE:
604     case AV_CODEC_ID_PCM_S24LE:
605     case AV_CODEC_ID_PCM_S32LE:
606         return 12;
607     default:
608         return 0;
609     }
610 }
611
612 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
613 {
614     int64_t next_dts;
615
616     if (cluster_idx >= track->entry)
617         return 0;
618
619     if (cluster_idx + 1 == track->entry)
620         next_dts = track->track_duration + track->start_dts;
621     else
622         next_dts = track->cluster[cluster_idx + 1].dts;
623
624     next_dts -= track->cluster[cluster_idx].dts;
625
626     av_assert0(next_dts >= 0);
627     av_assert0(next_dts <= INT_MAX);
628
629     return next_dts;
630 }
631
632 static int get_samples_per_packet(MOVTrack *track)
633 {
634     int i, first_duration;
635
636 // return track->enc->frame_size;
637
638     /* use 1 for raw PCM */
639     if (!track->audio_vbr)
640         return 1;
641
642     /* check to see if duration is constant for all clusters */
643     if (!track->entry)
644         return 0;
645     first_duration = get_cluster_duration(track, 0);
646     for (i = 1; i < track->entry; i++) {
647         if (get_cluster_duration(track, i) != first_duration)
648             return 0;
649     }
650     return first_duration;
651 }
652
653 static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
654 {
655     int64_t pos = avio_tell(pb);
656     int version = 0;
657     uint32_t tag = track->tag;
658
659     if (track->mode == MODE_MOV) {
660         if (track->timescale > UINT16_MAX) {
661             if (mov_get_lpcm_flags(track->enc->codec_id))
662                 tag = AV_RL32("lpcm");
663             version = 2;
664         } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
665                    mov_pcm_be_gt16(track->enc->codec_id) ||
666                    track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
667                    track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
668                    track->enc->codec_id == AV_CODEC_ID_QDM2) {
669             version = 1;
670         }
671     }
672
673     avio_wb32(pb, 0); /* size */
674     avio_wl32(pb, tag); // store it byteswapped
675     avio_wb32(pb, 0); /* Reserved */
676     avio_wb16(pb, 0); /* Reserved */
677     avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */
678
679     /* SoundDescription */
680     avio_wb16(pb, version); /* Version */
681     avio_wb16(pb, 0); /* Revision level */
682     avio_wb32(pb, 0); /* Reserved */
683
684     if (version == 2) {
685         avio_wb16(pb, 3);
686         avio_wb16(pb, 16);
687         avio_wb16(pb, 0xfffe);
688         avio_wb16(pb, 0);
689         avio_wb32(pb, 0x00010000);
690         avio_wb32(pb, 72);
691         avio_wb64(pb, av_double2int(track->enc->sample_rate));
692         avio_wb32(pb, track->enc->channels);
693         avio_wb32(pb, 0x7F000000);
694         avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
695         avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
696         avio_wb32(pb, track->sample_size);
697         avio_wb32(pb, get_samples_per_packet(track));
698     } else {
699         if (track->mode == MODE_MOV) {
700             avio_wb16(pb, track->enc->channels);
701             if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||
702                 track->enc->codec_id == AV_CODEC_ID_PCM_S8)
703                 avio_wb16(pb, 8); /* bits per sample */
704             else
705                 avio_wb16(pb, 16);
706             avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
707         } else { /* reserved for mp4/3gp */
708             avio_wb16(pb, 2);
709             avio_wb16(pb, 16);
710             avio_wb16(pb, 0);
711         }
712
713         avio_wb16(pb, 0); /* packet size (= 0) */
714         avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
715                       track->enc->sample_rate : 0);
716         avio_wb16(pb, 0); /* Reserved */
717     }
718
719     if (version == 1) { /* SoundDescription V1 extended info */
720         if (mov_pcm_le_gt16(track->enc->codec_id) ||
721             mov_pcm_be_gt16(track->enc->codec_id))
722             avio_wb32(pb, 1); /*  must be 1 for  uncompressed formats */
723         else
724             avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
725         avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
726         avio_wb32(pb, track->sample_size); /* Bytes per frame */
727         avio_wb32(pb, 2); /* Bytes per sample */
728     }
729
730     if (track->mode == MODE_MOV &&
731         (track->enc->codec_id == AV_CODEC_ID_AAC           ||
732          track->enc->codec_id == AV_CODEC_ID_AC3           ||
733          track->enc->codec_id == AV_CODEC_ID_AMR_NB        ||
734          track->enc->codec_id == AV_CODEC_ID_ALAC          ||
735          track->enc->codec_id == AV_CODEC_ID_ADPCM_MS      ||
736          track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
737          track->enc->codec_id == AV_CODEC_ID_QDM2          ||
738          (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
739          (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
740         mov_write_wave_tag(pb, track);
741     else if (track->tag == MKTAG('m','p','4','a'))
742         mov_write_esds_tag(pb, track);
743     else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
744         mov_write_amr_tag(pb, track);
745     else if (track->enc->codec_id == AV_CODEC_ID_AC3)
746         mov_write_ac3_tag(pb, track);
747     else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
748         mov_write_extradata_tag(pb, track);
749     else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
750         mov_write_wfex_tag(pb, track);
751     else if (track->vos_len > 0)
752         mov_write_glbl_tag(pb, track);
753
754     if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
755         mov_write_chan_tag(pb, track);
756
757     return update_size(pb, pos);
758 }
759
760 static int mov_write_d263_tag(AVIOContext *pb)
761 {
762     avio_wb32(pb, 0xf); /* size */
763     ffio_wfourcc(pb, "d263");
764     ffio_wfourcc(pb, "FFMP");
765     avio_w8(pb, 0); /* decoder version */
766     /* FIXME use AVCodecContext level/profile, when encoder will set values */
767     avio_w8(pb, 0xa); /* level */
768     avio_w8(pb, 0); /* profile */
769     return 0xf;
770 }
771
772 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
773 {
774     int64_t pos = avio_tell(pb);
775
776     avio_wb32(pb, 0);
777     ffio_wfourcc(pb, "avcC");
778     ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
779     return update_size(pb, pos);
780 }
781
782 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
783 {
784     int64_t pos = avio_tell(pb);
785
786     avio_wb32(pb, 0);
787     ffio_wfourcc(pb, "hvcC");
788     ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
789     return update_size(pb, pos);
790 }
791
792 /* also used by all avid codecs (dv, imx, meridien) and their variants */
793 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
794 {
795     int i;
796     avio_wb32(pb, 24); /* size */
797     ffio_wfourcc(pb, "ACLR");
798     ffio_wfourcc(pb, "ACLR");
799     ffio_wfourcc(pb, "0001");
800     avio_wb32(pb, 2); /* yuv range: full 1 / normal 2 */
801     avio_wb32(pb, 0); /* unknown */
802
803     avio_wb32(pb, 24); /* size */
804     ffio_wfourcc(pb, "APRG");
805     ffio_wfourcc(pb, "APRG");
806     ffio_wfourcc(pb, "0001");
807     avio_wb32(pb, 1); /* unknown */
808     avio_wb32(pb, 0); /* unknown */
809
810     avio_wb32(pb, 120); /* size */
811     ffio_wfourcc(pb, "ARES");
812     ffio_wfourcc(pb, "ARES");
813     ffio_wfourcc(pb, "0001");
814     avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
815     avio_wb32(pb, track->enc->width);
816     /* values below are based on samples created with quicktime and avid codecs */
817     if (track->vos_data[5] & 2) { // interlaced
818         avio_wb32(pb, track->enc->height / 2);
819         avio_wb32(pb, 2); /* unknown */
820         avio_wb32(pb, 0); /* unknown */
821         avio_wb32(pb, 4); /* unknown */
822     } else {
823         avio_wb32(pb, track->enc->height);
824         avio_wb32(pb, 1); /* unknown */
825         avio_wb32(pb, 0); /* unknown */
826         if (track->enc->height == 1080)
827             avio_wb32(pb, 5); /* unknown */
828         else
829             avio_wb32(pb, 6); /* unknown */
830     }
831     /* padding */
832     for (i = 0; i < 10; i++)
833         avio_wb64(pb, 0);
834
835     /* extra padding for stsd needed */
836     avio_wb32(pb, 0);
837     return 0;
838 }
839
840 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
841 {
842     int tag = track->enc->codec_tag;
843
844     if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
845         return 0;
846
847     if      (track->enc->codec_id == AV_CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
848     else if (track->enc->codec_id == AV_CODEC_ID_HEVC)      tag = MKTAG('h','e','v','1');
849     else if (track->enc->codec_id == AV_CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
850     else if (track->enc->codec_id == AV_CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
851     else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
852     else if (track->enc->codec_id == AV_CODEC_ID_VC1)       tag = MKTAG('v','c','-','1');
853     else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)  tag = MKTAG('m','p','4','v');
854     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)  tag = MKTAG('m','p','4','a');
855     else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)  tag = MKTAG('m','p','4','s');
856
857     return tag;
858 }
859
860 static const AVCodecTag codec_ipod_tags[] = {
861     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
862     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
863     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
864     { AV_CODEC_ID_ALAC,     MKTAG('a','l','a','c') },
865     { AV_CODEC_ID_AC3,      MKTAG('a','c','-','3') },
866     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
867     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
868     { AV_CODEC_ID_NONE, 0 },
869 };
870
871 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
872 {
873     int tag = track->enc->codec_tag;
874
875     // keep original tag for subs, ipod supports both formats
876     if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
877           (tag == MKTAG('t', 'x', '3', 'g') ||
878            tag == MKTAG('t', 'e', 'x', 't'))))
879         tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
880
881     if (!av_match_ext(s->filename, "m4a") && !av_match_ext(s->filename, "m4v"))
882         av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
883                "Quicktime/Ipod might not play the file\n");
884
885     return tag;
886 }
887
888 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
889 {
890     int tag;
891
892     if (track->enc->width == 720) { /* SD */
893         if (track->enc->height == 480) { /* NTSC */
894             if  (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
895             else                                            tag = MKTAG('d','v','c',' ');
896        }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
897         else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
898         else                                                tag = MKTAG('d','v','p','p');
899     } else if (track->enc->height == 720) { /* HD 720 line */
900         if  (track->enc->time_base.den == 50)               tag = MKTAG('d','v','h','q');
901         else                                                tag = MKTAG('d','v','h','p');
902     } else if (track->enc->height == 1080) { /* HD 1080 line */
903         if  (track->enc->time_base.den == 25)               tag = MKTAG('d','v','h','5');
904         else                                                tag = MKTAG('d','v','h','6');
905     } else {
906         av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
907         return 0;
908     }
909
910     return tag;
911 }
912
913 static AVRational find_fps(AVFormatContext *s, AVStream *st)
914 {
915     AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
916     /* if the codec time base makes no sense, try to fallback on stream frame rate */
917     if (av_timecode_check_frame_rate(rate) < 0) {
918         av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
919                rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
920         rate = st->avg_frame_rate;
921     }
922
923     return rate;
924 }
925
926 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
927 {
928     int tag = track->enc->codec_tag;
929     int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
930     AVStream *st = track->st;
931     int rate = av_q2d(find_fps(s, st));
932
933     if (!tag)
934         tag = MKTAG('m', '2', 'v', '1'); //fallback tag
935
936     if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
937         if (track->enc->width == 1280 && track->enc->height == 720) {
938             if (!interlaced) {
939                 if      (rate == 24) tag = MKTAG('x','d','v','4');
940                 else if (rate == 25) tag = MKTAG('x','d','v','5');
941                 else if (rate == 30) tag = MKTAG('x','d','v','1');
942                 else if (rate == 50) tag = MKTAG('x','d','v','a');
943                 else if (rate == 60) tag = MKTAG('x','d','v','9');
944             }
945         } else if (track->enc->width == 1440 && track->enc->height == 1080) {
946             if (!interlaced) {
947                 if      (rate == 24) tag = MKTAG('x','d','v','6');
948                 else if (rate == 25) tag = MKTAG('x','d','v','7');
949                 else if (rate == 30) tag = MKTAG('x','d','v','8');
950             } else {
951                 if      (rate == 25) tag = MKTAG('x','d','v','3');
952                 else if (rate == 30) tag = MKTAG('x','d','v','2');
953             }
954         } else if (track->enc->width == 1920 && track->enc->height == 1080) {
955             if (!interlaced) {
956                 if      (rate == 24) tag = MKTAG('x','d','v','d');
957                 else if (rate == 25) tag = MKTAG('x','d','v','e');
958                 else if (rate == 30) tag = MKTAG('x','d','v','f');
959             } else {
960                 if      (rate == 25) tag = MKTAG('x','d','v','c');
961                 else if (rate == 30) tag = MKTAG('x','d','v','b');
962             }
963         }
964     } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
965         if (track->enc->width == 1280 && track->enc->height == 720) {
966             if (!interlaced) {
967                 if      (rate == 24) tag = MKTAG('x','d','5','4');
968                 else if (rate == 25) tag = MKTAG('x','d','5','5');
969                 else if (rate == 30) tag = MKTAG('x','d','5','1');
970                 else if (rate == 50) tag = MKTAG('x','d','5','a');
971                 else if (rate == 60) tag = MKTAG('x','d','5','9');
972             }
973         } else if (track->enc->width == 1920 && track->enc->height == 1080) {
974             if (!interlaced) {
975                 if      (rate == 24) tag = MKTAG('x','d','5','d');
976                 else if (rate == 25) tag = MKTAG('x','d','5','e');
977                 else if (rate == 30) tag = MKTAG('x','d','5','f');
978             } else {
979                 if      (rate == 25) tag = MKTAG('x','d','5','c');
980                 else if (rate == 30) tag = MKTAG('x','d','5','b');
981             }
982         }
983     }
984
985     return tag;
986 }
987
988 static const struct {
989     enum AVPixelFormat pix_fmt;
990     uint32_t tag;
991     unsigned bps;
992 } mov_pix_fmt_tags[] = {
993     { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'),  0 },
994     { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
995     { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
996     { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
997     { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
998     { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
999     { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1000     { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1001     { AV_PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
1002     { AV_PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
1003     { AV_PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
1004     { AV_PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
1005     { AV_PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
1006     { AV_PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
1007     { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1008 };
1009
1010 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1011 {
1012     int tag = track->enc->codec_tag;
1013     int i;
1014     enum AVPixelFormat pix_fmt;
1015
1016     for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1017         if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
1018             tag = mov_pix_fmt_tags[i].tag;
1019             track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1020             if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
1021                 break;
1022         }
1023     }
1024
1025     pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1026                                   track->enc->bits_per_coded_sample);
1027     if (tag == MKTAG('r','a','w',' ') &&
1028         track->enc->pix_fmt != pix_fmt &&
1029         track->enc->pix_fmt != AV_PIX_FMT_NONE)
1030         av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1031                av_get_pix_fmt_name(track->enc->pix_fmt));
1032     return tag;
1033 }
1034
1035 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1036 {
1037     int tag = track->enc->codec_tag;
1038
1039     if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1040                  (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
1041                   track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
1042                   track->enc->codec_id == AV_CODEC_ID_H263 ||
1043                   track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1044                   av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
1045         if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
1046             tag = mov_get_dv_codec_tag(s, track);
1047         else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
1048             tag = mov_get_rawvideo_codec_tag(s, track);
1049         else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1050             tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1051         else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1052             tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
1053             if (!tag) { // if no mac fcc found, try with Microsoft tags
1054                 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
1055                 if (tag)
1056                     av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1057                            "the file may be unplayable!\n");
1058             }
1059         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1060             tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
1061             if (!tag) { // if no mac fcc found, try with Microsoft tags
1062                 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
1063                 if (ms_tag) {
1064                     tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1065                     av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1066                            "the file may be unplayable!\n");
1067                 }
1068             }
1069         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1070             tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
1071     }
1072
1073     return tag;
1074 }
1075
1076 static const AVCodecTag codec_3gp_tags[] = {
1077     { AV_CODEC_ID_H263,     MKTAG('s','2','6','3') },
1078     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
1079     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
1080     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
1081     { AV_CODEC_ID_AMR_NB,   MKTAG('s','a','m','r') },
1082     { AV_CODEC_ID_AMR_WB,   MKTAG('s','a','w','b') },
1083     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1084     { AV_CODEC_ID_NONE, 0 },
1085 };
1086
1087 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1088     { AV_CODEC_ID_MP3,    MKTAG('.','m','p','3') },
1089     { AV_CODEC_ID_AAC,    MKTAG('m','p','4','a') },
1090     { AV_CODEC_ID_H264,   MKTAG('a','v','c','1') },
1091     { AV_CODEC_ID_VP6A,   MKTAG('V','P','6','A') },
1092     { AV_CODEC_ID_VP6F,   MKTAG('V','P','6','F') },
1093     { AV_CODEC_ID_NONE, 0 },
1094 };
1095
1096 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1097 {
1098     int tag;
1099
1100     if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1101         tag = mp4_get_codec_tag(s, track);
1102     else if (track->mode == MODE_ISM) {
1103         tag = mp4_get_codec_tag(s, track);
1104         if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
1105             tag = MKTAG('w', 'm', 'a', ' ');
1106     } else if (track->mode == MODE_IPOD)
1107         tag = ipod_get_codec_tag(s, track);
1108     else if (track->mode & MODE_3GP)
1109         tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
1110     else if (track->mode == MODE_F4V)
1111         tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
1112     else
1113         tag = mov_get_codec_tag(s, track);
1114
1115     return tag;
1116 }
1117
1118 /** Write uuid atom.
1119  * Needed to make file play in iPods running newest firmware
1120  * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1121  */
1122 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1123 {
1124     avio_wb32(pb, 28);
1125     ffio_wfourcc(pb, "uuid");
1126     avio_wb32(pb, 0x6b6840f2);
1127     avio_wb32(pb, 0x5f244fc5);
1128     avio_wb32(pb, 0xba39a51b);
1129     avio_wb32(pb, 0xcf0323f3);
1130     avio_wb32(pb, 0x0);
1131     return 28;
1132 }
1133
1134 static const uint16_t fiel_data[] = {
1135     0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1136 };
1137
1138 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
1139 {
1140     unsigned mov_field_order = 0;
1141     if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
1142         mov_field_order = fiel_data[track->enc->field_order];
1143     else
1144         return 0;
1145     avio_wb32(pb, 10);
1146     ffio_wfourcc(pb, "fiel");
1147     avio_wb16(pb, mov_field_order);
1148     return 10;
1149 }
1150
1151 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1152 {
1153     int64_t pos = avio_tell(pb);
1154     avio_wb32(pb, 0);    /* size */
1155     avio_wl32(pb, track->tag); // store it byteswapped
1156     avio_wb32(pb, 0);    /* Reserved */
1157     avio_wb16(pb, 0);    /* Reserved */
1158     avio_wb16(pb, 1);    /* Data-reference index */
1159
1160     if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1161         mov_write_esds_tag(pb, track);
1162     else if (track->enc->extradata_size)
1163         avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1164
1165     return update_size(pb, pos);
1166 }
1167
1168 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1169 {
1170     AVRational sar;
1171     av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
1172               track->enc->sample_aspect_ratio.den, INT_MAX);
1173
1174     avio_wb32(pb, 16);
1175     ffio_wfourcc(pb, "pasp");
1176     avio_wb32(pb, sar.num);
1177     avio_wb32(pb, sar.den);
1178     return 16;
1179 }
1180
1181 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1182 {
1183     int xdcam_res =  (track->enc->width == 1280 && track->enc->height == 720)
1184                   || (track->enc->width == 1440 && track->enc->height == 1080)
1185                   || (track->enc->width == 1920 && track->enc->height == 1080);
1186
1187     if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name) {
1188         av_strlcpy(compressor_name, track->enc->codec->name, 32);
1189     } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1190         int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1191         AVStream *st = track->st;
1192         int rate = av_q2d(find_fps(NULL, st));
1193         av_strlcatf(compressor_name, len, "XDCAM");
1194         if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1195             av_strlcatf(compressor_name, len, " HD422");
1196         } else if(track->enc->width == 1440) {
1197             av_strlcatf(compressor_name, len, " HD");
1198         } else
1199             av_strlcatf(compressor_name, len, " EX");
1200
1201         av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
1202
1203         av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1204     }
1205 }
1206
1207 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1208 {
1209     int64_t pos = avio_tell(pb);
1210     char compressor_name[32] = { 0 };
1211
1212     avio_wb32(pb, 0); /* size */
1213     avio_wl32(pb, track->tag); // store it byteswapped
1214     avio_wb32(pb, 0); /* Reserved */
1215     avio_wb16(pb, 0); /* Reserved */
1216     avio_wb16(pb, 1); /* Data-reference index */
1217
1218     avio_wb16(pb, 0); /* Codec stream version */
1219     avio_wb16(pb, 0); /* Codec stream revision (=0) */
1220     if (track->mode == MODE_MOV) {
1221         ffio_wfourcc(pb, "FFMP"); /* Vendor */
1222         if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
1223             avio_wb32(pb, 0); /* Temporal Quality */
1224             avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1225         } else {
1226             avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1227             avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1228         }
1229     } else {
1230         avio_wb32(pb, 0); /* Reserved */
1231         avio_wb32(pb, 0); /* Reserved */
1232         avio_wb32(pb, 0); /* Reserved */
1233     }
1234     avio_wb16(pb, track->enc->width); /* Video width */
1235     avio_wb16(pb, track->height); /* Video height */
1236     avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1237     avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1238     avio_wb32(pb, 0); /* Data size (= 0) */
1239     avio_wb16(pb, 1); /* Frame count (= 1) */
1240
1241     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1242     find_compressor(compressor_name, 32, track);
1243     avio_w8(pb, strlen(compressor_name));
1244     avio_write(pb, compressor_name, 31);
1245
1246     if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1247         avio_wb16(pb, track->enc->bits_per_coded_sample);
1248     else
1249         avio_wb16(pb, 0x18); /* Reserved */
1250     avio_wb16(pb, 0xffff); /* Reserved */
1251     if (track->tag == MKTAG('m','p','4','v'))
1252         mov_write_esds_tag(pb, track);
1253     else if (track->enc->codec_id == AV_CODEC_ID_H263)
1254         mov_write_d263_tag(pb);
1255     else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
1256             track->enc->codec_id == AV_CODEC_ID_SVQ3) {
1257         mov_write_extradata_tag(pb, track);
1258         avio_wb32(pb, 0);
1259     } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
1260         mov_write_avid_tag(pb, track);
1261     else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
1262         mov_write_hvcc_tag(pb, track);
1263     else if (track->enc->codec_id == AV_CODEC_ID_H264) {
1264         mov_write_avcc_tag(pb, track);
1265         if (track->mode == MODE_IPOD)
1266             mov_write_uuid_tag_ipod(pb);
1267     } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1268         mov_write_dvc1_tag(pb, track);
1269     else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
1270              track->enc->codec_id == AV_CODEC_ID_VP6A) {
1271         /* Don't write any potential extradata here - the cropping
1272          * is signalled via the normal width/height fields. */
1273     } else if (track->vos_len > 0)
1274         mov_write_glbl_tag(pb, track);
1275
1276     if (track->enc->codec_id != AV_CODEC_ID_H264 &&
1277         track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
1278         track->enc->codec_id != AV_CODEC_ID_DNXHD)
1279         if (track->enc->field_order != AV_FIELD_UNKNOWN)
1280             mov_write_fiel_tag(pb, track);
1281
1282     if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1283         track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1284         mov_write_pasp_tag(pb, track);
1285     }
1286
1287     return update_size(pb, pos);
1288 }
1289
1290 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1291 {
1292     int64_t pos = avio_tell(pb);
1293     avio_wb32(pb, 0); /* size */
1294     ffio_wfourcc(pb, "rtp ");
1295     avio_wb32(pb, 0); /* Reserved */
1296     avio_wb16(pb, 0); /* Reserved */
1297     avio_wb16(pb, 1); /* Data-reference index */
1298
1299     avio_wb16(pb, 1); /* Hint track version */
1300     avio_wb16(pb, 1); /* Highest compatible version */
1301     avio_wb32(pb, track->max_packet_size); /* Max packet size */
1302
1303     avio_wb32(pb, 12); /* size */
1304     ffio_wfourcc(pb, "tims");
1305     avio_wb32(pb, track->timescale);
1306
1307     return update_size(pb, pos);
1308 }
1309
1310 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1311 {
1312     int64_t pos = avio_tell(pb);
1313 #if 1
1314     int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
1315     int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
1316
1317     if (nb_frames > 255) {
1318         av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1319         return AVERROR(EINVAL);
1320     }
1321
1322     avio_wb32(pb, 0); /* size */
1323     ffio_wfourcc(pb, "tmcd");               /* Data format */
1324     avio_wb32(pb, 0);                       /* Reserved */
1325     avio_wb32(pb, 1);                       /* Data reference index */
1326     avio_wb32(pb, 0);                       /* Flags */
1327     avio_wb32(pb, track->timecode_flags);   /* Flags (timecode) */
1328     avio_wb32(pb, track->timescale);        /* Timescale */
1329     avio_wb32(pb, frame_duration);          /* Frame duration */
1330     avio_w8(pb, nb_frames);                 /* Number of frames */
1331     avio_wb24(pb, 0);                       /* Reserved */
1332     /* TODO: source reference string */
1333 #else
1334
1335     avio_wb32(pb, 0); /* size */
1336     ffio_wfourcc(pb, "tmcd");               /* Data format */
1337     avio_wb32(pb, 0);                       /* Reserved */
1338     avio_wb32(pb, 1);                       /* Data reference index */
1339     if (track->enc->extradata_size)
1340         avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1341 #endif
1342     return update_size(pb, pos);
1343 }
1344
1345 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
1346 {
1347     int64_t pos = avio_tell(pb);
1348     avio_wb32(pb, 0); /* size */
1349     ffio_wfourcc(pb, "stsd");
1350     avio_wb32(pb, 0); /* version & flags */
1351     avio_wb32(pb, 1); /* entry count */
1352     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1353         mov_write_video_tag(pb, track);
1354     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1355         mov_write_audio_tag(pb, track);
1356     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1357         mov_write_subtitle_tag(pb, track);
1358     else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1359         mov_write_rtp_tag(pb, track);
1360     else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1361         mov_write_tmcd_tag(pb, track);
1362     return update_size(pb, pos);
1363 }
1364
1365 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1366 {
1367     MOVStts *ctts_entries;
1368     uint32_t entries = 0;
1369     uint32_t atom_size;
1370     int i;
1371
1372     ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
1373     ctts_entries[0].count = 1;
1374     ctts_entries[0].duration = track->cluster[0].cts;
1375     for (i = 1; i < track->entry; i++) {
1376         if (track->cluster[i].cts == ctts_entries[entries].duration) {
1377             ctts_entries[entries].count++; /* compress */
1378         } else {
1379             entries++;
1380             ctts_entries[entries].duration = track->cluster[i].cts;
1381             ctts_entries[entries].count = 1;
1382         }
1383     }
1384     entries++; /* last one */
1385     atom_size = 16 + (entries * 8);
1386     avio_wb32(pb, atom_size); /* size */
1387     ffio_wfourcc(pb, "ctts");
1388     avio_wb32(pb, 0); /* version & flags */
1389     avio_wb32(pb, entries); /* entry count */
1390     for (i = 0; i < entries; i++) {
1391         avio_wb32(pb, ctts_entries[i].count);
1392         avio_wb32(pb, ctts_entries[i].duration);
1393     }
1394     av_free(ctts_entries);
1395     return atom_size;
1396 }
1397
1398 /* Time to sample atom */
1399 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1400 {
1401     MOVStts *stts_entries;
1402     uint32_t entries = -1;
1403     uint32_t atom_size;
1404     int i;
1405
1406     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1407         stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1408         stts_entries[0].count = track->sample_count;
1409         stts_entries[0].duration = 1;
1410         entries = 1;
1411     } else {
1412         stts_entries = track->entry ?
1413                        av_malloc(track->entry * sizeof(*stts_entries)) : /* worst case */
1414                        NULL;
1415         for (i = 0; i < track->entry; i++) {
1416             int duration = get_cluster_duration(track, i);
1417             if (i && duration == stts_entries[entries].duration) {
1418                 stts_entries[entries].count++; /* compress */
1419             } else {
1420                 entries++;
1421                 stts_entries[entries].duration = duration;
1422                 stts_entries[entries].count = 1;
1423             }
1424         }
1425         entries++; /* last one */
1426     }
1427     atom_size = 16 + (entries * 8);
1428     avio_wb32(pb, atom_size); /* size */
1429     ffio_wfourcc(pb, "stts");
1430     avio_wb32(pb, 0); /* version & flags */
1431     avio_wb32(pb, entries); /* entry count */
1432     for (i = 0; i < entries; i++) {
1433         avio_wb32(pb, stts_entries[i].count);
1434         avio_wb32(pb, stts_entries[i].duration);
1435     }
1436     av_free(stts_entries);
1437     return atom_size;
1438 }
1439
1440 static int mov_write_dref_tag(AVIOContext *pb)
1441 {
1442     avio_wb32(pb, 28); /* size */
1443     ffio_wfourcc(pb, "dref");
1444     avio_wb32(pb, 0); /* version & flags */
1445     avio_wb32(pb, 1); /* entry count */
1446
1447     avio_wb32(pb, 0xc); /* size */
1448     //FIXME add the alis and rsrc atom
1449     ffio_wfourcc(pb, "url ");
1450     avio_wb32(pb, 1); /* version & flags */
1451
1452     return 28;
1453 }
1454
1455 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1456 {
1457     int64_t pos = avio_tell(pb);
1458     avio_wb32(pb, 0); /* size */
1459     ffio_wfourcc(pb, "stbl");
1460     mov_write_stsd_tag(pb, track);
1461     mov_write_stts_tag(pb, track);
1462     if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1463          track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1464         track->has_keyframes && track->has_keyframes < track->entry)
1465         mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1466     if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1467         mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1468     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1469         track->flags & MOV_TRACK_CTTS)
1470         mov_write_ctts_tag(pb, track);
1471     mov_write_stsc_tag(pb, track);
1472     mov_write_stsz_tag(pb, track);
1473     mov_write_stco_tag(pb, track);
1474     return update_size(pb, pos);
1475 }
1476
1477 static int mov_write_dinf_tag(AVIOContext *pb)
1478 {
1479     int64_t pos = avio_tell(pb);
1480     avio_wb32(pb, 0); /* size */
1481     ffio_wfourcc(pb, "dinf");
1482     mov_write_dref_tag(pb);
1483     return update_size(pb, pos);
1484 }
1485
1486 static int mov_write_nmhd_tag(AVIOContext *pb)
1487 {
1488     avio_wb32(pb, 12);
1489     ffio_wfourcc(pb, "nmhd");
1490     avio_wb32(pb, 0);
1491     return 12;
1492 }
1493
1494 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
1495 {
1496     int64_t pos = avio_tell(pb);
1497     const char *font = "Lucida Grande";
1498     avio_wb32(pb, 0);                   /* size */
1499     ffio_wfourcc(pb, "tcmi");           /* timecode media information atom */
1500     avio_wb32(pb, 0);                   /* version & flags */
1501     avio_wb16(pb, 0);                   /* text font */
1502     avio_wb16(pb, 0);                   /* text face */
1503     avio_wb16(pb, 12);                  /* text size */
1504     avio_wb16(pb, 0);                   /* (unknown, not in the QT specs...) */
1505     avio_wb16(pb, 0x0000);              /* text color (red) */
1506     avio_wb16(pb, 0x0000);              /* text color (green) */
1507     avio_wb16(pb, 0x0000);              /* text color (blue) */
1508     avio_wb16(pb, 0xffff);              /* background color (red) */
1509     avio_wb16(pb, 0xffff);              /* background color (green) */
1510     avio_wb16(pb, 0xffff);              /* background color (blue) */
1511     avio_w8(pb, strlen(font));          /* font len (part of the pascal string) */
1512     avio_write(pb, font, strlen(font)); /* font name */
1513     return update_size(pb, pos);
1514 }
1515
1516 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
1517 {
1518     int64_t pos = avio_tell(pb);
1519     avio_wb32(pb, 0);      /* size */
1520     ffio_wfourcc(pb, "gmhd");
1521     avio_wb32(pb, 0x18);   /* gmin size */
1522     ffio_wfourcc(pb, "gmin");/* generic media info */
1523     avio_wb32(pb, 0);      /* version & flags */
1524     avio_wb16(pb, 0x40);   /* graphics mode = */
1525     avio_wb16(pb, 0x8000); /* opColor (r?) */
1526     avio_wb16(pb, 0x8000); /* opColor (g?) */
1527     avio_wb16(pb, 0x8000); /* opColor (b?) */
1528     avio_wb16(pb, 0);      /* balance */
1529     avio_wb16(pb, 0);      /* reserved */
1530
1531     /*
1532      * This special text atom is required for
1533      * Apple Quicktime chapters. The contents
1534      * don't appear to be documented, so the
1535      * bytes are copied verbatim.
1536      */
1537     if (track->tag != MKTAG('c','6','0','8')) {
1538     avio_wb32(pb, 0x2C);   /* size */
1539     ffio_wfourcc(pb, "text");
1540     avio_wb16(pb, 0x01);
1541     avio_wb32(pb, 0x00);
1542     avio_wb32(pb, 0x00);
1543     avio_wb32(pb, 0x00);
1544     avio_wb32(pb, 0x01);
1545     avio_wb32(pb, 0x00);
1546     avio_wb32(pb, 0x00);
1547     avio_wb32(pb, 0x00);
1548     avio_wb32(pb, 0x00004000);
1549     avio_wb16(pb, 0x0000);
1550     }
1551
1552     if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1553         int64_t tmcd_pos = avio_tell(pb);
1554         avio_wb32(pb, 0); /* size */
1555         ffio_wfourcc(pb, "tmcd");
1556         mov_write_tcmi_tag(pb, track);
1557         update_size(pb, tmcd_pos);
1558     }
1559     return update_size(pb, pos);
1560 }
1561
1562 static int mov_write_smhd_tag(AVIOContext *pb)
1563 {
1564     avio_wb32(pb, 16); /* size */
1565     ffio_wfourcc(pb, "smhd");
1566     avio_wb32(pb, 0); /* version & flags */
1567     avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1568     avio_wb16(pb, 0); /* reserved */
1569     return 16;
1570 }
1571
1572 static int mov_write_vmhd_tag(AVIOContext *pb)
1573 {
1574     avio_wb32(pb, 0x14); /* size (always 0x14) */
1575     ffio_wfourcc(pb, "vmhd");
1576     avio_wb32(pb, 0x01); /* version & flags */
1577     avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1578     return 0x14;
1579 }
1580
1581 static int is_clcp_track(MOVTrack *track)
1582 {
1583     return track->tag == MKTAG('c','7','0','8') ||
1584            track->tag == MKTAG('c','6','0','8');
1585 }
1586
1587 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1588 {
1589     const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1590     int64_t pos = avio_tell(pb);
1591
1592     hdlr      = "dhlr";
1593     hdlr_type = "url ";
1594     descr     = "DataHandler";
1595
1596     if (track) {
1597         hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1598         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1599             hdlr_type = "vide";
1600             descr     = "VideoHandler";
1601         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1602             hdlr_type = "soun";
1603             descr     = "SoundHandler";
1604         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1605             if (is_clcp_track(track)) {
1606                 hdlr_type = "clcp";
1607                 descr = "ClosedCaptionHandler";
1608             } else {
1609                 if (track->tag == MKTAG('t','x','3','g')) {
1610                     hdlr_type = "sbtl";
1611                 } else if (track->tag == MKTAG('m','p','4','s')) {
1612                     hdlr_type = "subp";
1613                 } else {
1614                     hdlr_type = "text";
1615                 }
1616             descr = "SubtitleHandler";
1617             }
1618         } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1619             hdlr_type = "hint";
1620             descr     = "HintHandler";
1621         } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1622             hdlr_type = "tmcd";
1623             descr = "TimeCodeHandler";
1624         } else {
1625             char tag_buf[32];
1626             av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
1627                                     track->enc->codec_tag);
1628
1629             av_log(track->enc, AV_LOG_WARNING,
1630                    "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
1631                    tag_buf, track->enc->codec_tag);
1632         }
1633     }
1634
1635     avio_wb32(pb, 0); /* size */
1636     ffio_wfourcc(pb, "hdlr");
1637     avio_wb32(pb, 0); /* Version & flags */
1638     avio_write(pb, hdlr, 4); /* handler */
1639     ffio_wfourcc(pb, hdlr_type); /* handler type */
1640     avio_wb32(pb, 0); /* reserved */
1641     avio_wb32(pb, 0); /* reserved */
1642     avio_wb32(pb, 0); /* reserved */
1643     if (!track || track->mode == MODE_MOV)
1644         avio_w8(pb, strlen(descr)); /* pascal string */
1645     avio_write(pb, descr, strlen(descr)); /* handler description */
1646     if (track && track->mode != MODE_MOV)
1647         avio_w8(pb, 0); /* c string */
1648     return update_size(pb, pos);
1649 }
1650
1651 static int mov_write_hmhd_tag(AVIOContext *pb)
1652 {
1653     /* This atom must be present, but leaving the values at zero
1654      * seems harmless. */
1655     avio_wb32(pb, 28); /* size */
1656     ffio_wfourcc(pb, "hmhd");
1657     avio_wb32(pb, 0); /* version, flags */
1658     avio_wb16(pb, 0); /* maxPDUsize */
1659     avio_wb16(pb, 0); /* avgPDUsize */
1660     avio_wb32(pb, 0); /* maxbitrate */
1661     avio_wb32(pb, 0); /* avgbitrate */
1662     avio_wb32(pb, 0); /* reserved */
1663     return 28;
1664 }
1665
1666 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1667 {
1668     int64_t pos = avio_tell(pb);
1669     avio_wb32(pb, 0); /* size */
1670     ffio_wfourcc(pb, "minf");
1671     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1672         mov_write_vmhd_tag(pb);
1673     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1674         mov_write_smhd_tag(pb);
1675     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1676         if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
1677             mov_write_gmhd_tag(pb, track);
1678         } else {
1679             mov_write_nmhd_tag(pb);
1680         }
1681     } else if (track->tag == MKTAG('r','t','p',' ')) {
1682         mov_write_hmhd_tag(pb);
1683     } else if (track->tag == MKTAG('t','m','c','d')) {
1684         mov_write_gmhd_tag(pb, track);
1685     }
1686     if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1687         mov_write_hdlr_tag(pb, NULL);
1688     mov_write_dinf_tag(pb);
1689     mov_write_stbl_tag(pb, track);
1690     return update_size(pb, pos);
1691 }
1692
1693 static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1694 {
1695     int version = track->track_duration < INT32_MAX ? 0 : 1;
1696
1697     if (track->mode == MODE_ISM)
1698         version = 1;
1699
1700     (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1701     ffio_wfourcc(pb, "mdhd");
1702     avio_w8(pb, version);
1703     avio_wb24(pb, 0); /* flags */
1704     if (version == 1) {
1705         avio_wb64(pb, track->time);
1706         avio_wb64(pb, track->time);
1707     } else {
1708         avio_wb32(pb, track->time); /* creation time */
1709         avio_wb32(pb, track->time); /* modification time */
1710     }
1711     avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1712     if (!track->entry)
1713         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1714     else
1715         (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
1716     avio_wb16(pb, track->language); /* language */
1717     avio_wb16(pb, 0); /* reserved (quality) */
1718
1719     if (version != 0 && track->mode == MODE_MOV) {
1720         av_log(NULL, AV_LOG_ERROR,
1721                "FATAL error, file duration too long for timebase, this file will not be\n"
1722                "playable with quicktime. Choose a different timebase or a different\n"
1723                "container format\n");
1724     }
1725
1726     return 32;
1727 }
1728
1729 static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1730 {
1731     int64_t pos = avio_tell(pb);
1732     avio_wb32(pb, 0); /* size */
1733     ffio_wfourcc(pb, "mdia");
1734     mov_write_mdhd_tag(pb, track);
1735     mov_write_hdlr_tag(pb, track);
1736     mov_write_minf_tag(pb, track);
1737     return update_size(pb, pos);
1738 }
1739
1740 /* transformation matrix
1741      |a  b  u|
1742      |c  d  v|
1743      |tx ty w| */
1744 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
1745                          int16_t d, int16_t tx, int16_t ty)
1746 {
1747     avio_wb32(pb, a << 16);  /* 16.16 format */
1748     avio_wb32(pb, b << 16);  /* 16.16 format */
1749     avio_wb32(pb, 0);        /* u in 2.30 format */
1750     avio_wb32(pb, c << 16);  /* 16.16 format */
1751     avio_wb32(pb, d << 16);  /* 16.16 format */
1752     avio_wb32(pb, 0);        /* v in 2.30 format */
1753     avio_wb32(pb, tx << 16); /* 16.16 format */
1754     avio_wb32(pb, ty << 16); /* 16.16 format */
1755     avio_wb32(pb, 1 << 30);  /* w in 2.30 format */
1756 }
1757
1758 static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1759 {
1760     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1761                                       track->timescale, AV_ROUND_UP);
1762     int version = duration < INT32_MAX ? 0 : 1;
1763     int rotation = 0;
1764
1765     if (track->mode == MODE_ISM)
1766         version = 1;
1767
1768     (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1769     ffio_wfourcc(pb, "tkhd");
1770     avio_w8(pb, version);
1771     avio_wb24(pb, (track->flags & MOV_TRACK_ENABLED) ?
1772                   MOV_TKHD_FLAG_ENABLED | MOV_TKHD_FLAG_IN_MOVIE :
1773                   MOV_TKHD_FLAG_IN_MOVIE);
1774     if (version == 1) {
1775         avio_wb64(pb, track->time);
1776         avio_wb64(pb, track->time);
1777     } else {
1778         avio_wb32(pb, track->time); /* creation time */
1779         avio_wb32(pb, track->time); /* modification time */
1780     }
1781     avio_wb32(pb, track->track_id); /* track-id */
1782     avio_wb32(pb, 0); /* reserved */
1783     if (!track->entry)
1784         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1785     else
1786         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1787
1788     avio_wb32(pb, 0); /* reserved */
1789     avio_wb32(pb, 0); /* reserved */
1790     avio_wb16(pb, 0); /* layer */
1791     avio_wb16(pb, st ? st->codec->codec_type : 0); /* alternate group) */
1792     /* Volume, only for audio */
1793     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1794         avio_wb16(pb, 0x0100);
1795     else
1796         avio_wb16(pb, 0);
1797     avio_wb16(pb, 0); /* reserved */
1798
1799     /* Matrix structure */
1800     if (st && st->metadata) {
1801         AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
1802         rotation = (rot && rot->value) ? atoi(rot->value) : 0;
1803     }
1804     if (rotation == 90) {
1805         write_matrix(pb,  0,  1, -1,  0, track->enc->height, 0);
1806     } else if (rotation == 180) {
1807         write_matrix(pb, -1,  0,  0, -1, track->enc->width, track->enc->height);
1808     } else if (rotation == 270) {
1809         write_matrix(pb,  0, -1,  1,  0, 0, track->enc->width);
1810     } else {
1811         write_matrix(pb,  1,  0,  0,  1, 0, 0);
1812     }
1813     /* Track width and height, for visual only */
1814     if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1815                track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1816         if (track->mode == MODE_MOV) {
1817             avio_wb32(pb, track->enc->width << 16);
1818             avio_wb32(pb, track->height << 16);
1819         } else {
1820             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1821             if (!sample_aspect_ratio || track->height != track->enc->height)
1822                 sample_aspect_ratio = 1;
1823             avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
1824             avio_wb32(pb, track->height * 0x10000);
1825         }
1826     } else {
1827         avio_wb32(pb, 0);
1828         avio_wb32(pb, 0);
1829     }
1830     return 0x5c;
1831 }
1832
1833 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1834 {
1835     int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1836                                track->enc->sample_aspect_ratio.den);
1837
1838     int64_t pos = avio_tell(pb);
1839
1840     avio_wb32(pb, 0); /* size */
1841     ffio_wfourcc(pb, "tapt");
1842
1843     avio_wb32(pb, 20);
1844     ffio_wfourcc(pb, "clef");
1845     avio_wb32(pb, 0);
1846     avio_wb32(pb, width << 16);
1847     avio_wb32(pb, track->enc->height << 16);
1848
1849     avio_wb32(pb, 20);
1850     ffio_wfourcc(pb, "prof");
1851     avio_wb32(pb, 0);
1852     avio_wb32(pb, width << 16);
1853     avio_wb32(pb, track->enc->height << 16);
1854
1855     avio_wb32(pb, 20);
1856     ffio_wfourcc(pb, "enof");
1857     avio_wb32(pb, 0);
1858     avio_wb32(pb, track->enc->width << 16);
1859     avio_wb32(pb, track->enc->height << 16);
1860
1861     return update_size(pb, pos);
1862 }
1863
1864 // This box seems important for the psp playback ... without it the movie seems to hang
1865 static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1866 {
1867     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1868                                       track->timescale, AV_ROUND_UP);
1869     int version = duration < INT32_MAX ? 0 : 1;
1870     int entry_size, entry_count, size;
1871     int64_t delay, start_ct = track->cluster[0].cts;
1872     delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
1873                            track->timescale, AV_ROUND_DOWN);
1874     version |= delay < INT32_MAX ? 0 : 1;
1875
1876     entry_size = (version == 1) ? 20 : 12;
1877     entry_count = 1 + (delay > 0);
1878     size = 24 + entry_count * entry_size;
1879
1880     /* write the atom data */
1881     avio_wb32(pb, size);
1882     ffio_wfourcc(pb, "edts");
1883     avio_wb32(pb, size - 8);
1884     ffio_wfourcc(pb, "elst");
1885     avio_w8(pb, version);
1886     avio_wb24(pb, 0); /* flags */
1887
1888     avio_wb32(pb, entry_count);
1889     if (delay > 0) { /* add an empty edit to delay presentation */
1890         if (version == 1) {
1891             avio_wb64(pb, delay);
1892             avio_wb64(pb, -1);
1893         } else {
1894             avio_wb32(pb, delay);
1895             avio_wb32(pb, -1);
1896         }
1897         avio_wb32(pb, 0x00010000);
1898     } else {
1899         av_assert0(av_rescale_rnd(track->cluster[0].dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
1900         start_ct  = -FFMIN(track->cluster[0].dts, 0); //FFMIN needed due to rounding
1901         duration += delay;
1902     }
1903
1904     /* duration */
1905     if (version == 1) {
1906         avio_wb64(pb, duration);
1907         avio_wb64(pb, start_ct);
1908     } else {
1909         avio_wb32(pb, duration);
1910         avio_wb32(pb, start_ct);
1911     }
1912     avio_wb32(pb, 0x00010000);
1913     return size;
1914 }
1915
1916 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1917 {
1918     avio_wb32(pb, 20);   // size
1919     ffio_wfourcc(pb, "tref");
1920     avio_wb32(pb, 12);   // size (subatom)
1921     avio_wl32(pb, track->tref_tag);
1922     avio_wb32(pb, track->tref_id);
1923     return 20;
1924 }
1925
1926 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1927 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1928 {
1929     avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1930     ffio_wfourcc(pb, "uuid");
1931     ffio_wfourcc(pb, "USMT");
1932     avio_wb32(pb, 0x21d24fce);
1933     avio_wb32(pb, 0xbb88695c);
1934     avio_wb32(pb, 0xfac9c740);
1935     avio_wb32(pb, 0x1c);     // another size here!
1936     ffio_wfourcc(pb, "MTDT");
1937     avio_wb32(pb, 0x00010012);
1938     avio_wb32(pb, 0x0a);
1939     avio_wb32(pb, 0x55c40000);
1940     avio_wb32(pb, 0x1);
1941     avio_wb32(pb, 0x0);
1942     return 0x34;
1943 }
1944
1945 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
1946 {
1947     AVFormatContext *ctx = track->rtp_ctx;
1948     char buf[1000] = "";
1949     int len;
1950
1951     ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
1952                        NULL, NULL, 0, 0, ctx);
1953     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
1954     len = strlen(buf);
1955
1956     avio_wb32(pb, len + 24);
1957     ffio_wfourcc(pb, "udta");
1958     avio_wb32(pb, len + 16);
1959     ffio_wfourcc(pb, "hnti");
1960     avio_wb32(pb, len + 8);
1961     ffio_wfourcc(pb, "sdp ");
1962     avio_write(pb, buf, len);
1963     return len + 24;
1964 }
1965
1966 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
1967                               MOVTrack *track, AVStream *st)
1968 {
1969     int64_t pos = avio_tell(pb);
1970     avio_wb32(pb, 0); /* size */
1971     ffio_wfourcc(pb, "trak");
1972     mov_write_tkhd_tag(pb, track, st);
1973     if (supports_edts(mov))
1974         mov_write_edts_tag(pb, track);  // PSP Movies and several other cases require edts box
1975     if (track->tref_tag)
1976         mov_write_tref_tag(pb, track);
1977     mov_write_mdia_tag(pb, track);
1978     if (track->mode == MODE_PSP)
1979         mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
1980     if (track->tag == MKTAG('r','t','p',' '))
1981         mov_write_udta_sdp(pb, track);
1982     if (track->mode == MODE_MOV) {
1983         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1984             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1985             if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
1986                 mov_write_tapt_tag(pb, track);
1987             }
1988         }
1989         if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
1990             mov_write_tapt_tag(pb, track);
1991         }
1992     }
1993     return update_size(pb, pos);
1994 }
1995
1996 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1997 {
1998     int i, has_audio = 0, has_video = 0;
1999     int64_t pos = avio_tell(pb);
2000     int audio_profile = mov->iods_audio_profile;
2001     int video_profile = mov->iods_video_profile;
2002     for (i = 0; i < mov->nb_streams; i++) {
2003         if (mov->tracks[i].entry > 0) {
2004             has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
2005             has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
2006         }
2007     }
2008     if (audio_profile < 0)
2009         audio_profile = 0xFF - has_audio;
2010     if (video_profile < 0)
2011         video_profile = 0xFF - has_video;
2012     avio_wb32(pb, 0x0); /* size */
2013     ffio_wfourcc(pb, "iods");
2014     avio_wb32(pb, 0);    /* version & flags */
2015     put_descr(pb, 0x10, 7);
2016     avio_wb16(pb, 0x004f);
2017     avio_w8(pb, 0xff);
2018     avio_w8(pb, 0xff);
2019     avio_w8(pb, audio_profile);
2020     avio_w8(pb, video_profile);
2021     avio_w8(pb, 0xff);
2022     return update_size(pb, pos);
2023 }
2024
2025 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2026 {
2027     avio_wb32(pb, 0x20); /* size */
2028     ffio_wfourcc(pb, "trex");
2029     avio_wb32(pb, 0);   /* version & flags */
2030     avio_wb32(pb, track->track_id); /* track ID */
2031     avio_wb32(pb, 1);   /* default sample description index */
2032     avio_wb32(pb, 0);   /* default sample duration */
2033     avio_wb32(pb, 0);   /* default sample size */
2034     avio_wb32(pb, 0);   /* default sample flags */
2035     return 0;
2036 }
2037
2038 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2039 {
2040     int64_t pos = avio_tell(pb);
2041     int i;
2042     avio_wb32(pb, 0x0); /* size */
2043     ffio_wfourcc(pb, "mvex");
2044     for (i = 0; i < mov->nb_streams; i++)
2045         mov_write_trex_tag(pb, &mov->tracks[i]);
2046     return update_size(pb, pos);
2047 }
2048
2049 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2050 {
2051     int max_track_id = 1, i;
2052     int64_t max_track_len_temp, max_track_len = 0;
2053     int version;
2054
2055     for (i = 0; i < mov->nb_streams; i++) {
2056         if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2057             max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2058                                                 MOV_TIMESCALE,
2059                                                 mov->tracks[i].timescale,
2060                                                 AV_ROUND_UP);
2061             if (max_track_len < max_track_len_temp)
2062                 max_track_len = max_track_len_temp;
2063             if (max_track_id < mov->tracks[i].track_id)
2064                 max_track_id = mov->tracks[i].track_id;
2065         }
2066     }
2067
2068     version = max_track_len < UINT32_MAX ? 0 : 1;
2069     (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
2070     ffio_wfourcc(pb, "mvhd");
2071     avio_w8(pb, version);
2072     avio_wb24(pb, 0); /* flags */
2073     if (version == 1) {
2074         avio_wb64(pb, mov->time);
2075         avio_wb64(pb, mov->time);
2076     } else {
2077         avio_wb32(pb, mov->time); /* creation time */
2078         avio_wb32(pb, mov->time); /* modification time */
2079     }
2080     avio_wb32(pb, MOV_TIMESCALE);
2081     (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2082
2083     avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2084     avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2085     avio_wb16(pb, 0); /* reserved */
2086     avio_wb32(pb, 0); /* reserved */
2087     avio_wb32(pb, 0); /* reserved */
2088
2089     /* Matrix structure */
2090     write_matrix(pb, 1, 0, 0, 1, 0, 0);
2091
2092     avio_wb32(pb, 0); /* reserved (preview time) */
2093     avio_wb32(pb, 0); /* reserved (preview duration) */
2094     avio_wb32(pb, 0); /* reserved (poster time) */
2095     avio_wb32(pb, 0); /* reserved (selection time) */
2096     avio_wb32(pb, 0); /* reserved (selection duration) */
2097     avio_wb32(pb, 0); /* reserved (current time) */
2098     avio_wb32(pb, max_track_id + 1); /* Next track id */
2099     return 0x6c;
2100 }
2101
2102 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2103                                      AVFormatContext *s)
2104 {
2105     avio_wb32(pb, 33); /* size */
2106     ffio_wfourcc(pb, "hdlr");
2107     avio_wb32(pb, 0);
2108     avio_wb32(pb, 0);
2109     ffio_wfourcc(pb, "mdir");
2110     ffio_wfourcc(pb, "appl");
2111     avio_wb32(pb, 0);
2112     avio_wb32(pb, 0);
2113     avio_w8(pb, 0);
2114     return 33;
2115 }
2116
2117 /* helper function to write a data tag with the specified string as data */
2118 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2119 {
2120     if (long_style) {
2121         int size = 16 + strlen(data);
2122         avio_wb32(pb, size); /* size */
2123         ffio_wfourcc(pb, "data");
2124         avio_wb32(pb, 1);
2125         avio_wb32(pb, 0);
2126         avio_write(pb, data, strlen(data));
2127         return size;
2128     } else {
2129         if (!lang)
2130             lang = ff_mov_iso639_to_lang("und", 1);
2131         avio_wb16(pb, strlen(data)); /* string length */
2132         avio_wb16(pb, lang);
2133         avio_write(pb, data, strlen(data));
2134         return strlen(data) + 4;
2135     }
2136 }
2137
2138 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2139                                 const char *value, int lang, int long_style)
2140 {
2141     int size = 0;
2142     if (value && value[0]) {
2143         int64_t pos = avio_tell(pb);
2144         avio_wb32(pb, 0); /* size */
2145         ffio_wfourcc(pb, name);
2146         mov_write_string_data_tag(pb, value, lang, long_style);
2147         size = update_size(pb, pos);
2148     }
2149     return size;
2150 }
2151
2152 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2153                                      const char *name, const char *tag,
2154                                      int long_style)
2155 {
2156     int l, lang = 0, len, len2;
2157     AVDictionaryEntry *t, *t2 = NULL;
2158     char tag2[16];
2159
2160     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2161         return 0;
2162
2163     len = strlen(t->key);
2164     snprintf(tag2, sizeof(tag2), "%s-", tag);
2165     while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2166         len2 = strlen(t2->key);
2167         if (len2 == len + 4 && !strcmp(t->value, t2->value)
2168             && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2169             lang = l;
2170             break;
2171         }
2172     }
2173     return mov_write_string_tag(pb, name, t->value, lang, long_style);
2174 }
2175
2176 /* iTunes bpm number */
2177 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2178 {
2179     AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2180     int size = 0, tmpo = t ? atoi(t->value) : 0;
2181     if (tmpo) {
2182         size = 26;
2183         avio_wb32(pb, size);
2184         ffio_wfourcc(pb, "tmpo");
2185         avio_wb32(pb, size-8); /* size */
2186         ffio_wfourcc(pb, "data");
2187         avio_wb32(pb, 0x15);  //type specifier
2188         avio_wb32(pb, 0);
2189         avio_wb16(pb, tmpo);        // data
2190     }
2191     return size;
2192 }
2193
2194 /* iTunes track or disc number */
2195 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2196                               AVFormatContext *s, int disc)
2197 {
2198     AVDictionaryEntry *t = av_dict_get(s->metadata,
2199                                        disc ? "disc" : "track",
2200                                        NULL, 0);
2201     int size = 0, track = t ? atoi(t->value) : 0;
2202     if (track) {
2203         int tracks = 0;
2204         char *slash = strchr(t->value, '/');
2205         if (slash)
2206             tracks = atoi(slash + 1);
2207         avio_wb32(pb, 32); /* size */
2208         ffio_wfourcc(pb, disc ? "disk" : "trkn");
2209         avio_wb32(pb, 24); /* size */
2210         ffio_wfourcc(pb, "data");
2211         avio_wb32(pb, 0);        // 8 bytes empty
2212         avio_wb32(pb, 0);
2213         avio_wb16(pb, 0);        // empty
2214         avio_wb16(pb, track);    // track / disc number
2215         avio_wb16(pb, tracks);   // total track / disc number
2216         avio_wb16(pb, 0);        // empty
2217         size = 32;
2218     }
2219     return size;
2220 }
2221
2222 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2223                                    const char *name, const char *tag,
2224                                    int len)
2225 {
2226     AVDictionaryEntry *t = NULL;
2227     uint8_t num;
2228     int size = 24 + len;
2229
2230     if (len != 1 && len != 4)
2231         return -1;
2232
2233     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2234         return 0;
2235     num = atoi(t->value);
2236
2237     avio_wb32(pb, size);
2238     ffio_wfourcc(pb, name);
2239     avio_wb32(pb, size - 8);
2240     ffio_wfourcc(pb, "data");
2241     avio_wb32(pb, 0x15);
2242     avio_wb32(pb, 0);
2243     if (len==4) avio_wb32(pb, num);
2244     else        avio_w8 (pb, num);
2245
2246     return size;
2247 }
2248
2249 /* iTunes meta data list */
2250 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2251                               AVFormatContext *s)
2252 {
2253     int64_t pos = avio_tell(pb);
2254     avio_wb32(pb, 0); /* size */
2255     ffio_wfourcc(pb, "ilst");
2256     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
2257     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
2258     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2259     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2260     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
2261     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
2262     if (!mov->exact &&
2263         !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2264         mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2265     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
2266     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
2267     mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2268     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2269     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
2270     mov_write_string_metadata(s, pb, "desc",    "description",1);
2271     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
2272     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
2273     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
2274     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
2275     mov_write_int8_metadata  (s, pb, "tves",    "episode_sort",4);
2276     mov_write_int8_metadata  (s, pb, "tvsn",    "season_number",4);
2277     mov_write_int8_metadata  (s, pb, "stik",    "media_type",1);
2278     mov_write_int8_metadata  (s, pb, "hdvd",    "hd_video",  1);
2279     mov_write_int8_metadata  (s, pb, "pgap",    "gapless_playback",1);
2280     mov_write_int8_metadata  (s, pb, "cpil",    "compilation", 1);
2281     mov_write_trkn_tag(pb, mov, s, 0); // track number
2282     mov_write_trkn_tag(pb, mov, s, 1); // disc number
2283     mov_write_tmpo_tag(pb, s);
2284     return update_size(pb, pos);
2285 }
2286
2287 /* iTunes meta data tag */
2288 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2289                               AVFormatContext *s)
2290 {
2291     int size = 0;
2292     int64_t pos = avio_tell(pb);
2293     avio_wb32(pb, 0); /* size */
2294     ffio_wfourcc(pb, "meta");
2295     avio_wb32(pb, 0);
2296     mov_write_itunes_hdlr_tag(pb, mov, s);
2297     mov_write_ilst_tag(pb, mov, s);
2298     size = update_size(pb, pos);
2299     return size;
2300 }
2301
2302 static int utf8len(const uint8_t *b)
2303 {
2304     int len = 0;
2305     int val;
2306     while (*b) {
2307         GET_UTF8(val, *b++, return -1;)
2308         len++;
2309     }
2310     return len;
2311 }
2312
2313 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2314 {
2315     int val;
2316     while (*b) {
2317         GET_UTF8(val, *b++, return -1;)
2318         avio_wb16(pb, val);
2319     }
2320     avio_wb16(pb, 0x00);
2321     return 0;
2322 }
2323
2324 static uint16_t language_code(const char *str)
2325 {
2326     return (((str[0] - 0x60) & 0x1F) << 10) +
2327            (((str[1] - 0x60) & 0x1F) <<  5) +
2328            (( str[2] - 0x60) & 0x1F);
2329 }
2330
2331 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2332                                   const char *tag, const char *str)
2333 {
2334     int64_t pos = avio_tell(pb);
2335     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2336     if (!t || !utf8len(t->value))
2337         return 0;
2338     avio_wb32(pb, 0);   /* size */
2339     ffio_wfourcc(pb, tag); /* type */
2340     avio_wb32(pb, 0);   /* version + flags */
2341     if (!strcmp(tag, "yrrc"))
2342         avio_wb16(pb, atoi(t->value));
2343     else {
2344         avio_wb16(pb, language_code("eng")); /* language */
2345         avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2346         if (!strcmp(tag, "albm") &&
2347             (t = av_dict_get(s->metadata, "track", NULL, 0)))
2348             avio_w8(pb, atoi(t->value));
2349     }
2350     return update_size(pb, pos);
2351 }
2352
2353 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2354 {
2355     int64_t pos = avio_tell(pb);
2356     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2357
2358     avio_wb32(pb, 0);            // size
2359     ffio_wfourcc(pb, "chpl");
2360     avio_wb32(pb, 0x01000000);   // version + flags
2361     avio_wb32(pb, 0);            // unknown
2362     avio_w8(pb, nb_chapters);
2363
2364     for (i = 0; i < nb_chapters; i++) {
2365         AVChapter *c = s->chapters[i];
2366         AVDictionaryEntry *t;
2367         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2368
2369         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2370             int len = FFMIN(strlen(t->value), 255);
2371             avio_w8(pb, len);
2372             avio_write(pb, t->value, len);
2373         } else
2374             avio_w8(pb, 0);
2375     }
2376     return update_size(pb, pos);
2377 }
2378
2379 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2380                               AVFormatContext *s)
2381 {
2382     AVIOContext *pb_buf;
2383     int ret, size;
2384     uint8_t *buf;
2385
2386     ret = avio_open_dyn_buf(&pb_buf);
2387     if (ret < 0)
2388         return ret;
2389
2390     if (mov->mode & MODE_3GP) {
2391         mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2392         mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2393         mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2394         mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2395         mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2396         mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2397         mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2398         mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2399     } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2400         mov_write_string_metadata(s, pb_buf, "\251ART", "artist",      0);
2401         mov_write_string_metadata(s, pb_buf, "\251nam", "title",       0);
2402         mov_write_string_metadata(s, pb_buf, "\251aut", "author",      0);
2403         mov_write_string_metadata(s, pb_buf, "\251alb", "album",       0);
2404         mov_write_string_metadata(s, pb_buf, "\251day", "date",        0);
2405         mov_write_string_metadata(s, pb_buf, "\251swr", "encoder",     0);
2406         // currently ignored by mov.c
2407         mov_write_string_metadata(s, pb_buf, "\251des", "comment",     0);
2408         // add support for libquicktime, this atom is also actually read by mov.c
2409         mov_write_string_metadata(s, pb_buf, "\251cmt", "comment",     0);
2410         mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);
2411         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);
2412     } else {
2413         /* iTunes meta data */
2414         mov_write_meta_tag(pb_buf, mov, s);
2415     }
2416
2417     if (s->nb_chapters)
2418         mov_write_chpl_tag(pb_buf, s);
2419
2420     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2421         avio_wb32(pb, size + 8);
2422         ffio_wfourcc(pb, "udta");
2423         avio_write(pb, buf, size);
2424     }
2425     av_free(buf);
2426
2427     return 0;
2428 }
2429
2430 static void mov_write_psp_udta_tag(AVIOContext *pb,
2431                                    const char *str, const char *lang, int type)
2432 {
2433     int len = utf8len(str) + 1;
2434     if (len <= 0)
2435         return;
2436     avio_wb16(pb, len * 2 + 10);        /* size */
2437     avio_wb32(pb, type);                /* type */
2438     avio_wb16(pb, language_code(lang)); /* language */
2439     avio_wb16(pb, 0x01);                /* ? */
2440     ascii_to_wc(pb, str);
2441 }
2442
2443 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2444 {
2445     MOVMuxContext *mov = s->priv_data;
2446     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2447     int64_t pos, pos2;
2448
2449     if (title) {
2450         pos = avio_tell(pb);
2451         avio_wb32(pb, 0); /* size placeholder*/
2452         ffio_wfourcc(pb, "uuid");
2453         ffio_wfourcc(pb, "USMT");
2454         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2455         avio_wb32(pb, 0xbb88695c);
2456         avio_wb32(pb, 0xfac9c740);
2457
2458         pos2 = avio_tell(pb);
2459         avio_wb32(pb, 0); /* size placeholder*/
2460         ffio_wfourcc(pb, "MTDT");
2461         avio_wb16(pb, 4);
2462
2463         // ?
2464         avio_wb16(pb, 0x0C);                 /* size */
2465         avio_wb32(pb, 0x0B);                 /* type */
2466         avio_wb16(pb, language_code("und")); /* language */
2467         avio_wb16(pb, 0x0);                  /* ? */
2468         avio_wb16(pb, 0x021C);               /* data */
2469
2470         if (!mov->exact)
2471             mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
2472         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
2473         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2474
2475         update_size(pb, pos2);
2476         return update_size(pb, pos);
2477     }
2478
2479     return 0;
2480 }
2481
2482 static void build_chunks(MOVTrack *trk)
2483 {
2484     int i;
2485     MOVIentry *chunk = &trk->cluster[0];
2486     uint64_t chunkSize = chunk->size;
2487     chunk->chunkNum = 1;
2488     if (trk->chunkCount)
2489         return;
2490     trk->chunkCount = 1;
2491     for (i = 1; i<trk->entry; i++){
2492         if (chunk->pos + chunkSize == trk->cluster[i].pos &&
2493             chunkSize + trk->cluster[i].size < (1<<20)){
2494             chunkSize             += trk->cluster[i].size;
2495             chunk->samples_in_chunk += trk->cluster[i].entries;
2496         } else {
2497             trk->cluster[i].chunkNum = chunk->chunkNum+1;
2498             chunk=&trk->cluster[i];
2499             chunkSize = chunk->size;
2500             trk->chunkCount++;
2501         }
2502     }
2503 }
2504
2505 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2506                               AVFormatContext *s)
2507 {
2508     int i;
2509     int64_t pos = avio_tell(pb);
2510     avio_wb32(pb, 0); /* size placeholder*/
2511     ffio_wfourcc(pb, "moov");
2512
2513     for (i = 0; i < mov->nb_streams; i++) {
2514         if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2515             continue;
2516
2517         mov->tracks[i].time     = mov->time;
2518         mov->tracks[i].track_id = i + 1;
2519
2520         if (mov->tracks[i].entry)
2521             build_chunks(&mov->tracks[i]);
2522     }
2523
2524     if (mov->chapter_track)
2525         for (i = 0; i < s->nb_streams; i++) {
2526             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2527             mov->tracks[i].tref_id  = mov->tracks[mov->chapter_track].track_id;
2528         }
2529     for (i = 0; i < mov->nb_streams; i++) {
2530         if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
2531             mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
2532             mov->tracks[i].tref_id =
2533                 mov->tracks[mov->tracks[i].src_track].track_id;
2534         }
2535     }
2536     for (i = 0; i < mov->nb_streams; i++) {
2537         if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
2538             int src_trk = mov->tracks[i].src_track;
2539             mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
2540             mov->tracks[src_trk].tref_id  = mov->tracks[i].track_id;
2541             //src_trk may have a different timescale than the tmcd track
2542             mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
2543                                                        mov->tracks[i].timescale,
2544                                                        mov->tracks[src_trk].timescale);
2545         }
2546     }
2547
2548     mov_write_mvhd_tag(pb, mov);
2549     if (mov->mode != MODE_MOV && !mov->iods_skip)
2550         mov_write_iods_tag(pb, mov);
2551     for (i = 0; i < mov->nb_streams; i++) {
2552         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2553             mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2554         }
2555     }
2556     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2557         mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2558
2559     if (mov->mode == MODE_PSP)
2560         mov_write_uuidusmt_tag(pb, s);
2561     else
2562         mov_write_udta_tag(pb, mov, s);
2563
2564     return update_size(pb, pos);
2565 }
2566
2567 static void param_write_int(AVIOContext *pb, const char *name, int value)
2568 {
2569     avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2570 }
2571
2572 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2573 {
2574     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2575 }
2576
2577 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2578 {
2579     char buf[150];
2580     len = FFMIN(sizeof(buf) / 2 - 1, len);
2581     ff_data_to_hex(buf, value, len, 0);
2582     buf[2 * len] = '\0';
2583     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2584 }
2585
2586 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2587 {
2588     int64_t pos = avio_tell(pb);
2589     int i;
2590     static const uint8_t uuid[] = {
2591         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2592         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2593     };
2594
2595     avio_wb32(pb, 0);
2596     ffio_wfourcc(pb, "uuid");
2597     avio_write(pb, uuid, sizeof(uuid));
2598     avio_wb32(pb, 0);
2599
2600     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2601     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2602     avio_printf(pb, "<head>\n");
2603     if (!mov->exact)
2604         avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2605                     LIBAVFORMAT_IDENT);
2606     avio_printf(pb, "</head>\n");
2607     avio_printf(pb, "<body>\n");
2608     avio_printf(pb, "<switch>\n");
2609     for (i = 0; i < mov->nb_streams; i++) {
2610         MOVTrack *track = &mov->tracks[i];
2611         const char *type;
2612         /* track->track_id is initialized in write_moov, and thus isn't known
2613          * here yet */
2614         int track_id = i + 1;
2615
2616         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2617             type = "video";
2618         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2619             type = "audio";
2620         } else {
2621             continue;
2622         }
2623         avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
2624                                                        track->enc->bit_rate);
2625         param_write_int(pb, "systemBitrate", track->enc->bit_rate);
2626         param_write_int(pb, "trackID", track_id);
2627         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2628             if (track->enc->codec_id == AV_CODEC_ID_H264) {
2629                 uint8_t *ptr;
2630                 int size = track->enc->extradata_size;
2631                 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
2632                                                    &size)) {
2633                     param_write_hex(pb, "CodecPrivateData",
2634                                     ptr ? ptr : track->enc->extradata,
2635                                     size);
2636                     av_free(ptr);
2637                 }
2638                 param_write_string(pb, "FourCC", "H264");
2639             } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
2640                 param_write_string(pb, "FourCC", "WVC1");
2641                 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2642                                 track->enc->extradata_size);
2643             }
2644             param_write_int(pb, "MaxWidth", track->enc->width);
2645             param_write_int(pb, "MaxHeight", track->enc->height);
2646             param_write_int(pb, "DisplayWidth", track->enc->width);
2647             param_write_int(pb, "DisplayHeight", track->enc->height);
2648         } else {
2649             if (track->enc->codec_id == AV_CODEC_ID_AAC) {
2650                 param_write_string(pb, "FourCC", "AACL");
2651             } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
2652                 param_write_string(pb, "FourCC", "WMAP");
2653             }
2654             param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2655                             track->enc->extradata_size);
2656             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
2657                                                              track->enc->codec_id));
2658             param_write_int(pb, "Channels", track->enc->channels);
2659             param_write_int(pb, "SamplingRate", track->enc->sample_rate);
2660             param_write_int(pb, "BitsPerSample", 16);
2661             param_write_int(pb, "PacketSize", track->enc->block_align ?
2662                                               track->enc->block_align : 4);
2663         }
2664         avio_printf(pb, "</%s>\n", type);
2665     }
2666     avio_printf(pb, "</switch>\n");
2667     avio_printf(pb, "</body>\n");
2668     avio_printf(pb, "</smil>\n");
2669
2670     return update_size(pb, pos);
2671 }
2672
2673 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2674 {
2675     avio_wb32(pb, 16);
2676     ffio_wfourcc(pb, "mfhd");
2677     avio_wb32(pb, 0);
2678     avio_wb32(pb, mov->fragments);
2679     return 0;
2680 }
2681
2682 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2683                               MOVTrack *track, int64_t moof_offset)
2684 {
2685     int64_t pos = avio_tell(pb);
2686     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2687                      MOV_TFHD_BASE_DATA_OFFSET;
2688     if (!track->entry) {
2689         flags |= MOV_TFHD_DURATION_IS_EMPTY;
2690     } else {
2691         flags |= MOV_TFHD_DEFAULT_FLAGS;
2692     }
2693     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
2694         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
2695
2696     /* Don't set a default sample size, the silverlight player refuses
2697      * to play files with that set. Don't set a default sample duration,
2698      * WMP freaks out if it is set. Don't set a base data offset, PIFF
2699      * file format says it MUST NOT be set. */
2700     if (track->mode == MODE_ISM)
2701         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2702                    MOV_TFHD_BASE_DATA_OFFSET);
2703
2704     avio_wb32(pb, 0); /* size placeholder */
2705     ffio_wfourcc(pb, "tfhd");
2706     avio_w8(pb, 0); /* version */
2707     avio_wb24(pb, flags);
2708
2709     avio_wb32(pb, track->track_id); /* track-id */
2710     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
2711         avio_wb64(pb, moof_offset);
2712     if (flags & MOV_TFHD_DEFAULT_DURATION) {
2713         track->default_duration = get_cluster_duration(track, 0);
2714         avio_wb32(pb, track->default_duration);
2715     }
2716     if (flags & MOV_TFHD_DEFAULT_SIZE) {
2717         track->default_size = track->entry ? track->cluster[0].size : 1;
2718         avio_wb32(pb, track->default_size);
2719     } else
2720         track->default_size = -1;
2721
2722     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
2723         track->default_sample_flags =
2724             track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
2725             (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2726             MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
2727         avio_wb32(pb, track->default_sample_flags);
2728     }
2729
2730     return update_size(pb, pos);
2731 }
2732
2733 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2734 {
2735     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2736            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2737 }
2738
2739 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
2740                               MOVTrack *track, int moof_size)
2741 {
2742     int64_t pos = avio_tell(pb);
2743     uint32_t flags = MOV_TRUN_DATA_OFFSET;
2744     int i;
2745
2746     for (i = 0; i < track->entry; i++) {
2747         if (get_cluster_duration(track, i) != track->default_duration)
2748             flags |= MOV_TRUN_SAMPLE_DURATION;
2749         if (track->cluster[i].size != track->default_size)
2750             flags |= MOV_TRUN_SAMPLE_SIZE;
2751         if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
2752             flags |= MOV_TRUN_SAMPLE_FLAGS;
2753     }
2754     if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
2755         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
2756     if (track->flags & MOV_TRACK_CTTS)
2757         flags |= MOV_TRUN_SAMPLE_CTS;
2758
2759     avio_wb32(pb, 0); /* size placeholder */
2760     ffio_wfourcc(pb, "trun");
2761     avio_w8(pb, 0); /* version */
2762     avio_wb24(pb, flags);
2763
2764     avio_wb32(pb, track->entry); /* sample count */
2765     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
2766         !(mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) &&
2767         track->track_id != 1)
2768         avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
2769     else
2770         avio_wb32(pb, moof_size + 8 + track->data_offset +
2771                       track->cluster[0].pos); /* data offset */
2772     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
2773         avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
2774
2775     for (i = 0; i < track->entry; i++) {
2776         if (flags & MOV_TRUN_SAMPLE_DURATION)
2777             avio_wb32(pb, get_cluster_duration(track, i));
2778         if (flags & MOV_TRUN_SAMPLE_SIZE)
2779             avio_wb32(pb, track->cluster[i].size);
2780         if (flags & MOV_TRUN_SAMPLE_FLAGS)
2781             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
2782         if (flags & MOV_TRUN_SAMPLE_CTS)
2783             avio_wb32(pb, track->cluster[i].cts);
2784     }
2785
2786     return update_size(pb, pos);
2787 }
2788
2789 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2790 {
2791     int64_t pos = avio_tell(pb);
2792     static const uint8_t uuid[] = {
2793         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2794         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2795     };
2796
2797     avio_wb32(pb, 0); /* size placeholder */
2798     ffio_wfourcc(pb, "uuid");
2799     avio_write(pb, uuid, sizeof(uuid));
2800     avio_w8(pb, 1);
2801     avio_wb24(pb, 0);
2802     avio_wb64(pb, track->frag_start);
2803     avio_wb64(pb, track->start_dts + track->track_duration -
2804                   track->cluster[0].dts);
2805
2806     return update_size(pb, pos);
2807 }
2808
2809 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2810                               MOVTrack *track, int entry)
2811 {
2812     int n = track->nb_frag_info - 1 - entry, i;
2813     int size = 8 + 16 + 4 + 1 + 16*n;
2814     static const uint8_t uuid[] = {
2815         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2816         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2817     };
2818
2819     if (entry < 0)
2820         return 0;
2821
2822     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2823     avio_wb32(pb, size);
2824     ffio_wfourcc(pb, "uuid");
2825     avio_write(pb, uuid, sizeof(uuid));
2826     avio_w8(pb, 1);
2827     avio_wb24(pb, 0);
2828     avio_w8(pb, n);
2829     for (i = 0; i < n; i++) {
2830         int index = entry + 1 + i;
2831         avio_wb64(pb, track->frag_info[index].time);
2832         avio_wb64(pb, track->frag_info[index].duration);
2833     }
2834     if (n < mov->ism_lookahead) {
2835         int free_size = 16 * (mov->ism_lookahead - n);
2836         avio_wb32(pb, free_size);
2837         ffio_wfourcc(pb, "free");
2838         ffio_fill(pb, 0, free_size - 8);
2839     }
2840
2841     return 0;
2842 }
2843
2844 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2845                                MOVTrack *track)
2846 {
2847     int64_t pos = avio_tell(pb);
2848     int i;
2849     for (i = 0; i < mov->ism_lookahead; i++) {
2850         /* Update the tfrf tag for the last ism_lookahead fragments,
2851          * nb_frag_info - 1 is the next fragment to be written. */
2852         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2853     }
2854     avio_seek(pb, pos, SEEK_SET);
2855     return 0;
2856 }
2857
2858 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
2859                               MOVTrack *track, int64_t moof_offset,
2860                               int moof_size)
2861 {
2862     int64_t pos = avio_tell(pb);
2863     avio_wb32(pb, 0); /* size placeholder */
2864     ffio_wfourcc(pb, "traf");
2865
2866     mov_write_tfhd_tag(pb, mov, track, moof_offset);
2867     mov_write_trun_tag(pb, mov, track, moof_size);
2868     if (mov->mode == MODE_ISM) {
2869         mov_write_tfxd_tag(pb, track);
2870
2871         if (mov->ism_lookahead) {
2872             int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
2873
2874             track->tfrf_offset = avio_tell(pb);
2875             avio_wb32(pb, 8 + size);
2876             ffio_wfourcc(pb, "free");
2877             for (i = 0; i < size; i++)
2878                 avio_w8(pb, 0);
2879         }
2880     }
2881
2882     return update_size(pb, pos);
2883 }
2884
2885 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
2886                                        int tracks, int moof_size)
2887 {
2888     int64_t pos = avio_tell(pb);
2889     int i;
2890
2891     avio_wb32(pb, 0); /* size placeholder */
2892     ffio_wfourcc(pb, "moof");
2893
2894     mov_write_mfhd_tag(pb, mov);
2895     for (i = 0; i < mov->nb_streams; i++) {
2896         MOVTrack *track = &mov->tracks[i];
2897         if (tracks >= 0 && i != tracks)
2898             continue;
2899         if (!track->entry)
2900             continue;
2901         mov_write_traf_tag(pb, mov, track, pos, moof_size);
2902     }
2903
2904     return update_size(pb, pos);
2905 }
2906
2907 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
2908 {
2909     AVIOContext *avio_buf;
2910     int ret, moof_size;
2911
2912     if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
2913         return ret;
2914     mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
2915     moof_size = ffio_close_null_buf(avio_buf);
2916     return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
2917 }
2918
2919 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
2920 {
2921     int64_t pos = avio_tell(pb);
2922     int i;
2923
2924     avio_wb32(pb, 0); /* size placeholder */
2925     ffio_wfourcc(pb, "tfra");
2926     avio_w8(pb, 1); /* version */
2927     avio_wb24(pb, 0);
2928
2929     avio_wb32(pb, track->track_id);
2930     avio_wb32(pb, 0); /* length of traf/trun/sample num */
2931     avio_wb32(pb, track->nb_frag_info);
2932     for (i = 0; i < track->nb_frag_info; i++) {
2933         avio_wb64(pb, track->frag_info[i].time);
2934         avio_wb64(pb, track->frag_info[i].offset);
2935         avio_w8(pb, 1); /* traf number */
2936         avio_w8(pb, 1); /* trun number */
2937         avio_w8(pb, 1); /* sample number */
2938     }
2939
2940     return update_size(pb, pos);
2941 }
2942
2943 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
2944 {
2945     int64_t pos = avio_tell(pb);
2946     int i;
2947
2948     avio_wb32(pb, 0); /* size placeholder */
2949     ffio_wfourcc(pb, "mfra");
2950     /* An empty mfra atom is enough to indicate to the publishing point that
2951      * the stream has ended. */
2952     if (mov->flags & FF_MOV_FLAG_ISML)
2953         return update_size(pb, pos);
2954
2955     for (i = 0; i < mov->nb_streams; i++) {
2956         MOVTrack *track = &mov->tracks[i];
2957         if (track->nb_frag_info)
2958             mov_write_tfra_tag(pb, track);
2959     }
2960
2961     avio_wb32(pb, 16);
2962     ffio_wfourcc(pb, "mfro");
2963     avio_wb32(pb, 0); /* version + flags */
2964     avio_wb32(pb, avio_tell(pb) + 4 - pos);
2965
2966     return update_size(pb, pos);
2967 }
2968
2969 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
2970 {
2971     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
2972     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
2973
2974     mov->mdat_pos = avio_tell(pb);
2975     avio_wb32(pb, 0); /* size placeholder*/
2976     ffio_wfourcc(pb, "mdat");
2977     return 0;
2978 }
2979
2980 /* TODO: This needs to be more general */
2981 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
2982 {
2983     MOVMuxContext *mov = s->priv_data;
2984     int64_t pos = avio_tell(pb);
2985     int has_h264 = 0, has_video = 0;
2986     int minor = 0x200;
2987     int i;
2988
2989     for (i = 0; i < s->nb_streams; i++) {
2990         AVStream *st = s->streams[i];
2991         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2992             has_video = 1;
2993         if (st->codec->codec_id == AV_CODEC_ID_H264)
2994             has_h264 = 1;
2995     }
2996
2997     avio_wb32(pb, 0); /* size */
2998     ffio_wfourcc(pb, "ftyp");
2999
3000     if (mov->major_brand && strlen(mov->major_brand) >= 4)
3001         ffio_wfourcc(pb, mov->major_brand);
3002     else if (mov->mode == MODE_3GP) {
3003         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
3004         minor =     has_h264 ?   0x100 :   0x200;
3005     } else if (mov->mode & MODE_3G2) {
3006         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
3007         minor =     has_h264 ? 0x20000 : 0x10000;
3008     } else if (mov->mode == MODE_PSP)
3009         ffio_wfourcc(pb, "MSNV");
3010     else if (mov->mode == MODE_MP4)
3011         ffio_wfourcc(pb, "isom");
3012     else if (mov->mode == MODE_IPOD)
3013         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3014     else if (mov->mode == MODE_ISM)
3015         ffio_wfourcc(pb, "isml");
3016     else if (mov->mode == MODE_F4V)
3017         ffio_wfourcc(pb, "f4v ");
3018     else
3019         ffio_wfourcc(pb, "qt  ");
3020
3021     avio_wb32(pb, minor);
3022
3023     if (mov->mode == MODE_MOV)
3024         ffio_wfourcc(pb, "qt  ");
3025     else if (mov->mode == MODE_ISM) {
3026         ffio_wfourcc(pb, "piff");
3027         ffio_wfourcc(pb, "iso2");
3028     } else {
3029         ffio_wfourcc(pb, "isom");
3030         ffio_wfourcc(pb, "iso2");
3031         if (has_h264)
3032             ffio_wfourcc(pb, "avc1");
3033     }
3034
3035     if (mov->mode == MODE_3GP)
3036         ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3037     else if (mov->mode & MODE_3G2)
3038         ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3039     else if (mov->mode == MODE_PSP)
3040         ffio_wfourcc(pb, "MSNV");
3041     else if (mov->mode == MODE_MP4)
3042         ffio_wfourcc(pb, "mp41");
3043     return update_size(pb, pos);
3044 }
3045
3046 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3047 {
3048     AVCodecContext *video_codec = s->streams[0]->codec;
3049     AVCodecContext *audio_codec = s->streams[1]->codec;
3050     int audio_rate = audio_codec->sample_rate;
3051     int frame_rate = ((video_codec->time_base.den) * (0x10000)) / (video_codec->time_base.num);
3052     int audio_kbitrate = audio_codec->bit_rate / 1000;
3053     int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3054
3055     avio_wb32(pb, 0x94); /* size */
3056     ffio_wfourcc(pb, "uuid");
3057     ffio_wfourcc(pb, "PROF");
3058
3059     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3060     avio_wb32(pb, 0xbb88695c);
3061     avio_wb32(pb, 0xfac9c740);
3062
3063     avio_wb32(pb, 0x0);  /* ? */
3064     avio_wb32(pb, 0x3);  /* 3 sections ? */
3065
3066     avio_wb32(pb, 0x14); /* size */
3067     ffio_wfourcc(pb, "FPRF");
3068     avio_wb32(pb, 0x0);  /* ? */
3069     avio_wb32(pb, 0x0);  /* ? */
3070     avio_wb32(pb, 0x0);  /* ? */
3071
3072     avio_wb32(pb, 0x2c);  /* size */
3073     ffio_wfourcc(pb, "APRF"); /* audio */
3074     avio_wb32(pb, 0x0);
3075     avio_wb32(pb, 0x2);   /* TrackID */
3076     ffio_wfourcc(pb, "mp4a");
3077     avio_wb32(pb, 0x20f);
3078     avio_wb32(pb, 0x0);
3079     avio_wb32(pb, audio_kbitrate);
3080     avio_wb32(pb, audio_kbitrate);
3081     avio_wb32(pb, audio_rate);
3082     avio_wb32(pb, audio_codec->channels);
3083
3084     avio_wb32(pb, 0x34);  /* size */
3085     ffio_wfourcc(pb, "VPRF");   /* video */
3086     avio_wb32(pb, 0x0);
3087     avio_wb32(pb, 0x1);    /* TrackID */
3088     if (video_codec->codec_id == AV_CODEC_ID_H264) {
3089         ffio_wfourcc(pb, "avc1");
3090         avio_wb16(pb, 0x014D);
3091         avio_wb16(pb, 0x0015);
3092     } else {
3093         ffio_wfourcc(pb, "mp4v");
3094         avio_wb16(pb, 0x0000);
3095         avio_wb16(pb, 0x0103);
3096     }
3097     avio_wb32(pb, 0x0);
3098     avio_wb32(pb, video_kbitrate);
3099     avio_wb32(pb, video_kbitrate);
3100     avio_wb32(pb, frame_rate);
3101     avio_wb32(pb, frame_rate);
3102     avio_wb16(pb, video_codec->width);
3103     avio_wb16(pb, video_codec->height);
3104     avio_wb32(pb, 0x010001); /* ? */
3105 }
3106
3107 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3108 {
3109     uint32_t c = -1;
3110     int i, closed_gop = 0;
3111
3112     for (i = 0; i < pkt->size - 4; i++) {
3113         c = (c << 8) + pkt->data[i];
3114         if (c == 0x1b8) { // gop
3115             closed_gop = pkt->data[i + 4] >> 6 & 0x01;
3116         } else if (c == 0x100) { // pic
3117             int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
3118             if (!temp_ref || closed_gop) // I picture is not reordered
3119                 *flags = MOV_SYNC_SAMPLE;
3120             else
3121                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
3122             break;
3123         }
3124     }
3125     return 0;
3126 }
3127
3128 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
3129 {
3130     const uint8_t *start, *next, *end = pkt->data + pkt->size;
3131     int seq = 0, entry = 0;
3132     int key = pkt->flags & AV_PKT_FLAG_KEY;
3133     start = find_next_marker(pkt->data, end);
3134     for (next = start; next < end; start = next) {
3135         next = find_next_marker(start + 4, end);
3136         switch (AV_RB32(start)) {
3137         case VC1_CODE_SEQHDR:
3138             seq = 1;
3139             break;
3140         case VC1_CODE_ENTRYPOINT:
3141             entry = 1;
3142             break;
3143         case VC1_CODE_SLICE:
3144             trk->vc1_info.slices = 1;
3145             break;
3146         }
3147     }
3148     if (!trk->entry && !fragment) {
3149         /* First packet in first fragment */
3150         trk->vc1_info.first_packet_seq   = seq;
3151         trk->vc1_info.first_packet_entry = entry;
3152     } else if ((seq && !trk->vc1_info.packet_seq) ||
3153                (entry && !trk->vc1_info.packet_entry)) {
3154         int i;
3155         for (i = 0; i < trk->entry; i++)
3156             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
3157         trk->has_keyframes = 0;
3158         if (seq)
3159             trk->vc1_info.packet_seq = 1;
3160         if (entry)
3161             trk->vc1_info.packet_entry = 1;
3162         if (!fragment) {
3163             /* First fragment */
3164             if ((!seq   || trk->vc1_info.first_packet_seq) &&
3165                 (!entry || trk->vc1_info.first_packet_entry)) {
3166                 /* First packet had the same headers as this one, readd the
3167                  * sync sample flag. */
3168                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
3169                 trk->has_keyframes = 1;
3170             }
3171         }
3172     }
3173     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
3174         key = seq && entry;
3175     else if (trk->vc1_info.packet_seq)
3176         key = seq;
3177     else if (trk->vc1_info.packet_entry)
3178         key = entry;
3179     if (key) {
3180         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
3181         trk->has_keyframes++;
3182     }
3183 }
3184
3185 static int mov_flush_fragment(AVFormatContext *s)
3186 {
3187     MOVMuxContext *mov = s->priv_data;
3188     int i, first_track = -1;
3189     int64_t mdat_size = 0;
3190
3191     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3192         return 0;
3193
3194     if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
3195         int64_t pos = avio_tell(s->pb);
3196         uint8_t *buf;
3197         int buf_size, moov_size;
3198
3199         for (i = 0; i < mov->nb_streams; i++)
3200             if (!mov->tracks[i].entry)
3201                 break;
3202         /* Don't write the initial moov unless all tracks have data */
3203         if (i < mov->nb_streams)
3204             return 0;
3205
3206         moov_size = get_moov_size(s);
3207         for (i = 0; i < mov->nb_streams; i++)
3208             mov->tracks[i].data_offset = pos + moov_size + 8;
3209
3210         mov_write_moov_tag(s->pb, mov, s);
3211
3212         buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
3213         mov->mdat_buf = NULL;
3214         avio_wb32(s->pb, buf_size + 8);
3215         ffio_wfourcc(s->pb, "mdat");
3216         avio_write(s->pb, buf, buf_size);
3217         av_free(buf);
3218
3219         mov->fragments++;
3220         mov->mdat_size = 0;
3221         for (i = 0; i < mov->nb_streams; i++) {
3222             if (mov->tracks[i].entry)
3223                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
3224                                              mov->tracks[i].track_duration -
3225                                              mov->tracks[i].cluster[0].dts;
3226             mov->tracks[i].entry = 0;
3227         }
3228         avio_flush(s->pb);
3229         return 0;
3230     }
3231
3232     for (i = 0; i < mov->nb_streams; i++) {
3233         MOVTrack *track = &mov->tracks[i];
3234         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
3235             track->data_offset = 0;
3236         else
3237             track->data_offset = mdat_size;
3238         if (!track->mdat_buf)
3239             continue;
3240         mdat_size += avio_tell(track->mdat_buf);
3241         if (first_track < 0)
3242             first_track = i;
3243     }
3244
3245     if (!mdat_size)
3246         return 0;
3247
3248     for (i = 0; i < mov->nb_streams; i++) {
3249         MOVTrack *track = &mov->tracks[i];
3250         int buf_size, write_moof = 1, moof_tracks = -1;
3251         uint8_t *buf;
3252         int64_t duration = 0;
3253
3254         if (track->entry)
3255             duration = track->start_dts + track->track_duration -
3256                        track->cluster[0].dts;
3257         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
3258             if (!track->mdat_buf)
3259                 continue;
3260             mdat_size = avio_tell(track->mdat_buf);
3261             moof_tracks = i;
3262         } else {
3263             write_moof = i == first_track;
3264         }
3265
3266         if (write_moof) {
3267             MOVFragmentInfo *info;
3268             avio_flush(s->pb);
3269             track->nb_frag_info++;
3270             if (track->nb_frag_info >= track->frag_info_capacity) {
3271                 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3272                 if (av_reallocp_array(&track->frag_info,
3273                                       new_capacity,
3274                                       sizeof(*track->frag_info)))
3275                     return AVERROR(ENOMEM);
3276                 track->frag_info_capacity = new_capacity;
3277             }
3278             info = &track->frag_info[track->nb_frag_info - 1];
3279             info->offset   = avio_tell(s->pb);
3280             info->time     = mov->tracks[i].frag_start;
3281             info->duration = duration;
3282             mov_write_tfrf_tags(s->pb, mov, track);
3283
3284             mov_write_moof_tag(s->pb, mov, moof_tracks);
3285             info->tfrf_offset = track->tfrf_offset;
3286             mov->fragments++;
3287
3288             avio_wb32(s->pb, mdat_size + 8);
3289             ffio_wfourcc(s->pb, "mdat");
3290         }
3291
3292         if (track->entry)
3293             track->frag_start += duration;
3294         track->entry = 0;
3295         if (!track->mdat_buf)
3296             continue;
3297         buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
3298         track->mdat_buf = NULL;
3299
3300         avio_write(s->pb, buf, buf_size);
3301         av_free(buf);
3302     }
3303
3304     mov->mdat_size = 0;
3305
3306     avio_flush(s->pb);
3307     return 0;
3308 }
3309
3310 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3311 {
3312     MOVMuxContext *mov = s->priv_data;
3313     AVIOContext *pb = s->pb;
3314     MOVTrack *trk = &mov->tracks[pkt->stream_index];
3315     AVCodecContext *enc = trk->enc;
3316     unsigned int samples_in_chunk = 0;
3317     int size = pkt->size;
3318     uint8_t *reformatted_data = NULL;
3319
3320     if (trk->entry) {
3321         int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
3322         if (duration < 0 || duration > INT_MAX) {
3323             av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
3324                 duration, pkt->dts
3325             );
3326
3327             pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
3328             pkt->pts = AV_NOPTS_VALUE;
3329         }
3330     }
3331     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
3332         int ret;
3333         if (mov->fragments > 0) {
3334             if (!trk->mdat_buf) {
3335                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
3336                     return ret;
3337             }
3338             pb = trk->mdat_buf;
3339         } else {
3340             if (!mov->mdat_buf) {
3341                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
3342                     return ret;
3343             }
3344             pb = mov->mdat_buf;
3345         }
3346     }
3347
3348     if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
3349         /* We must find out how many AMR blocks there are in one packet */
3350         static uint16_t packed_size[16] =
3351             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
3352         int len = 0;
3353
3354         while (len < size && samples_in_chunk < 100) {
3355             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
3356             samples_in_chunk++;
3357         }
3358         if (samples_in_chunk > 1) {
3359             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
3360             return -1;
3361         }
3362     } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
3363                enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
3364         samples_in_chunk = enc->frame_size;
3365     } else if (trk->sample_size)
3366         samples_in_chunk = size / trk->sample_size;
3367     else
3368         samples_in_chunk = 1;
3369
3370     /* copy extradata if it exists */
3371     if (trk->vos_len == 0 && enc->extradata_size > 0) {
3372         trk->vos_len  = enc->extradata_size;
3373         trk->vos_data = av_malloc(trk->vos_len);
3374         memcpy(trk->vos_data, enc->extradata, trk->vos_len);
3375     }
3376
3377     if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
3378         (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
3379         if (!s->streams[pkt->stream_index]->nb_frames) {
3380             av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
3381                    "use audio bitstream filter 'aac_adtstoasc' to fix it "
3382                    "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
3383             return -1;
3384         }
3385         av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
3386     }
3387     if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {
3388         /* from x264 or from bytestream h264 */
3389         /* nal reformating needed */
3390         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3391             ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
3392                                        &size);
3393             avio_write(pb, reformatted_data, size);
3394         } else {
3395             size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
3396         }
3397     } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
3398                (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
3399         /* extradata is Annex B, assume the bitstream is too and convert it */
3400         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3401             ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
3402             avio_write(pb, reformatted_data, size);
3403         } else {
3404             size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
3405         }
3406     } else {
3407         avio_write(pb, pkt->data, size);
3408     }
3409
3410     if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
3411          enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
3412         /* copy frame to create needed atoms */
3413         trk->vos_len  = size;
3414         trk->vos_data = av_malloc(size);
3415         if (!trk->vos_data)
3416             return AVERROR(ENOMEM);
3417         memcpy(trk->vos_data, pkt->data, size);
3418     }
3419
3420     if (trk->entry >= trk->cluster_capacity) {
3421         unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
3422         if (av_reallocp_array(&trk->cluster, new_capacity,
3423                               sizeof(*trk->cluster)))
3424             return AVERROR(ENOMEM);
3425         trk->cluster_capacity = new_capacity;
3426     }
3427
3428     trk->cluster[trk->entry].pos              = avio_tell(pb) - size;
3429     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
3430     trk->cluster[trk->entry].chunkNum         = 0;
3431     trk->cluster[trk->entry].size             = size;
3432     trk->cluster[trk->entry].entries          = samples_in_chunk;
3433     trk->cluster[trk->entry].dts              = pkt->dts;
3434     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
3435         /* First packet of a new fragment. We already wrote the duration
3436          * of the last packet of the previous fragment based on track_duration,
3437          * which might not exactly match our dts. Therefore adjust the dts
3438          * of this packet to be what the previous packets duration implies. */
3439         trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
3440     }
3441     if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !supports_edts(mov)) {
3442         trk->cluster[trk->entry].dts = trk->start_dts = 0;
3443     }
3444     if (trk->start_dts == AV_NOPTS_VALUE)
3445         trk->start_dts = pkt->dts;
3446     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
3447     trk->last_sample_is_subtitle_end = 0;
3448
3449     if (pkt->pts == AV_NOPTS_VALUE) {
3450         av_log(s, AV_LOG_WARNING, "pts has no value\n");
3451         pkt->pts = pkt->dts;
3452     }
3453     if (pkt->dts != pkt->pts)
3454         trk->flags |= MOV_TRACK_CTTS;
3455     trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;
3456     trk->cluster[trk->entry].flags = 0;
3457     if (enc->codec_id == AV_CODEC_ID_VC1) {
3458         mov_parse_vc1_frame(pkt, trk, mov->fragments);
3459     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
3460         if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
3461             trk->entry > 0) { // force sync sample for the first key frame
3462             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
3463             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
3464                 trk->flags |= MOV_TRACK_STPS;
3465         } else {
3466             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
3467         }
3468         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
3469             trk->has_keyframes++;
3470     }
3471     trk->entry++;
3472     trk->sample_count += samples_in_chunk;
3473     mov->mdat_size    += size;
3474
3475     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
3476         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
3477                                  reformatted_data, size);
3478     av_free(reformatted_data);
3479     return 0;
3480 }
3481
3482 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
3483 {
3484         MOVMuxContext *mov = s->priv_data;
3485         MOVTrack *trk = &mov->tracks[pkt->stream_index];
3486         AVCodecContext *enc = trk->enc;
3487         int64_t frag_duration = 0;
3488         int size = pkt->size;
3489
3490         if (!pkt->size)
3491             return 0;             /* Discard 0 sized packets */
3492
3493         if (trk->entry && pkt->stream_index < s->nb_streams)
3494             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
3495                                          s->streams[pkt->stream_index]->time_base,
3496                                          AV_TIME_BASE_Q);
3497         if ((mov->max_fragment_duration &&
3498              frag_duration >= mov->max_fragment_duration) ||
3499              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
3500              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
3501               enc->codec_type == AVMEDIA_TYPE_VIDEO &&
3502               trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
3503             if (frag_duration >= mov->min_fragment_duration)
3504                 mov_flush_fragment(s);
3505         }
3506
3507         return ff_mov_write_packet(s, pkt);
3508 }
3509
3510 static int mov_write_subtitle_end_packet(AVFormatContext *s,
3511                                          int stream_index,
3512                                          int64_t dts) {
3513     AVPacket end;
3514     uint8_t data[2] = {0};
3515     int ret;
3516
3517     av_init_packet(&end);
3518     end.size = sizeof(data);
3519     end.data = data;
3520     end.pts = dts;
3521     end.dts = dts;
3522     end.duration = 0;
3523     end.stream_index = stream_index;
3524
3525     ret = mov_write_single_packet(s, &end);
3526     av_free_packet(&end);
3527
3528     return ret;
3529 }
3530
3531 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3532 {
3533     if (!pkt) {
3534         mov_flush_fragment(s);
3535         return 1;
3536     } else {
3537         int i;
3538         MOVMuxContext *mov = s->priv_data;
3539
3540         if (!pkt->size) return 0; /* Discard 0 sized packets */
3541
3542         /*
3543          * Subtitles require special handling.
3544          *
3545          * 1) For full complaince, every track must have a sample at
3546          * dts == 0, which is rarely true for subtitles. So, as soon
3547          * as we see any packet with dts > 0, write an empty subtitle
3548          * at dts == 0 for any subtitle track with no samples in it.
3549          *
3550          * 2) For each subtitle track, check if the current packet's
3551          * dts is past the duration of the last subtitle sample. If
3552          * so, we now need to write an end sample for that subtitle.
3553          *
3554          * This must be done conditionally to allow for subtitles that
3555          * immediately replace each other, in which case an end sample
3556          * is not needed, and is, in fact, actively harmful.
3557          *
3558          * 3) See mov_write_trailer for how the final end sample is
3559          * handled.
3560          */
3561         for (i = 0; i < mov->nb_streams; i++) {
3562             MOVTrack *trk = &mov->tracks[i];
3563             int ret;
3564
3565             if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
3566                 trk->track_duration < pkt->dts &&
3567                 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
3568                 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
3569                 if (ret < 0) return ret;
3570                 trk->last_sample_is_subtitle_end = 1;
3571             }
3572         }
3573
3574         return mov_write_single_packet(s, pkt);
3575     }
3576 }
3577
3578 // QuickTime chapters involve an additional text track with the chapter names
3579 // as samples, and a tref pointing from the other tracks to the chapter one.
3580 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
3581 {
3582     AVIOContext *pb;
3583
3584     MOVMuxContext *mov = s->priv_data;
3585     MOVTrack *track = &mov->tracks[tracknum];
3586     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
3587     int i, len;
3588
3589     track->mode = mov->mode;
3590     track->tag = MKTAG('t','e','x','t');
3591     track->timescale = MOV_TIMESCALE;
3592     track->enc = avcodec_alloc_context3(NULL);
3593     if (!track->enc)
3594         return AVERROR(ENOMEM);
3595     track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3596 #if 0
3597     // These properties are required to make QT recognize the chapter track
3598     uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
3599     if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
3600         return AVERROR(ENOMEM);
3601     memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
3602 #else
3603     if (avio_open_dyn_buf(&pb) >= 0) {
3604         int size;
3605         uint8_t *buf;
3606
3607         /* Stub header (usually for Quicktime chapter track) */
3608         // TextSampleEntry
3609         avio_wb32(pb, 0x01); // displayFlags
3610         avio_w8(pb, 0x00);   // horizontal justification
3611         avio_w8(pb, 0x00);   // vertical justification
3612         avio_w8(pb, 0x00);   // bgColourRed
3613         avio_w8(pb, 0x00);   // bgColourGreen
3614         avio_w8(pb, 0x00);   // bgColourBlue
3615         avio_w8(pb, 0x00);   // bgColourAlpha
3616         // BoxRecord
3617         avio_wb16(pb, 0x00); // defTextBoxTop
3618         avio_wb16(pb, 0x00); // defTextBoxLeft
3619         avio_wb16(pb, 0x00); // defTextBoxBottom
3620         avio_wb16(pb, 0x00); // defTextBoxRight
3621         // StyleRecord
3622         avio_wb16(pb, 0x00); // startChar
3623         avio_wb16(pb, 0x00); // endChar
3624         avio_wb16(pb, 0x01); // fontID
3625         avio_w8(pb, 0x00);   // fontStyleFlags
3626         avio_w8(pb, 0x00);   // fontSize
3627         avio_w8(pb, 0x00);   // fgColourRed
3628         avio_w8(pb, 0x00);   // fgColourGreen
3629         avio_w8(pb, 0x00);   // fgColourBlue
3630         avio_w8(pb, 0x00);   // fgColourAlpha
3631         // FontTableBox
3632         avio_wb32(pb, 0x0D); // box size
3633         ffio_wfourcc(pb, "ftab"); // box atom name
3634         avio_wb16(pb, 0x01); // entry count
3635         // FontRecord
3636         avio_wb16(pb, 0x01); // font ID
3637         avio_w8(pb, 0x00);   // font name length
3638
3639         if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
3640             track->enc->extradata = buf;
3641             track->enc->extradata_size = size;
3642         } else {
3643             av_freep(&buf);
3644         }
3645     }
3646 #endif
3647
3648     for (i = 0; i < s->nb_chapters; i++) {
3649         AVChapter *c = s->chapters[i];
3650         AVDictionaryEntry *t;
3651
3652         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
3653         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
3654         pkt.duration = end - pkt.dts;
3655
3656         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3657             len      = strlen(t->value);
3658             pkt.size = len + 2;
3659             pkt.data = av_malloc(pkt.size);
3660             if (!pkt.data)
3661                 return AVERROR(ENOMEM);
3662             AV_WB16(pkt.data, len);
3663             memcpy(pkt.data + 2, t->value, len);
3664             ff_mov_write_packet(s, &pkt);
3665             av_freep(&pkt.data);
3666         }
3667     }
3668
3669     return 0;
3670 }
3671
3672 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
3673 {
3674     int ret;
3675     MOVMuxContext *mov  = s->priv_data;
3676     MOVTrack *track     = &mov->tracks[index];
3677     AVStream *src_st    = s->streams[src_index];
3678     AVTimecode tc;
3679     AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
3680     AVRational rate = find_fps(s, src_st);
3681
3682     /* compute the frame number */
3683     ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
3684     if (ret < 0)
3685         return ret;
3686
3687     /* tmcd track based on video stream */
3688     track->mode      = mov->mode;
3689     track->tag       = MKTAG('t','m','c','d');
3690     track->src_track = src_index;
3691     track->timescale = mov->tracks[src_index].timescale;
3692     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
3693         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
3694
3695     /* encode context: tmcd data stream */
3696     track->enc = avcodec_alloc_context3(NULL);
3697     track->enc->codec_type = AVMEDIA_TYPE_DATA;
3698     track->enc->codec_tag  = track->tag;
3699     track->enc->time_base  = av_inv_q(rate);
3700
3701     /* the tmcd track just contains one packet with the frame number */
3702     pkt.data = av_malloc(pkt.size);
3703     AV_WB32(pkt.data, tc.start);
3704     ret = ff_mov_write_packet(s, &pkt);
3705     av_free(pkt.data);
3706     return ret;
3707 }
3708
3709 /*
3710  * st->disposition controls the "enabled" flag in the tkhd tag.
3711  * QuickTime will not play a track if it is not enabled.  So make sure
3712  * that one track of each type (audio, video, subtitle) is enabled.
3713  *
3714  * Subtitles are special.  For audio and video, setting "enabled" also
3715  * makes the track "default" (i.e. it is rendered when played). For
3716  * subtitles, an "enabled" subtitle is not rendered by default, but
3717  * if no subtitle is enabled, the subtitle menu in QuickTime will be
3718  * empty!
3719  */
3720 static void enable_tracks(AVFormatContext *s)
3721 {
3722     MOVMuxContext *mov = s->priv_data;
3723     int i;
3724     uint8_t enabled[AVMEDIA_TYPE_NB];
3725     int first[AVMEDIA_TYPE_NB];
3726
3727     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3728         enabled[i] = 0;
3729         first[i] = -1;
3730     }
3731
3732     for (i = 0; i < s->nb_streams; i++) {
3733         AVStream *st = s->streams[i];
3734
3735         if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
3736             st->codec->codec_type >= AVMEDIA_TYPE_NB)
3737             continue;
3738
3739         if (first[st->codec->codec_type] < 0)
3740             first[st->codec->codec_type] = i;
3741         if (st->disposition & AV_DISPOSITION_DEFAULT) {
3742             mov->tracks[i].flags |= MOV_TRACK_ENABLED;
3743             enabled[st->codec->codec_type] = 1;
3744         }
3745     }
3746
3747     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3748         switch (i) {
3749         case AVMEDIA_TYPE_VIDEO:
3750         case AVMEDIA_TYPE_AUDIO:
3751         case AVMEDIA_TYPE_SUBTITLE:
3752             if (!enabled[i] && first[i] >= 0)
3753                 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
3754             break;
3755         }
3756     }
3757 }
3758
3759 static void mov_free(AVFormatContext *s)
3760 {
3761     MOVMuxContext *mov = s->priv_data;
3762     int i;
3763
3764     if (mov->chapter_track) {
3765         if (mov->tracks[mov->chapter_track].enc)
3766             av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
3767         av_freep(&mov->tracks[mov->chapter_track].enc);
3768     }
3769
3770     for (i = 0; i < mov->nb_streams; i++) {
3771         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
3772             ff_mov_close_hinting(&mov->tracks[i]);
3773         else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
3774             av_freep(&mov->tracks[i].enc);
3775         av_freep(&mov->tracks[i].cluster);
3776         av_freep(&mov->tracks[i].frag_info);
3777
3778         if (mov->tracks[i].vos_len)
3779             av_freep(&mov->tracks[i].vos_data);
3780     }
3781
3782     av_freep(&mov->tracks);
3783 }
3784
3785 static uint32_t rgb_to_yuv(uint32_t rgb)
3786 {
3787     uint8_t r, g, b;
3788     int y, cb, cr;
3789
3790     r = (rgb >> 16) & 0xFF;
3791     g = (rgb >>  8) & 0xFF;
3792     b = (rgb      ) & 0xFF;
3793
3794     y  = av_clip_uint8( 16. +  0.257 * r + 0.504 * g + 0.098 * b);
3795     cb = av_clip_uint8(128. -  0.148 * r - 0.291 * g + 0.439 * b);
3796     cr = av_clip_uint8(128. +  0.439 * r - 0.368 * g - 0.071 * b);
3797
3798     return (y << 16) | (cr << 8) | cb;
3799 }
3800
3801 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
3802                                                     AVStream *st)
3803 {
3804     int i, width = 720, height = 480;
3805     int have_palette = 0, have_size = 0;
3806     uint32_t palette[16];
3807     char *cur = st->codec->extradata;
3808
3809     while (cur && *cur) {
3810         if (strncmp("palette:", cur, 8) == 0) {
3811             int i, count;
3812             count = sscanf(cur + 8,
3813                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3814                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3815                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3816                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
3817                 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
3818                 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
3819                 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
3820                 &palette[12], &palette[13], &palette[14], &palette[15]);
3821
3822             for (i = 0; i < count; i++) {
3823                 palette[i] = rgb_to_yuv(palette[i]);
3824             }
3825             have_palette = 1;
3826         } else if (!strncmp("size:", cur, 5)) {
3827             sscanf(cur + 5, "%dx%d", &width, &height);
3828             have_size = 1;
3829         }
3830         if (have_palette && have_size)
3831             break;
3832         cur += strcspn(cur, "\n\r");
3833         cur += strspn(cur, "\n\r");
3834     }
3835     if (have_palette) {
3836         track->vos_data = av_malloc(16*4);
3837         if (!track->vos_data)
3838             return AVERROR(ENOMEM);
3839         for (i = 0; i < 16; i++) {
3840             AV_WB32(track->vos_data + i * 4, palette[i]);
3841         }
3842         track->vos_len = 16 * 4;
3843     }
3844     st->codec->width = width;
3845     st->codec->height = track->height = height;
3846
3847     return 0;
3848 }
3849
3850 static int mov_write_header(AVFormatContext *s)
3851 {
3852     AVIOContext *pb = s->pb;
3853     MOVMuxContext *mov = s->priv_data;
3854     AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
3855     int i, ret, hint_track = 0, tmcd_track = 0;
3856
3857     /* Default mode == MP4 */
3858     mov->mode = MODE_MP4;
3859
3860     if (s->oformat != NULL) {
3861         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
3862         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
3863         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
3864         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
3865         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
3866         else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
3867         else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
3868     }
3869
3870     for (i = 0; i < s->nb_streams; i++)
3871         if (s->streams[i]->codec->flags & CODEC_FLAG_BITEXACT)
3872             mov->exact = 1;
3873
3874     /* Set the FRAGMENT flag if any of the fragmentation methods are
3875      * enabled. */
3876     if (mov->max_fragment_duration || mov->max_fragment_size ||
3877         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
3878                       FF_MOV_FLAG_FRAG_KEYFRAME |
3879                       FF_MOV_FLAG_FRAG_CUSTOM))
3880         mov->flags |= FF_MOV_FLAG_FRAGMENT;
3881
3882     /* Set other implicit flags immediately */
3883     if (mov->mode == MODE_ISM)
3884         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
3885                       FF_MOV_FLAG_FRAGMENT;
3886
3887     /* faststart: moov at the beginning of the file, if supported */
3888     if (mov->flags & FF_MOV_FLAG_FASTSTART) {
3889         if ((mov->flags & FF_MOV_FLAG_FRAGMENT) ||
3890             (s->flags & AVFMT_FLAG_CUSTOM_IO)) {
3891             av_log(s, AV_LOG_WARNING, "The faststart flag is incompatible "
3892                    "with fragmentation and custom IO, disabling faststart\n");
3893             mov->flags &= ~FF_MOV_FLAG_FASTSTART;
3894         } else
3895             mov->reserved_moov_size = -1;
3896     }
3897
3898     if (!supports_edts(mov) && s->avoid_negative_ts < 0) {
3899         s->avoid_negative_ts = 2;
3900     }
3901
3902     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
3903      * is enabled, we don't support non-seekable output at all. */
3904     if (!s->pb->seekable &&
3905         (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
3906         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
3907         return AVERROR(EINVAL);
3908     }
3909
3910     mov_write_ftyp_tag(pb,s);
3911     if (mov->mode == MODE_PSP) {
3912         int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
3913         for (i = 0; i < s->nb_streams; i++) {
3914             AVStream *st = s->streams[i];
3915             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3916                 video_streams_nb++;
3917             else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3918                 audio_streams_nb++;
3919             else
3920                 other_streams_nb++;
3921             }
3922
3923         if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
3924             av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3925             return AVERROR(EINVAL);
3926         }
3927         mov_write_uuidprof_tag(pb, s);
3928     }
3929
3930     mov->nb_streams = s->nb_streams;
3931     if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
3932         mov->chapter_track = mov->nb_streams++;
3933
3934     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
3935         /* Add hint tracks for each audio and video stream */
3936         hint_track = mov->nb_streams;
3937         for (i = 0; i < s->nb_streams; i++) {
3938             AVStream *st = s->streams[i];
3939             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3940                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3941                 mov->nb_streams++;
3942             }
3943         }
3944     }
3945
3946     if (mov->mode == MODE_MOV) {
3947         tmcd_track = mov->nb_streams;
3948
3949         /* +1 tmcd track for each video stream with a timecode */
3950         for (i = 0; i < s->nb_streams; i++) {
3951             AVStream *st = s->streams[i];
3952             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3953                 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
3954                 mov->nb_meta_tmcd++;
3955         }
3956
3957         /* check if there is already a tmcd track to remux */
3958         if (mov->nb_meta_tmcd) {
3959             for (i = 0; i < s->nb_streams; i++) {
3960                 AVStream *st = s->streams[i];
3961                 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
3962                     av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
3963                            "so timecode metadata are now ignored\n");
3964                     mov->nb_meta_tmcd = 0;
3965                 }
3966             }
3967         }
3968
3969         mov->nb_streams += mov->nb_meta_tmcd;
3970     }
3971
3972     // Reserve an extra stream for chapters for the case where chapters
3973     // are written in the trailer
3974     mov->tracks = av_mallocz((mov->nb_streams + 1) * sizeof(*mov->tracks));
3975     if (!mov->tracks)
3976         return AVERROR(ENOMEM);
3977
3978     for (i = 0; i < s->nb_streams; i++) {
3979         AVStream *st= s->streams[i];
3980         MOVTrack *track= &mov->tracks[i];
3981         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3982
3983         track->enc = st->codec;
3984         track->st = st;
3985         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
3986         if (track->language < 0)
3987             track->language = 0;
3988         track->mode = mov->mode;
3989         track->tag  = mov_find_codec_tag(s, track);
3990         if (!track->tag) {
3991             av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
3992                    "codec not currently supported in container\n",
3993                    avcodec_get_name(st->codec->codec_id), i);
3994             ret = AVERROR(EINVAL);
3995             goto error;
3996         }
3997         /* If hinting of this track is enabled by a later hint track,
3998          * this is updated. */
3999         track->hint_track = -1;
4000         track->start_dts  = AV_NOPTS_VALUE;
4001         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4002             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
4003                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
4004                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
4005                 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
4006                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
4007                     ret = AVERROR(EINVAL);
4008                     goto error;
4009                 }
4010                 track->height = track->tag >> 24 == 'n' ? 486 : 576;
4011             }
4012             if (mov->video_track_timescale) {
4013                 track->timescale = mov->video_track_timescale;
4014             } else {
4015                 track->timescale = st->codec->time_base.den;
4016                 while(track->timescale < 10000)
4017                     track->timescale *= 2;
4018             }
4019             if (track->mode == MODE_MOV && track->timescale > 100000)
4020                 av_log(s, AV_LOG_WARNING,
4021                        "WARNING codec timebase is very high. If duration is too long,\n"
4022                        "file may not be playable by quicktime. Specify a shorter timebase\n"
4023                        "or choose different container.\n");
4024         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4025             track->timescale = st->codec->sample_rate;
4026             if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
4027                 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
4028                 track->audio_vbr = 1;
4029             }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
4030                      st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
4031                      st->codec->codec_id == AV_CODEC_ID_ILBC){
4032                 if (!st->codec->block_align) {
4033                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
4034                     ret = AVERROR(EINVAL);
4035                     goto error;
4036                 }
4037                 track->sample_size = st->codec->block_align;
4038             }else if (st->codec->frame_size > 1){ /* assume compressed audio */
4039                 track->audio_vbr = 1;
4040             }else{
4041                 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
4042             }
4043             if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
4044                 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
4045                 track->audio_vbr = 1;
4046             }
4047             if (track->mode != MODE_MOV &&
4048                 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
4049                 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
4050                        i, track->enc->sample_rate);
4051                 ret = AVERROR(EINVAL);
4052                 goto error;
4053             }
4054         } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4055             track->timescale = st->codec->time_base.den;
4056         } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
4057             track->timescale = st->codec->time_base.den;
4058         } else {
4059             track->timescale = MOV_TIMESCALE;
4060         }
4061         if (!track->height)
4062             track->height = st->codec->height;
4063         /* The ism specific timescale isn't mandatory, but is assumed by
4064          * some tools, such as mp4split. */
4065         if (mov->mode == MODE_ISM)
4066             track->timescale = 10000000;
4067
4068         avpriv_set_pts_info(st, 64, 1, track->timescale);
4069
4070         /* copy extradata if it exists */
4071         if (st->codec->extradata_size) {
4072             if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
4073                 mov_create_dvd_sub_decoder_specific_info(track, st);
4074             else {
4075                 track->vos_len  = st->codec->extradata_size;
4076                 track->vos_data = av_malloc(track->vos_len);
4077                 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
4078             }
4079         }
4080     }
4081
4082     enable_tracks(s);
4083
4084
4085     if (mov->reserved_moov_size){
4086         mov->reserved_moov_pos= avio_tell(pb);
4087         if (mov->reserved_moov_size > 0)
4088             avio_skip(pb, mov->reserved_moov_size);
4089     }
4090
4091     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4092         /* If no fragmentation options have been set, set a default. */
4093         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
4094                             FF_MOV_FLAG_FRAG_CUSTOM)) &&
4095             !mov->max_fragment_duration && !mov->max_fragment_size)
4096             mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
4097     } else {
4098         if (mov->flags & FF_MOV_FLAG_FASTSTART)
4099             mov->reserved_moov_pos = avio_tell(pb);
4100         mov_write_mdat_tag(pb, mov);
4101     }
4102
4103     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
4104         mov->time = ff_iso8601_to_unix_time(t->value);
4105     if (mov->time)
4106         mov->time += 0x7C25B080; // 1970 based -> 1904 based
4107
4108     if (mov->chapter_track)
4109         if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4110             goto error;
4111
4112     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4113         /* Initialize the hint tracks for each audio and video stream */
4114         for (i = 0; i < s->nb_streams; i++) {
4115             AVStream *st = s->streams[i];
4116             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4117                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4118                 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
4119                     goto error;
4120                 hint_track++;
4121             }
4122         }
4123     }
4124
4125     if (mov->nb_meta_tmcd) {
4126         /* Initialize the tmcd tracks */
4127         for (i = 0; i < s->nb_streams; i++) {
4128             AVStream *st = s->streams[i];
4129             t = global_tcr;
4130
4131             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4132                 if (!t)
4133                     t = av_dict_get(st->metadata, "timecode", NULL, 0);
4134                 if (!t)
4135                     continue;
4136                 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
4137                     goto error;
4138                 tmcd_track++;
4139             }
4140         }
4141     }
4142
4143     avio_flush(pb);
4144
4145     if (mov->flags & FF_MOV_FLAG_ISML)
4146         mov_write_isml_manifest(pb, mov);
4147
4148     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4149         mov_write_moov_tag(pb, mov, s);
4150         mov->fragments++;
4151     }
4152
4153     return 0;
4154  error:
4155     mov_free(s);
4156     return ret;
4157 }
4158
4159 static int get_moov_size(AVFormatContext *s)
4160 {
4161     int ret;
4162     AVIOContext *moov_buf;
4163     MOVMuxContext *mov = s->priv_data;
4164
4165     if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
4166         return ret;
4167     mov_write_moov_tag(moov_buf, mov, s);
4168     return ffio_close_null_buf(moov_buf);
4169 }
4170
4171 /*
4172  * This function gets the moov size if moved to the top of the file: the chunk
4173  * offset table can switch between stco (32-bit entries) to co64 (64-bit
4174  * entries) when the moov is moved to the beginning, so the size of the moov
4175  * would change. It also updates the chunk offset tables.
4176  */
4177 static int compute_moov_size(AVFormatContext *s)
4178 {
4179     int i, moov_size, moov_size2;
4180     MOVMuxContext *mov = s->priv_data;
4181
4182     moov_size = get_moov_size(s);
4183     if (moov_size < 0)
4184         return moov_size;
4185
4186     for (i = 0; i < mov->nb_streams; i++)
4187         mov->tracks[i].data_offset += moov_size;
4188
4189     moov_size2 = get_moov_size(s);
4190     if (moov_size2 < 0)
4191         return moov_size2;
4192
4193     /* if the size changed, we just switched from stco to co64 and need to
4194      * update the offsets */
4195     if (moov_size2 != moov_size)
4196         for (i = 0; i < mov->nb_streams; i++)
4197             mov->tracks[i].data_offset += moov_size2 - moov_size;
4198
4199     return moov_size2;
4200 }
4201
4202 static int shift_data(AVFormatContext *s)
4203 {
4204     int ret = 0, moov_size;
4205     MOVMuxContext *mov = s->priv_data;
4206     int64_t pos, pos_end = avio_tell(s->pb);
4207     uint8_t *buf, *read_buf[2];
4208     int read_buf_id = 0;
4209     int read_size[2];
4210     AVIOContext *read_pb;
4211
4212     moov_size = compute_moov_size(s);
4213     if (moov_size < 0)
4214         return moov_size;
4215
4216     buf = av_malloc(moov_size * 2);
4217     if (!buf)
4218         return AVERROR(ENOMEM);
4219     read_buf[0] = buf;
4220     read_buf[1] = buf + moov_size;
4221
4222     /* Shift the data: the AVIO context of the output can only be used for
4223      * writing, so we re-open the same output, but for reading. It also avoids
4224      * a read/seek/write/seek back and forth. */
4225     avio_flush(s->pb);
4226     ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
4227     if (ret < 0) {
4228         av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
4229                "the second pass (faststart)\n", s->filename);
4230         goto end;
4231     }
4232
4233     /* mark the end of the shift to up to the last data we wrote, and get ready
4234      * for writing */
4235     pos_end = avio_tell(s->pb);
4236     avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
4237
4238     /* start reading at where the new moov will be placed */
4239     avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
4240     pos = avio_tell(read_pb);
4241
4242 #define READ_BLOCK do {                                                             \
4243     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size);  \
4244     read_buf_id ^= 1;                                                               \
4245 } while (0)
4246
4247     /* shift data by chunk of at most moov_size */
4248     READ_BLOCK;
4249     do {
4250         int n;
4251         READ_BLOCK;
4252         n = read_size[read_buf_id];
4253         if (n <= 0)
4254             break;
4255         avio_write(s->pb, read_buf[read_buf_id], n);
4256         pos += n;
4257     } while (pos < pos_end);
4258     avio_close(read_pb);
4259
4260 end:
4261     av_free(buf);
4262     return ret;
4263 }
4264
4265 static int mov_write_trailer(AVFormatContext *s)
4266 {
4267     MOVMuxContext *mov = s->priv_data;
4268     AVIOContext *pb = s->pb;
4269     int res = 0;
4270     int i;
4271     int64_t moov_pos;
4272
4273     /*
4274      * Before actually writing the trailer, make sure that there are no
4275      * dangling subtitles, that need a terminating sample.
4276      */
4277     for (i = 0; i < mov->nb_streams; i++) {
4278         MOVTrack *trk = &mov->tracks[i];
4279         if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4280             !trk->last_sample_is_subtitle_end) {
4281             mov_write_subtitle_end_packet(s, i, trk->track_duration);
4282             trk->last_sample_is_subtitle_end = 1;
4283         }
4284     }
4285
4286     // If there were no chapters when the header was written, but there
4287     // are chapters now, write them in the trailer.  This only works
4288     // when we are not doing fragments.
4289     if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4290         if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
4291             mov->chapter_track = mov->nb_streams++;
4292             if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4293                 goto error;
4294         }
4295     }
4296
4297     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4298         moov_pos = avio_tell(pb);
4299
4300         /* Write size of mdat tag */
4301         if (mov->mdat_size + 8 <= UINT32_MAX) {
4302             avio_seek(pb, mov->mdat_pos, SEEK_SET);
4303             avio_wb32(pb, mov->mdat_size + 8);
4304         } else {
4305             /* overwrite 'wide' placeholder atom */
4306             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
4307             /* special value: real atom size will be 64 bit value after
4308              * tag field */
4309             avio_wb32(pb, 1);
4310             ffio_wfourcc(pb, "mdat");
4311             avio_wb64(pb, mov->mdat_size + 16);
4312         }
4313         avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
4314
4315         if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4316             av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
4317             res = shift_data(s);
4318             if (res == 0) {
4319                 avio_seek(s->pb, mov->reserved_moov_pos, SEEK_SET);
4320                 mov_write_moov_tag(pb, mov, s);
4321             }
4322         } else if (mov->reserved_moov_size > 0) {
4323             int64_t size;
4324             mov_write_moov_tag(pb, mov, s);
4325             size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
4326             if (size < 8){
4327                 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
4328                 return -1;
4329             }
4330             avio_wb32(pb, size);
4331             ffio_wfourcc(pb, "free");
4332             for (i = 0; i < size; i++)
4333                 avio_w8(pb, 0);
4334             avio_seek(pb, moov_pos, SEEK_SET);
4335         } else {
4336             mov_write_moov_tag(pb, mov, s);
4337         }
4338     } else {
4339         mov_flush_fragment(s);
4340         mov_write_mfra_tag(pb, mov);
4341     }
4342
4343     for (i = 0; i < mov->nb_streams; i++) {
4344         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
4345             mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
4346             int64_t off = avio_tell(pb);
4347             uint8_t buf[7];
4348             if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
4349                 avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
4350                 avio_write(pb, buf, 7);
4351                 avio_seek(pb, off, SEEK_SET);
4352             }
4353         }
4354     }
4355
4356 error:
4357     mov_free(s);
4358
4359     return res;
4360 }
4361
4362 #if CONFIG_MOV_MUXER
4363 MOV_CLASS(mov)
4364 AVOutputFormat ff_mov_muxer = {
4365     .name              = "mov",
4366     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4367     .extensions        = "mov",
4368     .priv_data_size    = sizeof(MOVMuxContext),
4369     .audio_codec       = AV_CODEC_ID_AAC,
4370     .video_codec       = CONFIG_LIBX264_ENCODER ?
4371                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4372     .write_header      = mov_write_header,
4373     .write_packet      = mov_write_packet,
4374     .write_trailer     = mov_write_trailer,
4375     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4376     .codec_tag         = (const AVCodecTag* const []){
4377         ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
4378     },
4379     .priv_class        = &mov_muxer_class,
4380 };
4381 #endif
4382 #if CONFIG_TGP_MUXER
4383 MOV_CLASS(tgp)
4384 AVOutputFormat ff_tgp_muxer = {
4385     .name              = "3gp",
4386     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
4387     .extensions        = "3gp",
4388     .priv_data_size    = sizeof(MOVMuxContext),
4389     .audio_codec       = AV_CODEC_ID_AMR_NB,
4390     .video_codec       = AV_CODEC_ID_H263,
4391     .write_header      = mov_write_header,
4392     .write_packet      = mov_write_packet,
4393     .write_trailer     = mov_write_trailer,
4394     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4395     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4396     .priv_class        = &tgp_muxer_class,
4397 };
4398 #endif
4399 #if CONFIG_MP4_MUXER
4400 MOV_CLASS(mp4)
4401 AVOutputFormat ff_mp4_muxer = {
4402     .name              = "mp4",
4403     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
4404     .mime_type         = "application/mp4",
4405     .extensions        = "mp4",
4406     .priv_data_size    = sizeof(MOVMuxContext),
4407     .audio_codec       = AV_CODEC_ID_AAC,
4408     .video_codec       = CONFIG_LIBX264_ENCODER ?
4409                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4410     .write_header      = mov_write_header,
4411     .write_packet      = mov_write_packet,
4412     .write_trailer     = mov_write_trailer,
4413     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4414     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4415     .priv_class        = &mp4_muxer_class,
4416 };
4417 #endif
4418 #if CONFIG_PSP_MUXER
4419 MOV_CLASS(psp)
4420 AVOutputFormat ff_psp_muxer = {
4421     .name              = "psp",
4422     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
4423     .extensions        = "mp4,psp",
4424     .priv_data_size    = sizeof(MOVMuxContext),
4425     .audio_codec       = AV_CODEC_ID_AAC,
4426     .video_codec       = CONFIG_LIBX264_ENCODER ?
4427                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4428     .write_header      = mov_write_header,
4429     .write_packet      = mov_write_packet,
4430     .write_trailer     = mov_write_trailer,
4431     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4432     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4433     .priv_class        = &psp_muxer_class,
4434 };
4435 #endif
4436 #if CONFIG_TG2_MUXER
4437 MOV_CLASS(tg2)
4438 AVOutputFormat ff_tg2_muxer = {
4439     .name              = "3g2",
4440     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
4441     .extensions        = "3g2",
4442     .priv_data_size    = sizeof(MOVMuxContext),
4443     .audio_codec       = AV_CODEC_ID_AMR_NB,
4444     .video_codec       = AV_CODEC_ID_H263,
4445     .write_header      = mov_write_header,
4446     .write_packet      = mov_write_packet,
4447     .write_trailer     = mov_write_trailer,
4448     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4449     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4450     .priv_class        = &tg2_muxer_class,
4451 };
4452 #endif
4453 #if CONFIG_IPOD_MUXER
4454 MOV_CLASS(ipod)
4455 AVOutputFormat ff_ipod_muxer = {
4456     .name              = "ipod",
4457     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
4458     .mime_type         = "application/mp4",
4459     .extensions        = "m4v,m4a",
4460     .priv_data_size    = sizeof(MOVMuxContext),
4461     .audio_codec       = AV_CODEC_ID_AAC,
4462     .video_codec       = AV_CODEC_ID_H264,
4463     .write_header      = mov_write_header,
4464     .write_packet      = mov_write_packet,
4465     .write_trailer     = mov_write_trailer,
4466     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4467     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
4468     .priv_class        = &ipod_muxer_class,
4469 };
4470 #endif
4471 #if CONFIG_ISMV_MUXER
4472 MOV_CLASS(ismv)
4473 AVOutputFormat ff_ismv_muxer = {
4474     .name              = "ismv",
4475     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
4476     .mime_type         = "application/mp4",
4477     .extensions        = "ismv,isma",
4478     .priv_data_size    = sizeof(MOVMuxContext),
4479     .audio_codec       = AV_CODEC_ID_AAC,
4480     .video_codec       = AV_CODEC_ID_H264,
4481     .write_header      = mov_write_header,
4482     .write_packet      = mov_write_packet,
4483     .write_trailer     = mov_write_trailer,
4484     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4485     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4486     .priv_class        = &ismv_muxer_class,
4487 };
4488 #endif
4489 #if CONFIG_F4V_MUXER
4490 MOV_CLASS(f4v)
4491 AVOutputFormat ff_f4v_muxer = {
4492     .name              = "f4v",
4493     .long_name         = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
4494     .mime_type         = "application/f4v",
4495     .extensions        = "f4v",
4496     .priv_data_size    = sizeof(MOVMuxContext),
4497     .audio_codec       = AV_CODEC_ID_AAC,
4498     .video_codec       = AV_CODEC_ID_H264,
4499     .write_header      = mov_write_header,
4500     .write_packet      = mov_write_packet,
4501     .write_trailer     = mov_write_trailer,
4502     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
4503     .codec_tag         = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
4504     .priv_class        = &f4v_muxer_class,
4505 };
4506 #endif