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