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