]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
Merge commit '96138e8c8da4b9397e627c934a33c22988d1192b'
[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')) hdlr_type = "sbtl";
1593             else if (track->tag == MKTAG('m','p','4','s')) hdlr_type = "subp";
1594             else                                      hdlr_type = "text";
1595             descr = "SubtitleHandler";
1596             }
1597         } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1598             hdlr_type = "hint";
1599             descr     = "HintHandler";
1600         } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1601             hdlr_type = "tmcd";
1602             descr = "TimeCodeHandler";
1603         } else {
1604             char tag_buf[32];
1605             av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
1606                                     track->enc->codec_tag);
1607
1608             av_log(track->enc, AV_LOG_WARNING,
1609                    "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
1610                    tag_buf, track->enc->codec_tag);
1611         }
1612     }
1613
1614     avio_wb32(pb, 0); /* size */
1615     ffio_wfourcc(pb, "hdlr");
1616     avio_wb32(pb, 0); /* Version & flags */
1617     avio_write(pb, hdlr, 4); /* handler */
1618     ffio_wfourcc(pb, hdlr_type); /* handler type */
1619     avio_wb32(pb, 0); /* reserved */
1620     avio_wb32(pb, 0); /* reserved */
1621     avio_wb32(pb, 0); /* reserved */
1622     if (!track || track->mode == MODE_MOV)
1623         avio_w8(pb, strlen(descr)); /* pascal string */
1624     avio_write(pb, descr, strlen(descr)); /* handler description */
1625     if (track && track->mode != MODE_MOV)
1626         avio_w8(pb, 0); /* c string */
1627     return update_size(pb, pos);
1628 }
1629
1630 static int mov_write_hmhd_tag(AVIOContext *pb)
1631 {
1632     /* This atom must be present, but leaving the values at zero
1633      * seems harmless. */
1634     avio_wb32(pb, 28); /* size */
1635     ffio_wfourcc(pb, "hmhd");
1636     avio_wb32(pb, 0); /* version, flags */
1637     avio_wb16(pb, 0); /* maxPDUsize */
1638     avio_wb16(pb, 0); /* avgPDUsize */
1639     avio_wb32(pb, 0); /* maxbitrate */
1640     avio_wb32(pb, 0); /* avgbitrate */
1641     avio_wb32(pb, 0); /* reserved */
1642     return 28;
1643 }
1644
1645 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1646 {
1647     int64_t pos = avio_tell(pb);
1648     avio_wb32(pb, 0); /* size */
1649     ffio_wfourcc(pb, "minf");
1650     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1651         mov_write_vmhd_tag(pb);
1652     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1653         mov_write_smhd_tag(pb);
1654     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1655         if (track->tag == MKTAG('t','e','x','t') || track->tag == MKTAG('c','6','0','8')) {
1656             mov_write_gmhd_tag(pb, track);
1657         } else {
1658             mov_write_nmhd_tag(pb);
1659         }
1660     } else if (track->tag == MKTAG('r','t','p',' ')) {
1661         mov_write_hmhd_tag(pb);
1662     } else if (track->tag == MKTAG('t','m','c','d')) {
1663         mov_write_gmhd_tag(pb, track);
1664     }
1665     if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1666         mov_write_hdlr_tag(pb, NULL);
1667     mov_write_dinf_tag(pb);
1668     mov_write_stbl_tag(pb, track);
1669     return update_size(pb, pos);
1670 }
1671
1672 static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1673 {
1674     int version = track->track_duration < INT32_MAX ? 0 : 1;
1675
1676     if (track->mode == MODE_ISM)
1677         version = 1;
1678
1679     (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1680     ffio_wfourcc(pb, "mdhd");
1681     avio_w8(pb, version);
1682     avio_wb24(pb, 0); /* flags */
1683     if (version == 1) {
1684         avio_wb64(pb, track->time);
1685         avio_wb64(pb, track->time);
1686     } else {
1687         avio_wb32(pb, track->time); /* creation time */
1688         avio_wb32(pb, track->time); /* modification time */
1689     }
1690     avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1691     if (!track->entry)
1692         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1693     else
1694         (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
1695     avio_wb16(pb, track->language); /* language */
1696     avio_wb16(pb, 0); /* reserved (quality) */
1697
1698     if (version != 0 && track->mode == MODE_MOV) {
1699         av_log(NULL, AV_LOG_ERROR,
1700                "FATAL error, file duration too long for timebase, this file will not be\n"
1701                "playable with quicktime. Choose a different timebase or a different\n"
1702                "container format\n");
1703     }
1704
1705     return 32;
1706 }
1707
1708 static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1709 {
1710     int64_t pos = avio_tell(pb);
1711     avio_wb32(pb, 0); /* size */
1712     ffio_wfourcc(pb, "mdia");
1713     mov_write_mdhd_tag(pb, track);
1714     mov_write_hdlr_tag(pb, track);
1715     mov_write_minf_tag(pb, track);
1716     return update_size(pb, pos);
1717 }
1718
1719 /* transformation matrix
1720      |a  b  u|
1721      |c  d  v|
1722      |tx ty w| */
1723 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
1724                          int16_t d, int16_t tx, int16_t ty)
1725 {
1726     avio_wb32(pb, a << 16);  /* 16.16 format */
1727     avio_wb32(pb, b << 16);  /* 16.16 format */
1728     avio_wb32(pb, 0);        /* u in 2.30 format */
1729     avio_wb32(pb, c << 16);  /* 16.16 format */
1730     avio_wb32(pb, d << 16);  /* 16.16 format */
1731     avio_wb32(pb, 0);        /* v in 2.30 format */
1732     avio_wb32(pb, tx << 16); /* 16.16 format */
1733     avio_wb32(pb, ty << 16); /* 16.16 format */
1734     avio_wb32(pb, 1 << 30);  /* w in 2.30 format */
1735 }
1736
1737 static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1738 {
1739     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1740                                       track->timescale, AV_ROUND_UP);
1741     int version = duration < INT32_MAX ? 0 : 1;
1742     int rotation = 0;
1743
1744     if (track->mode == MODE_ISM)
1745         version = 1;
1746
1747     (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1748     ffio_wfourcc(pb, "tkhd");
1749     avio_w8(pb, version);
1750     avio_wb24(pb, (track->flags & MOV_TRACK_ENABLED) ?
1751                   MOV_TKHD_FLAG_ENABLED | MOV_TKHD_FLAG_IN_MOVIE :
1752                   MOV_TKHD_FLAG_IN_MOVIE);
1753     if (version == 1) {
1754         avio_wb64(pb, track->time);
1755         avio_wb64(pb, track->time);
1756     } else {
1757         avio_wb32(pb, track->time); /* creation time */
1758         avio_wb32(pb, track->time); /* modification time */
1759     }
1760     avio_wb32(pb, track->track_id); /* track-id */
1761     avio_wb32(pb, 0); /* reserved */
1762     if (!track->entry)
1763         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1764     else
1765         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1766
1767     avio_wb32(pb, 0); /* reserved */
1768     avio_wb32(pb, 0); /* reserved */
1769     avio_wb16(pb, 0); /* layer */
1770     avio_wb16(pb, st ? st->codec->codec_type : 0); /* alternate group) */
1771     /* Volume, only for audio */
1772     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1773         avio_wb16(pb, 0x0100);
1774     else
1775         avio_wb16(pb, 0);
1776     avio_wb16(pb, 0); /* reserved */
1777
1778     /* Matrix structure */
1779     if (st && st->metadata) {
1780         AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
1781         rotation = (rot && rot->value) ? atoi(rot->value) : 0;
1782     }
1783     if (rotation == 90) {
1784         write_matrix(pb,  0,  1, -1,  0, track->enc->height, 0);
1785     } else if (rotation == 180) {
1786         write_matrix(pb, -1,  0,  0, -1, track->enc->width, track->enc->height);
1787     } else if (rotation == 270) {
1788         write_matrix(pb,  0, -1,  1,  0, 0, track->enc->width);
1789     } else {
1790         write_matrix(pb,  1,  0,  0,  1, 0, 0);
1791     }
1792     /* Track width and height, for visual only */
1793     if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1794                track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1795         if (track->mode == MODE_MOV) {
1796             avio_wb32(pb, track->enc->width << 16);
1797             avio_wb32(pb, track->height << 16);
1798         } else {
1799             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1800             if (!sample_aspect_ratio || track->height != track->enc->height)
1801                 sample_aspect_ratio = 1;
1802             avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
1803             avio_wb32(pb, track->height * 0x10000);
1804         }
1805     } else {
1806         avio_wb32(pb, 0);
1807         avio_wb32(pb, 0);
1808     }
1809     return 0x5c;
1810 }
1811
1812 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1813 {
1814     int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1815                                track->enc->sample_aspect_ratio.den);
1816
1817     int64_t pos = avio_tell(pb);
1818
1819     avio_wb32(pb, 0); /* size */
1820     ffio_wfourcc(pb, "tapt");
1821
1822     avio_wb32(pb, 20);
1823     ffio_wfourcc(pb, "clef");
1824     avio_wb32(pb, 0);
1825     avio_wb32(pb, width << 16);
1826     avio_wb32(pb, track->enc->height << 16);
1827
1828     avio_wb32(pb, 20);
1829     ffio_wfourcc(pb, "prof");
1830     avio_wb32(pb, 0);
1831     avio_wb32(pb, width << 16);
1832     avio_wb32(pb, track->enc->height << 16);
1833
1834     avio_wb32(pb, 20);
1835     ffio_wfourcc(pb, "enof");
1836     avio_wb32(pb, 0);
1837     avio_wb32(pb, track->enc->width << 16);
1838     avio_wb32(pb, track->enc->height << 16);
1839
1840     return update_size(pb, pos);
1841 }
1842
1843 // This box seems important for the psp playback ... without it the movie seems to hang
1844 static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1845 {
1846     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1847                                       track->timescale, AV_ROUND_UP);
1848     int version = duration < INT32_MAX ? 0 : 1;
1849     int entry_size, entry_count, size;
1850     int64_t delay, start_ct = track->cluster[0].cts;
1851     delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
1852                            track->timescale, AV_ROUND_DOWN);
1853     version |= delay < INT32_MAX ? 0 : 1;
1854
1855     entry_size = (version == 1) ? 20 : 12;
1856     entry_count = 1 + (delay > 0);
1857     size = 24 + entry_count * entry_size;
1858
1859     /* write the atom data */
1860     avio_wb32(pb, size);
1861     ffio_wfourcc(pb, "edts");
1862     avio_wb32(pb, size - 8);
1863     ffio_wfourcc(pb, "elst");
1864     avio_w8(pb, version);
1865     avio_wb24(pb, 0); /* flags */
1866
1867     avio_wb32(pb, entry_count);
1868     if (delay > 0) { /* add an empty edit to delay presentation */
1869         if (version == 1) {
1870             avio_wb64(pb, delay);
1871             avio_wb64(pb, -1);
1872         } else {
1873             avio_wb32(pb, delay);
1874             avio_wb32(pb, -1);
1875         }
1876         avio_wb32(pb, 0x00010000);
1877     } else {
1878         av_assert0(av_rescale_rnd(track->cluster[0].dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
1879         start_ct  = -FFMIN(track->cluster[0].dts, 0); //FFMIN needed due to rounding
1880         duration += delay;
1881     }
1882
1883     /* duration */
1884     if (version == 1) {
1885         avio_wb64(pb, duration);
1886         avio_wb64(pb, start_ct);
1887     } else {
1888         avio_wb32(pb, duration);
1889         avio_wb32(pb, start_ct);
1890     }
1891     avio_wb32(pb, 0x00010000);
1892     return size;
1893 }
1894
1895 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1896 {
1897     avio_wb32(pb, 20);   // size
1898     ffio_wfourcc(pb, "tref");
1899     avio_wb32(pb, 12);   // size (subatom)
1900     avio_wl32(pb, track->tref_tag);
1901     avio_wb32(pb, track->tref_id);
1902     return 20;
1903 }
1904
1905 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1906 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1907 {
1908     avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1909     ffio_wfourcc(pb, "uuid");
1910     ffio_wfourcc(pb, "USMT");
1911     avio_wb32(pb, 0x21d24fce);
1912     avio_wb32(pb, 0xbb88695c);
1913     avio_wb32(pb, 0xfac9c740);
1914     avio_wb32(pb, 0x1c);     // another size here!
1915     ffio_wfourcc(pb, "MTDT");
1916     avio_wb32(pb, 0x00010012);
1917     avio_wb32(pb, 0x0a);
1918     avio_wb32(pb, 0x55c40000);
1919     avio_wb32(pb, 0x1);
1920     avio_wb32(pb, 0x0);
1921     return 0x34;
1922 }
1923
1924 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
1925 {
1926     AVFormatContext *ctx = track->rtp_ctx;
1927     char buf[1000] = "";
1928     int len;
1929
1930     ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
1931                        NULL, NULL, 0, 0, ctx);
1932     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
1933     len = strlen(buf);
1934
1935     avio_wb32(pb, len + 24);
1936     ffio_wfourcc(pb, "udta");
1937     avio_wb32(pb, len + 16);
1938     ffio_wfourcc(pb, "hnti");
1939     avio_wb32(pb, len + 8);
1940     ffio_wfourcc(pb, "sdp ");
1941     avio_write(pb, buf, len);
1942     return len + 24;
1943 }
1944
1945 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
1946                               MOVTrack *track, AVStream *st)
1947 {
1948     int64_t pos = avio_tell(pb);
1949     avio_wb32(pb, 0); /* size */
1950     ffio_wfourcc(pb, "trak");
1951     mov_write_tkhd_tag(pb, track, st);
1952     if (supports_edts(mov))
1953         mov_write_edts_tag(pb, track);  // PSP Movies and several other cases require edts box
1954     if (track->tref_tag)
1955         mov_write_tref_tag(pb, track);
1956     mov_write_mdia_tag(pb, track);
1957     if (track->mode == MODE_PSP)
1958         mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
1959     if (track->tag == MKTAG('r','t','p',' '))
1960         mov_write_udta_sdp(pb, track);
1961     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO && track->mode == MODE_MOV) {
1962         double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1963         if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio)
1964             mov_write_tapt_tag(pb, track);
1965     }
1966     return update_size(pb, pos);
1967 }
1968
1969 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1970 {
1971     int i, has_audio = 0, has_video = 0;
1972     int64_t pos = avio_tell(pb);
1973     int audio_profile = mov->iods_audio_profile;
1974     int video_profile = mov->iods_video_profile;
1975     for (i = 0; i < mov->nb_streams; i++) {
1976         if (mov->tracks[i].entry > 0) {
1977             has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
1978             has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
1979         }
1980     }
1981     if (audio_profile < 0)
1982         audio_profile = 0xFF - has_audio;
1983     if (video_profile < 0)
1984         video_profile = 0xFF - has_video;
1985     avio_wb32(pb, 0x0); /* size */
1986     ffio_wfourcc(pb, "iods");
1987     avio_wb32(pb, 0);    /* version & flags */
1988     put_descr(pb, 0x10, 7);
1989     avio_wb16(pb, 0x004f);
1990     avio_w8(pb, 0xff);
1991     avio_w8(pb, 0xff);
1992     avio_w8(pb, audio_profile);
1993     avio_w8(pb, video_profile);
1994     avio_w8(pb, 0xff);
1995     return update_size(pb, pos);
1996 }
1997
1998 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
1999 {
2000     avio_wb32(pb, 0x20); /* size */
2001     ffio_wfourcc(pb, "trex");
2002     avio_wb32(pb, 0);   /* version & flags */
2003     avio_wb32(pb, track->track_id); /* track ID */
2004     avio_wb32(pb, 1);   /* default sample description index */
2005     avio_wb32(pb, 0);   /* default sample duration */
2006     avio_wb32(pb, 0);   /* default sample size */
2007     avio_wb32(pb, 0);   /* default sample flags */
2008     return 0;
2009 }
2010
2011 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2012 {
2013     int64_t pos = avio_tell(pb);
2014     int i;
2015     avio_wb32(pb, 0x0); /* size */
2016     ffio_wfourcc(pb, "mvex");
2017     for (i = 0; i < mov->nb_streams; i++)
2018         mov_write_trex_tag(pb, &mov->tracks[i]);
2019     return update_size(pb, pos);
2020 }
2021
2022 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2023 {
2024     int max_track_id = 1, i;
2025     int64_t max_track_len_temp, max_track_len = 0;
2026     int version;
2027
2028     for (i = 0; i < mov->nb_streams; i++) {
2029         if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2030             max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2031                                                 MOV_TIMESCALE,
2032                                                 mov->tracks[i].timescale,
2033                                                 AV_ROUND_UP);
2034             if (max_track_len < max_track_len_temp)
2035                 max_track_len = max_track_len_temp;
2036             if (max_track_id < mov->tracks[i].track_id)
2037                 max_track_id = mov->tracks[i].track_id;
2038         }
2039     }
2040
2041     version = max_track_len < UINT32_MAX ? 0 : 1;
2042     (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
2043     ffio_wfourcc(pb, "mvhd");
2044     avio_w8(pb, version);
2045     avio_wb24(pb, 0); /* flags */
2046     if (version == 1) {
2047         avio_wb64(pb, mov->time);
2048         avio_wb64(pb, mov->time);
2049     } else {
2050         avio_wb32(pb, mov->time); /* creation time */
2051         avio_wb32(pb, mov->time); /* modification time */
2052     }
2053     avio_wb32(pb, MOV_TIMESCALE);
2054     (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2055
2056     avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2057     avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2058     avio_wb16(pb, 0); /* reserved */
2059     avio_wb32(pb, 0); /* reserved */
2060     avio_wb32(pb, 0); /* reserved */
2061
2062     /* Matrix structure */
2063     write_matrix(pb, 1, 0, 0, 1, 0, 0);
2064
2065     avio_wb32(pb, 0); /* reserved (preview time) */
2066     avio_wb32(pb, 0); /* reserved (preview duration) */
2067     avio_wb32(pb, 0); /* reserved (poster time) */
2068     avio_wb32(pb, 0); /* reserved (selection time) */
2069     avio_wb32(pb, 0); /* reserved (selection duration) */
2070     avio_wb32(pb, 0); /* reserved (current time) */
2071     avio_wb32(pb, max_track_id + 1); /* Next track id */
2072     return 0x6c;
2073 }
2074
2075 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2076                                      AVFormatContext *s)
2077 {
2078     avio_wb32(pb, 33); /* size */
2079     ffio_wfourcc(pb, "hdlr");
2080     avio_wb32(pb, 0);
2081     avio_wb32(pb, 0);
2082     ffio_wfourcc(pb, "mdir");
2083     ffio_wfourcc(pb, "appl");
2084     avio_wb32(pb, 0);
2085     avio_wb32(pb, 0);
2086     avio_w8(pb, 0);
2087     return 33;
2088 }
2089
2090 /* helper function to write a data tag with the specified string as data */
2091 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2092 {
2093     if (long_style) {
2094         int size = 16 + strlen(data);
2095         avio_wb32(pb, size); /* size */
2096         ffio_wfourcc(pb, "data");
2097         avio_wb32(pb, 1);
2098         avio_wb32(pb, 0);
2099         avio_write(pb, data, strlen(data));
2100         return size;
2101     } else {
2102         if (!lang)
2103             lang = ff_mov_iso639_to_lang("und", 1);
2104         avio_wb16(pb, strlen(data)); /* string length */
2105         avio_wb16(pb, lang);
2106         avio_write(pb, data, strlen(data));
2107         return strlen(data) + 4;
2108     }
2109 }
2110
2111 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2112                                 const char *value, int lang, int long_style)
2113 {
2114     int size = 0;
2115     if (value && value[0]) {
2116         int64_t pos = avio_tell(pb);
2117         avio_wb32(pb, 0); /* size */
2118         ffio_wfourcc(pb, name);
2119         mov_write_string_data_tag(pb, value, lang, long_style);
2120         size = update_size(pb, pos);
2121     }
2122     return size;
2123 }
2124
2125 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2126                                      const char *name, const char *tag,
2127                                      int long_style)
2128 {
2129     int l, lang = 0, len, len2;
2130     AVDictionaryEntry *t, *t2 = NULL;
2131     char tag2[16];
2132
2133     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2134         return 0;
2135
2136     len = strlen(t->key);
2137     snprintf(tag2, sizeof(tag2), "%s-", tag);
2138     while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2139         len2 = strlen(t2->key);
2140         if (len2 == len + 4 && !strcmp(t->value, t2->value)
2141             && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2142             lang = l;
2143             break;
2144         }
2145     }
2146     return mov_write_string_tag(pb, name, t->value, lang, long_style);
2147 }
2148
2149 /* iTunes bpm number */
2150 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2151 {
2152     AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2153     int size = 0, tmpo = t ? atoi(t->value) : 0;
2154     if (tmpo) {
2155         size = 26;
2156         avio_wb32(pb, size);
2157         ffio_wfourcc(pb, "tmpo");
2158         avio_wb32(pb, size-8); /* size */
2159         ffio_wfourcc(pb, "data");
2160         avio_wb32(pb, 0x15);  //type specifier
2161         avio_wb32(pb, 0);
2162         avio_wb16(pb, tmpo);        // data
2163     }
2164     return size;
2165 }
2166
2167 /* iTunes track or disc number */
2168 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2169                               AVFormatContext *s, int disc)
2170 {
2171     AVDictionaryEntry *t = av_dict_get(s->metadata,
2172                                        disc ? "disc" : "track",
2173                                        NULL, 0);
2174     int size = 0, track = t ? atoi(t->value) : 0;
2175     if (track) {
2176         int tracks = 0;
2177         char *slash = strchr(t->value, '/');
2178         if (slash)
2179             tracks = atoi(slash + 1);
2180         avio_wb32(pb, 32); /* size */
2181         ffio_wfourcc(pb, disc ? "disk" : "trkn");
2182         avio_wb32(pb, 24); /* size */
2183         ffio_wfourcc(pb, "data");
2184         avio_wb32(pb, 0);        // 8 bytes empty
2185         avio_wb32(pb, 0);
2186         avio_wb16(pb, 0);        // empty
2187         avio_wb16(pb, track);    // track / disc number
2188         avio_wb16(pb, tracks);   // total track / disc number
2189         avio_wb16(pb, 0);        // empty
2190         size = 32;
2191     }
2192     return size;
2193 }
2194
2195 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2196                                    const char *name, const char *tag,
2197                                    int len)
2198 {
2199     AVDictionaryEntry *t = NULL;
2200     uint8_t num;
2201     int size = 24 + len;
2202
2203     if (len != 1 && len != 4)
2204         return -1;
2205
2206     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2207         return 0;
2208     num = atoi(t->value);
2209
2210     avio_wb32(pb, size);
2211     ffio_wfourcc(pb, name);
2212     avio_wb32(pb, size - 8);
2213     ffio_wfourcc(pb, "data");
2214     avio_wb32(pb, 0x15);
2215     avio_wb32(pb, 0);
2216     if (len==4) avio_wb32(pb, num);
2217     else        avio_w8 (pb, num);
2218
2219     return size;
2220 }
2221
2222 /* iTunes meta data list */
2223 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2224                               AVFormatContext *s)
2225 {
2226     int64_t pos = avio_tell(pb);
2227     avio_wb32(pb, 0); /* size */
2228     ffio_wfourcc(pb, "ilst");
2229     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
2230     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
2231     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2232     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2233     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
2234     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
2235     if (!mov->exact &&
2236         !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2237         mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2238     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
2239     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
2240     mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2241     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2242     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
2243     mov_write_string_metadata(s, pb, "desc",    "description",1);
2244     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
2245     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
2246     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
2247     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
2248     mov_write_int8_metadata  (s, pb, "tves",    "episode_sort",4);
2249     mov_write_int8_metadata  (s, pb, "tvsn",    "season_number",4);
2250     mov_write_int8_metadata  (s, pb, "stik",    "media_type",1);
2251     mov_write_int8_metadata  (s, pb, "hdvd",    "hd_video",  1);
2252     mov_write_int8_metadata  (s, pb, "pgap",    "gapless_playback",1);
2253     mov_write_int8_metadata  (s, pb, "cpil",    "compilation", 1);
2254     mov_write_trkn_tag(pb, mov, s, 0); // track number
2255     mov_write_trkn_tag(pb, mov, s, 1); // disc number
2256     mov_write_tmpo_tag(pb, s);
2257     return update_size(pb, pos);
2258 }
2259
2260 /* iTunes meta data tag */
2261 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2262                               AVFormatContext *s)
2263 {
2264     int size = 0;
2265     int64_t pos = avio_tell(pb);
2266     avio_wb32(pb, 0); /* size */
2267     ffio_wfourcc(pb, "meta");
2268     avio_wb32(pb, 0);
2269     mov_write_itunes_hdlr_tag(pb, mov, s);
2270     mov_write_ilst_tag(pb, mov, s);
2271     size = update_size(pb, pos);
2272     return size;
2273 }
2274
2275 static int utf8len(const uint8_t *b)
2276 {
2277     int len = 0;
2278     int val;
2279     while (*b) {
2280         GET_UTF8(val, *b++, return -1;)
2281         len++;
2282     }
2283     return len;
2284 }
2285
2286 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2287 {
2288     int val;
2289     while (*b) {
2290         GET_UTF8(val, *b++, return -1;)
2291         avio_wb16(pb, val);
2292     }
2293     avio_wb16(pb, 0x00);
2294     return 0;
2295 }
2296
2297 static uint16_t language_code(const char *str)
2298 {
2299     return (((str[0] - 0x60) & 0x1F) << 10) +
2300            (((str[1] - 0x60) & 0x1F) <<  5) +
2301            (( str[2] - 0x60) & 0x1F);
2302 }
2303
2304 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2305                                   const char *tag, const char *str)
2306 {
2307     int64_t pos = avio_tell(pb);
2308     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2309     if (!t || !utf8len(t->value))
2310         return 0;
2311     avio_wb32(pb, 0);   /* size */
2312     ffio_wfourcc(pb, tag); /* type */
2313     avio_wb32(pb, 0);   /* version + flags */
2314     if (!strcmp(tag, "yrrc"))
2315         avio_wb16(pb, atoi(t->value));
2316     else {
2317         avio_wb16(pb, language_code("eng")); /* language */
2318         avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2319         if (!strcmp(tag, "albm") &&
2320             (t = av_dict_get(s->metadata, "track", NULL, 0)))
2321             avio_w8(pb, atoi(t->value));
2322     }
2323     return update_size(pb, pos);
2324 }
2325
2326 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2327 {
2328     int64_t pos = avio_tell(pb);
2329     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2330
2331     avio_wb32(pb, 0);            // size
2332     ffio_wfourcc(pb, "chpl");
2333     avio_wb32(pb, 0x01000000);   // version + flags
2334     avio_wb32(pb, 0);            // unknown
2335     avio_w8(pb, nb_chapters);
2336
2337     for (i = 0; i < nb_chapters; i++) {
2338         AVChapter *c = s->chapters[i];
2339         AVDictionaryEntry *t;
2340         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2341
2342         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2343             int len = FFMIN(strlen(t->value), 255);
2344             avio_w8(pb, len);
2345             avio_write(pb, t->value, len);
2346         } else
2347             avio_w8(pb, 0);
2348     }
2349     return update_size(pb, pos);
2350 }
2351
2352 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2353                               AVFormatContext *s)
2354 {
2355     AVIOContext *pb_buf;
2356     int ret, size;
2357     uint8_t *buf;
2358
2359     ret = avio_open_dyn_buf(&pb_buf);
2360     if (ret < 0)
2361         return ret;
2362
2363     if (mov->mode & MODE_3GP) {
2364         mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2365         mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2366         mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2367         mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2368         mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2369         mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2370         mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2371         mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2372     } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2373         mov_write_string_metadata(s, pb_buf, "\251ART", "artist",      0);
2374         mov_write_string_metadata(s, pb_buf, "\251nam", "title",       0);
2375         mov_write_string_metadata(s, pb_buf, "\251aut", "author",      0);
2376         mov_write_string_metadata(s, pb_buf, "\251alb", "album",       0);
2377         mov_write_string_metadata(s, pb_buf, "\251day", "date",        0);
2378         mov_write_string_metadata(s, pb_buf, "\251swr", "encoder",     0);
2379         // currently ignored by mov.c
2380         mov_write_string_metadata(s, pb_buf, "\251des", "comment",     0);
2381         // add support for libquicktime, this atom is also actually read by mov.c
2382         mov_write_string_metadata(s, pb_buf, "\251cmt", "comment",     0);
2383         mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);
2384         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);
2385     } else {
2386         /* iTunes meta data */
2387         mov_write_meta_tag(pb_buf, mov, s);
2388     }
2389
2390     if (s->nb_chapters)
2391         mov_write_chpl_tag(pb_buf, s);
2392
2393     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2394         avio_wb32(pb, size + 8);
2395         ffio_wfourcc(pb, "udta");
2396         avio_write(pb, buf, size);
2397     }
2398     av_free(buf);
2399
2400     return 0;
2401 }
2402
2403 static void mov_write_psp_udta_tag(AVIOContext *pb,
2404                                    const char *str, const char *lang, int type)
2405 {
2406     int len = utf8len(str) + 1;
2407     if (len <= 0)
2408         return;
2409     avio_wb16(pb, len * 2 + 10);        /* size */
2410     avio_wb32(pb, type);                /* type */
2411     avio_wb16(pb, language_code(lang)); /* language */
2412     avio_wb16(pb, 0x01);                /* ? */
2413     ascii_to_wc(pb, str);
2414 }
2415
2416 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2417 {
2418     MOVMuxContext *mov = s->priv_data;
2419     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2420     int64_t pos, pos2;
2421
2422     if (title) {
2423         pos = avio_tell(pb);
2424         avio_wb32(pb, 0); /* size placeholder*/
2425         ffio_wfourcc(pb, "uuid");
2426         ffio_wfourcc(pb, "USMT");
2427         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2428         avio_wb32(pb, 0xbb88695c);
2429         avio_wb32(pb, 0xfac9c740);
2430
2431         pos2 = avio_tell(pb);
2432         avio_wb32(pb, 0); /* size placeholder*/
2433         ffio_wfourcc(pb, "MTDT");
2434         avio_wb16(pb, 4);
2435
2436         // ?
2437         avio_wb16(pb, 0x0C);                 /* size */
2438         avio_wb32(pb, 0x0B);                 /* type */
2439         avio_wb16(pb, language_code("und")); /* language */
2440         avio_wb16(pb, 0x0);                  /* ? */
2441         avio_wb16(pb, 0x021C);               /* data */
2442
2443         if (!mov->exact)
2444             mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
2445         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
2446         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2447
2448         update_size(pb, pos2);
2449         return update_size(pb, pos);
2450     }
2451
2452     return 0;
2453 }
2454
2455 static void build_chunks(MOVTrack *trk)
2456 {
2457     int i;
2458     MOVIentry *chunk = &trk->cluster[0];
2459     uint64_t chunkSize = chunk->size;
2460     chunk->chunkNum = 1;
2461     if (trk->chunkCount)
2462         return;
2463     trk->chunkCount = 1;
2464     for (i = 1; i<trk->entry; i++){
2465         if (chunk->pos + chunkSize == trk->cluster[i].pos &&
2466             chunkSize + trk->cluster[i].size < (1<<20)){
2467             chunkSize             += trk->cluster[i].size;
2468             chunk->samples_in_chunk += trk->cluster[i].entries;
2469         } else {
2470             trk->cluster[i].chunkNum = chunk->chunkNum+1;
2471             chunk=&trk->cluster[i];
2472             chunkSize = chunk->size;
2473             trk->chunkCount++;
2474         }
2475     }
2476 }
2477
2478 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2479                               AVFormatContext *s)
2480 {
2481     int i;
2482     int64_t pos = avio_tell(pb);
2483     avio_wb32(pb, 0); /* size placeholder*/
2484     ffio_wfourcc(pb, "moov");
2485
2486     for (i = 0; i < mov->nb_streams; i++) {
2487         if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2488             continue;
2489
2490         mov->tracks[i].time     = mov->time;
2491         mov->tracks[i].track_id = i + 1;
2492
2493         if (mov->tracks[i].entry)
2494             build_chunks(&mov->tracks[i]);
2495     }
2496
2497     if (mov->chapter_track)
2498         for (i = 0; i < s->nb_streams; i++) {
2499             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2500             mov->tracks[i].tref_id  = mov->tracks[mov->chapter_track].track_id;
2501         }
2502     for (i = 0; i < mov->nb_streams; i++) {
2503         if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
2504             mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
2505             mov->tracks[i].tref_id =
2506                 mov->tracks[mov->tracks[i].src_track].track_id;
2507         }
2508     }
2509     for (i = 0; i < mov->nb_streams; i++) {
2510         if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
2511             int src_trk = mov->tracks[i].src_track;
2512             mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
2513             mov->tracks[src_trk].tref_id  = mov->tracks[i].track_id;
2514             //src_trk may have a different timescale than the tmcd track
2515             mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
2516                                                        mov->tracks[i].timescale,
2517                                                        mov->tracks[src_trk].timescale);
2518         }
2519     }
2520
2521     mov_write_mvhd_tag(pb, mov);
2522     if (mov->mode != MODE_MOV && !mov->iods_skip)
2523         mov_write_iods_tag(pb, mov);
2524     for (i = 0; i < mov->nb_streams; i++) {
2525         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2526             mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2527         }
2528     }
2529     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2530         mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2531
2532     if (mov->mode == MODE_PSP)
2533         mov_write_uuidusmt_tag(pb, s);
2534     else
2535         mov_write_udta_tag(pb, mov, s);
2536
2537     return update_size(pb, pos);
2538 }
2539
2540 static void param_write_int(AVIOContext *pb, const char *name, int value)
2541 {
2542     avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2543 }
2544
2545 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2546 {
2547     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2548 }
2549
2550 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2551 {
2552     char buf[150];
2553     len = FFMIN(sizeof(buf) / 2 - 1, len);
2554     ff_data_to_hex(buf, value, len, 0);
2555     buf[2 * len] = '\0';
2556     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2557 }
2558
2559 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2560 {
2561     int64_t pos = avio_tell(pb);
2562     int i;
2563     static const uint8_t uuid[] = {
2564         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2565         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2566     };
2567
2568     avio_wb32(pb, 0);
2569     ffio_wfourcc(pb, "uuid");
2570     avio_write(pb, uuid, sizeof(uuid));
2571     avio_wb32(pb, 0);
2572
2573     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2574     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2575     avio_printf(pb, "<head>\n");
2576     if (!mov->exact)
2577         avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2578                     LIBAVFORMAT_IDENT);
2579     avio_printf(pb, "</head>\n");
2580     avio_printf(pb, "<body>\n");
2581     avio_printf(pb, "<switch>\n");
2582     for (i = 0; i < mov->nb_streams; i++) {
2583         MOVTrack *track = &mov->tracks[i];
2584         const char *type;
2585         /* track->track_id is initialized in write_moov, and thus isn't known
2586          * here yet */
2587         int track_id = i + 1;
2588
2589         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2590             type = "video";
2591         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2592             type = "audio";
2593         } else {
2594             continue;
2595         }
2596         avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
2597                                                        track->enc->bit_rate);
2598         param_write_int(pb, "systemBitrate", track->enc->bit_rate);
2599         param_write_int(pb, "trackID", track_id);
2600         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2601             if (track->enc->codec_id == AV_CODEC_ID_H264) {
2602                 uint8_t *ptr;
2603                 int size = track->enc->extradata_size;
2604                 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
2605                                                    &size)) {
2606                     param_write_hex(pb, "CodecPrivateData",
2607                                     ptr ? ptr : track->enc->extradata,
2608                                     size);
2609                     av_free(ptr);
2610                 }
2611                 param_write_string(pb, "FourCC", "H264");
2612             } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
2613                 param_write_string(pb, "FourCC", "WVC1");
2614                 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2615                                 track->enc->extradata_size);
2616             }
2617             param_write_int(pb, "MaxWidth", track->enc->width);
2618             param_write_int(pb, "MaxHeight", track->enc->height);
2619             param_write_int(pb, "DisplayWidth", track->enc->width);
2620             param_write_int(pb, "DisplayHeight", track->enc->height);
2621         } else {
2622             if (track->enc->codec_id == AV_CODEC_ID_AAC) {
2623                 param_write_string(pb, "FourCC", "AACL");
2624             } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
2625                 param_write_string(pb, "FourCC", "WMAP");
2626             }
2627             param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2628                             track->enc->extradata_size);
2629             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
2630                                                              track->enc->codec_id));
2631             param_write_int(pb, "Channels", track->enc->channels);
2632             param_write_int(pb, "SamplingRate", track->enc->sample_rate);
2633             param_write_int(pb, "BitsPerSample", 16);
2634             param_write_int(pb, "PacketSize", track->enc->block_align ?
2635                                               track->enc->block_align : 4);
2636         }
2637         avio_printf(pb, "</%s>\n", type);
2638     }
2639     avio_printf(pb, "</switch>\n");
2640     avio_printf(pb, "</body>\n");
2641     avio_printf(pb, "</smil>\n");
2642
2643     return update_size(pb, pos);
2644 }
2645
2646 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2647 {
2648     avio_wb32(pb, 16);
2649     ffio_wfourcc(pb, "mfhd");
2650     avio_wb32(pb, 0);
2651     avio_wb32(pb, mov->fragments);
2652     return 0;
2653 }
2654
2655 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2656                               MOVTrack *track, int64_t moof_offset)
2657 {
2658     int64_t pos = avio_tell(pb);
2659     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2660                      MOV_TFHD_BASE_DATA_OFFSET;
2661     if (!track->entry) {
2662         flags |= MOV_TFHD_DURATION_IS_EMPTY;
2663     } else {
2664         flags |= MOV_TFHD_DEFAULT_FLAGS;
2665     }
2666     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
2667         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
2668
2669     /* Don't set a default sample size, the silverlight player refuses
2670      * to play files with that set. Don't set a default sample duration,
2671      * WMP freaks out if it is set. Don't set a base data offset, PIFF
2672      * file format says it MUST NOT be set. */
2673     if (track->mode == MODE_ISM)
2674         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2675                    MOV_TFHD_BASE_DATA_OFFSET);
2676
2677     avio_wb32(pb, 0); /* size placeholder */
2678     ffio_wfourcc(pb, "tfhd");
2679     avio_w8(pb, 0); /* version */
2680     avio_wb24(pb, flags);
2681
2682     avio_wb32(pb, track->track_id); /* track-id */
2683     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
2684         avio_wb64(pb, moof_offset);
2685     if (flags & MOV_TFHD_DEFAULT_DURATION) {
2686         track->default_duration = get_cluster_duration(track, 0);
2687         avio_wb32(pb, track->default_duration);
2688     }
2689     if (flags & MOV_TFHD_DEFAULT_SIZE) {
2690         track->default_size = track->entry ? track->cluster[0].size : 1;
2691         avio_wb32(pb, track->default_size);
2692     } else
2693         track->default_size = -1;
2694
2695     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
2696         track->default_sample_flags =
2697             track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
2698             (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2699             MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
2700         avio_wb32(pb, track->default_sample_flags);
2701     }
2702
2703     return update_size(pb, pos);
2704 }
2705
2706 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2707 {
2708     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2709            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2710 }
2711
2712 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
2713                               MOVTrack *track, int moof_size)
2714 {
2715     int64_t pos = avio_tell(pb);
2716     uint32_t flags = MOV_TRUN_DATA_OFFSET;
2717     int i;
2718
2719     for (i = 0; i < track->entry; i++) {
2720         if (get_cluster_duration(track, i) != track->default_duration)
2721             flags |= MOV_TRUN_SAMPLE_DURATION;
2722         if (track->cluster[i].size != track->default_size)
2723             flags |= MOV_TRUN_SAMPLE_SIZE;
2724         if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
2725             flags |= MOV_TRUN_SAMPLE_FLAGS;
2726     }
2727     if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
2728         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
2729     if (track->flags & MOV_TRACK_CTTS)
2730         flags |= MOV_TRUN_SAMPLE_CTS;
2731
2732     avio_wb32(pb, 0); /* size placeholder */
2733     ffio_wfourcc(pb, "trun");
2734     avio_w8(pb, 0); /* version */
2735     avio_wb24(pb, flags);
2736
2737     avio_wb32(pb, track->entry); /* sample count */
2738     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
2739         !(mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) &&
2740         track->track_id != 1)
2741         avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
2742     else
2743         avio_wb32(pb, moof_size + 8 + track->data_offset +
2744                       track->cluster[0].pos); /* data offset */
2745     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
2746         avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
2747
2748     for (i = 0; i < track->entry; i++) {
2749         if (flags & MOV_TRUN_SAMPLE_DURATION)
2750             avio_wb32(pb, get_cluster_duration(track, i));
2751         if (flags & MOV_TRUN_SAMPLE_SIZE)
2752             avio_wb32(pb, track->cluster[i].size);
2753         if (flags & MOV_TRUN_SAMPLE_FLAGS)
2754             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
2755         if (flags & MOV_TRUN_SAMPLE_CTS)
2756             avio_wb32(pb, track->cluster[i].cts);
2757     }
2758
2759     return update_size(pb, pos);
2760 }
2761
2762 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2763 {
2764     int64_t pos = avio_tell(pb);
2765     static const uint8_t uuid[] = {
2766         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2767         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2768     };
2769
2770     avio_wb32(pb, 0); /* size placeholder */
2771     ffio_wfourcc(pb, "uuid");
2772     avio_write(pb, uuid, sizeof(uuid));
2773     avio_w8(pb, 1);
2774     avio_wb24(pb, 0);
2775     avio_wb64(pb, track->frag_start);
2776     avio_wb64(pb, track->start_dts + track->track_duration -
2777                   track->cluster[0].dts);
2778
2779     return update_size(pb, pos);
2780 }
2781
2782 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2783                               MOVTrack *track, int entry)
2784 {
2785     int n = track->nb_frag_info - 1 - entry, i;
2786     int size = 8 + 16 + 4 + 1 + 16*n;
2787     static const uint8_t uuid[] = {
2788         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2789         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2790     };
2791
2792     if (entry < 0)
2793         return 0;
2794
2795     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2796     avio_wb32(pb, size);
2797     ffio_wfourcc(pb, "uuid");
2798     avio_write(pb, uuid, sizeof(uuid));
2799     avio_w8(pb, 1);
2800     avio_wb24(pb, 0);
2801     avio_w8(pb, n);
2802     for (i = 0; i < n; i++) {
2803         int index = entry + 1 + i;
2804         avio_wb64(pb, track->frag_info[index].time);
2805         avio_wb64(pb, track->frag_info[index].duration);
2806     }
2807     if (n < mov->ism_lookahead) {
2808         int free_size = 16 * (mov->ism_lookahead - n);
2809         avio_wb32(pb, free_size);
2810         ffio_wfourcc(pb, "free");
2811         ffio_fill(pb, 0, free_size - 8);
2812     }
2813
2814     return 0;
2815 }
2816
2817 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2818                                MOVTrack *track)
2819 {
2820     int64_t pos = avio_tell(pb);
2821     int i;
2822     for (i = 0; i < mov->ism_lookahead; i++) {
2823         /* Update the tfrf tag for the last ism_lookahead fragments,
2824          * nb_frag_info - 1 is the next fragment to be written. */
2825         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2826     }
2827     avio_seek(pb, pos, SEEK_SET);
2828     return 0;
2829 }
2830
2831 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
2832                               MOVTrack *track, int64_t moof_offset,
2833                               int moof_size)
2834 {
2835     int64_t pos = avio_tell(pb);
2836     avio_wb32(pb, 0); /* size placeholder */
2837     ffio_wfourcc(pb, "traf");
2838
2839     mov_write_tfhd_tag(pb, mov, track, moof_offset);
2840     mov_write_trun_tag(pb, mov, track, moof_size);
2841     if (mov->mode == MODE_ISM) {
2842         mov_write_tfxd_tag(pb, track);
2843
2844         if (mov->ism_lookahead) {
2845             int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
2846
2847             track->tfrf_offset = avio_tell(pb);
2848             avio_wb32(pb, 8 + size);
2849             ffio_wfourcc(pb, "free");
2850             for (i = 0; i < size; i++)
2851                 avio_w8(pb, 0);
2852         }
2853     }
2854
2855     return update_size(pb, pos);
2856 }
2857
2858 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
2859                                        int tracks, int moof_size)
2860 {
2861     int64_t pos = avio_tell(pb);
2862     int i;
2863
2864     avio_wb32(pb, 0); /* size placeholder */
2865     ffio_wfourcc(pb, "moof");
2866
2867     mov_write_mfhd_tag(pb, mov);
2868     for (i = 0; i < mov->nb_streams; i++) {
2869         MOVTrack *track = &mov->tracks[i];
2870         if (tracks >= 0 && i != tracks)
2871             continue;
2872         if (!track->entry)
2873             continue;
2874         mov_write_traf_tag(pb, mov, track, pos, moof_size);
2875     }
2876
2877     return update_size(pb, pos);
2878 }
2879
2880 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
2881 {
2882     AVIOContext *avio_buf;
2883     int ret, moof_size;
2884
2885     if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
2886         return ret;
2887     mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
2888     moof_size = ffio_close_null_buf(avio_buf);
2889     return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
2890 }
2891
2892 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
2893 {
2894     int64_t pos = avio_tell(pb);
2895     int i;
2896
2897     avio_wb32(pb, 0); /* size placeholder */
2898     ffio_wfourcc(pb, "tfra");
2899     avio_w8(pb, 1); /* version */
2900     avio_wb24(pb, 0);
2901
2902     avio_wb32(pb, track->track_id);
2903     avio_wb32(pb, 0); /* length of traf/trun/sample num */
2904     avio_wb32(pb, track->nb_frag_info);
2905     for (i = 0; i < track->nb_frag_info; i++) {
2906         avio_wb64(pb, track->frag_info[i].time);
2907         avio_wb64(pb, track->frag_info[i].offset);
2908         avio_w8(pb, 1); /* traf number */
2909         avio_w8(pb, 1); /* trun number */
2910         avio_w8(pb, 1); /* sample number */
2911     }
2912
2913     return update_size(pb, pos);
2914 }
2915
2916 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
2917 {
2918     int64_t pos = avio_tell(pb);
2919     int i;
2920
2921     avio_wb32(pb, 0); /* size placeholder */
2922     ffio_wfourcc(pb, "mfra");
2923     /* An empty mfra atom is enough to indicate to the publishing point that
2924      * the stream has ended. */
2925     if (mov->flags & FF_MOV_FLAG_ISML)
2926         return update_size(pb, pos);
2927
2928     for (i = 0; i < mov->nb_streams; i++) {
2929         MOVTrack *track = &mov->tracks[i];
2930         if (track->nb_frag_info)
2931             mov_write_tfra_tag(pb, track);
2932     }
2933
2934     avio_wb32(pb, 16);
2935     ffio_wfourcc(pb, "mfro");
2936     avio_wb32(pb, 0); /* version + flags */
2937     avio_wb32(pb, avio_tell(pb) + 4 - pos);
2938
2939     return update_size(pb, pos);
2940 }
2941
2942 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
2943 {
2944     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
2945     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
2946
2947     mov->mdat_pos = avio_tell(pb);
2948     avio_wb32(pb, 0); /* size placeholder*/
2949     ffio_wfourcc(pb, "mdat");
2950     return 0;
2951 }
2952
2953 /* TODO: This needs to be more general */
2954 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
2955 {
2956     MOVMuxContext *mov = s->priv_data;
2957     int64_t pos = avio_tell(pb);
2958     int has_h264 = 0, has_video = 0;
2959     int minor = 0x200;
2960     int i;
2961
2962     for (i = 0; i < s->nb_streams; i++) {
2963         AVStream *st = s->streams[i];
2964         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2965             has_video = 1;
2966         if (st->codec->codec_id == AV_CODEC_ID_H264)
2967             has_h264 = 1;
2968     }
2969
2970     avio_wb32(pb, 0); /* size */
2971     ffio_wfourcc(pb, "ftyp");
2972
2973     if (mov->major_brand && strlen(mov->major_brand) >= 4)
2974         ffio_wfourcc(pb, mov->major_brand);
2975     else if (mov->mode == MODE_3GP) {
2976         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
2977         minor =     has_h264 ?   0x100 :   0x200;
2978     } else if (mov->mode & MODE_3G2) {
2979         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
2980         minor =     has_h264 ? 0x20000 : 0x10000;
2981     } else if (mov->mode == MODE_PSP)
2982         ffio_wfourcc(pb, "MSNV");
2983     else if (mov->mode == MODE_MP4)
2984         ffio_wfourcc(pb, "isom");
2985     else if (mov->mode == MODE_IPOD)
2986         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
2987     else if (mov->mode == MODE_ISM)
2988         ffio_wfourcc(pb, "isml");
2989     else if (mov->mode == MODE_F4V)
2990         ffio_wfourcc(pb, "f4v ");
2991     else
2992         ffio_wfourcc(pb, "qt  ");
2993
2994     avio_wb32(pb, minor);
2995
2996     if (mov->mode == MODE_MOV)
2997         ffio_wfourcc(pb, "qt  ");
2998     else if (mov->mode == MODE_ISM) {
2999         ffio_wfourcc(pb, "piff");
3000         ffio_wfourcc(pb, "iso2");
3001     } else {
3002         ffio_wfourcc(pb, "isom");
3003         ffio_wfourcc(pb, "iso2");
3004         if (has_h264)
3005             ffio_wfourcc(pb, "avc1");
3006     }
3007
3008     if (mov->mode == MODE_3GP)
3009         ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3010     else if (mov->mode & MODE_3G2)
3011         ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3012     else if (mov->mode == MODE_PSP)
3013         ffio_wfourcc(pb, "MSNV");
3014     else if (mov->mode == MODE_MP4)
3015         ffio_wfourcc(pb, "mp41");
3016     return update_size(pb, pos);
3017 }
3018
3019 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3020 {
3021     AVCodecContext *video_codec = s->streams[0]->codec;
3022     AVCodecContext *audio_codec = s->streams[1]->codec;
3023     int audio_rate = audio_codec->sample_rate;
3024     int frame_rate = ((video_codec->time_base.den) * (0x10000)) / (video_codec->time_base.num);
3025     int audio_kbitrate = audio_codec->bit_rate / 1000;
3026     int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3027
3028     avio_wb32(pb, 0x94); /* size */
3029     ffio_wfourcc(pb, "uuid");
3030     ffio_wfourcc(pb, "PROF");
3031
3032     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3033     avio_wb32(pb, 0xbb88695c);
3034     avio_wb32(pb, 0xfac9c740);
3035
3036     avio_wb32(pb, 0x0);  /* ? */
3037     avio_wb32(pb, 0x3);  /* 3 sections ? */
3038
3039     avio_wb32(pb, 0x14); /* size */
3040     ffio_wfourcc(pb, "FPRF");
3041     avio_wb32(pb, 0x0);  /* ? */
3042     avio_wb32(pb, 0x0);  /* ? */
3043     avio_wb32(pb, 0x0);  /* ? */
3044
3045     avio_wb32(pb, 0x2c);  /* size */
3046     ffio_wfourcc(pb, "APRF"); /* audio */
3047     avio_wb32(pb, 0x0);
3048     avio_wb32(pb, 0x2);   /* TrackID */
3049     ffio_wfourcc(pb, "mp4a");
3050     avio_wb32(pb, 0x20f);
3051     avio_wb32(pb, 0x0);
3052     avio_wb32(pb, audio_kbitrate);
3053     avio_wb32(pb, audio_kbitrate);
3054     avio_wb32(pb, audio_rate);
3055     avio_wb32(pb, audio_codec->channels);
3056
3057     avio_wb32(pb, 0x34);  /* size */
3058     ffio_wfourcc(pb, "VPRF");   /* video */
3059     avio_wb32(pb, 0x0);
3060     avio_wb32(pb, 0x1);    /* TrackID */
3061     if (video_codec->codec_id == AV_CODEC_ID_H264) {
3062         ffio_wfourcc(pb, "avc1");
3063         avio_wb16(pb, 0x014D);
3064         avio_wb16(pb, 0x0015);
3065     } else {
3066         ffio_wfourcc(pb, "mp4v");
3067         avio_wb16(pb, 0x0000);
3068         avio_wb16(pb, 0x0103);
3069     }
3070     avio_wb32(pb, 0x0);
3071     avio_wb32(pb, video_kbitrate);
3072     avio_wb32(pb, video_kbitrate);
3073     avio_wb32(pb, frame_rate);
3074     avio_wb32(pb, frame_rate);
3075     avio_wb16(pb, video_codec->width);
3076     avio_wb16(pb, video_codec->height);
3077     avio_wb32(pb, 0x010001); /* ? */
3078 }
3079
3080 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3081 {
3082     uint32_t c = -1;
3083     int i, closed_gop = 0;
3084
3085     for (i = 0; i < pkt->size - 4; i++) {
3086         c = (c << 8) + pkt->data[i];
3087         if (c == 0x1b8) { // gop
3088             closed_gop = pkt->data[i + 4] >> 6 & 0x01;
3089         } else if (c == 0x100) { // pic
3090             int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
3091             if (!temp_ref || closed_gop) // I picture is not reordered
3092                 *flags = MOV_SYNC_SAMPLE;
3093             else
3094                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
3095             break;
3096         }
3097     }
3098     return 0;
3099 }
3100
3101 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
3102 {
3103     const uint8_t *start, *next, *end = pkt->data + pkt->size;
3104     int seq = 0, entry = 0;
3105     int key = pkt->flags & AV_PKT_FLAG_KEY;
3106     start = find_next_marker(pkt->data, end);
3107     for (next = start; next < end; start = next) {
3108         next = find_next_marker(start + 4, end);
3109         switch (AV_RB32(start)) {
3110         case VC1_CODE_SEQHDR:
3111             seq = 1;
3112             break;
3113         case VC1_CODE_ENTRYPOINT:
3114             entry = 1;
3115             break;
3116         case VC1_CODE_SLICE:
3117             trk->vc1_info.slices = 1;
3118             break;
3119         }
3120     }
3121     if (!trk->entry && !fragment) {
3122         /* First packet in first fragment */
3123         trk->vc1_info.first_packet_seq   = seq;
3124         trk->vc1_info.first_packet_entry = entry;
3125     } else if ((seq && !trk->vc1_info.packet_seq) ||
3126                (entry && !trk->vc1_info.packet_entry)) {
3127         int i;
3128         for (i = 0; i < trk->entry; i++)
3129             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
3130         trk->has_keyframes = 0;
3131         if (seq)
3132             trk->vc1_info.packet_seq = 1;
3133         if (entry)
3134             trk->vc1_info.packet_entry = 1;
3135         if (!fragment) {
3136             /* First fragment */
3137             if ((!seq   || trk->vc1_info.first_packet_seq) &&
3138                 (!entry || trk->vc1_info.first_packet_entry)) {
3139                 /* First packet had the same headers as this one, readd the
3140                  * sync sample flag. */
3141                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
3142                 trk->has_keyframes = 1;
3143             }
3144         }
3145     }
3146     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
3147         key = seq && entry;
3148     else if (trk->vc1_info.packet_seq)
3149         key = seq;
3150     else if (trk->vc1_info.packet_entry)
3151         key = entry;
3152     if (key) {
3153         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
3154         trk->has_keyframes++;
3155     }
3156 }
3157
3158 static int mov_flush_fragment(AVFormatContext *s)
3159 {
3160     MOVMuxContext *mov = s->priv_data;
3161     int i, first_track = -1;
3162     int64_t mdat_size = 0;
3163
3164     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3165         return 0;
3166
3167     if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
3168         int64_t pos = avio_tell(s->pb);
3169         uint8_t *buf;
3170         int buf_size, moov_size;
3171
3172         for (i = 0; i < mov->nb_streams; i++)
3173             if (!mov->tracks[i].entry)
3174                 break;
3175         /* Don't write the initial moov unless all tracks have data */
3176         if (i < mov->nb_streams)
3177             return 0;
3178
3179         moov_size = get_moov_size(s);
3180         for (i = 0; i < mov->nb_streams; i++)
3181             mov->tracks[i].data_offset = pos + moov_size + 8;
3182
3183         mov_write_moov_tag(s->pb, mov, s);
3184
3185         buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
3186         mov->mdat_buf = NULL;
3187         avio_wb32(s->pb, buf_size + 8);
3188         ffio_wfourcc(s->pb, "mdat");
3189         avio_write(s->pb, buf, buf_size);
3190         av_free(buf);
3191
3192         mov->fragments++;
3193         mov->mdat_size = 0;
3194         for (i = 0; i < mov->nb_streams; i++) {
3195             if (mov->tracks[i].entry)
3196                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
3197                                              mov->tracks[i].track_duration -
3198                                              mov->tracks[i].cluster[0].dts;
3199             mov->tracks[i].entry = 0;
3200         }
3201         avio_flush(s->pb);
3202         return 0;
3203     }
3204
3205     for (i = 0; i < mov->nb_streams; i++) {
3206         MOVTrack *track = &mov->tracks[i];
3207         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
3208             track->data_offset = 0;
3209         else
3210             track->data_offset = mdat_size;
3211         if (!track->mdat_buf)
3212             continue;
3213         mdat_size += avio_tell(track->mdat_buf);
3214         if (first_track < 0)
3215             first_track = i;
3216     }
3217
3218     if (!mdat_size)
3219         return 0;
3220
3221     for (i = 0; i < mov->nb_streams; i++) {
3222         MOVTrack *track = &mov->tracks[i];
3223         int buf_size, write_moof = 1, moof_tracks = -1;
3224         uint8_t *buf;
3225         int64_t duration = 0;
3226
3227         if (track->entry)
3228             duration = track->start_dts + track->track_duration -
3229                        track->cluster[0].dts;
3230         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
3231             if (!track->mdat_buf)
3232                 continue;
3233             mdat_size = avio_tell(track->mdat_buf);
3234             moof_tracks = i;
3235         } else {
3236             write_moof = i == first_track;
3237         }
3238
3239         if (write_moof) {
3240             MOVFragmentInfo *info;
3241             avio_flush(s->pb);
3242             track->nb_frag_info++;
3243             if (track->nb_frag_info >= track->frag_info_capacity) {
3244                 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3245                 if (av_reallocp_array(&track->frag_info,
3246                                       new_capacity,
3247                                       sizeof(*track->frag_info)))
3248                     return AVERROR(ENOMEM);
3249                 track->frag_info_capacity = new_capacity;
3250             }
3251             info = &track->frag_info[track->nb_frag_info - 1];
3252             info->offset   = avio_tell(s->pb);
3253             info->time     = mov->tracks[i].frag_start;
3254             info->duration = duration;
3255             mov_write_tfrf_tags(s->pb, mov, track);
3256
3257             mov_write_moof_tag(s->pb, mov, moof_tracks);
3258             info->tfrf_offset = track->tfrf_offset;
3259             mov->fragments++;
3260
3261             avio_wb32(s->pb, mdat_size + 8);
3262             ffio_wfourcc(s->pb, "mdat");
3263         }
3264
3265         if (track->entry)
3266             track->frag_start += duration;
3267         track->entry = 0;
3268         if (!track->mdat_buf)
3269             continue;
3270         buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
3271         track->mdat_buf = NULL;
3272
3273         avio_write(s->pb, buf, buf_size);
3274         av_free(buf);
3275     }
3276
3277     mov->mdat_size = 0;
3278
3279     avio_flush(s->pb);
3280     return 0;
3281 }
3282
3283 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3284 {
3285     MOVMuxContext *mov = s->priv_data;
3286     AVIOContext *pb = s->pb;
3287     MOVTrack *trk = &mov->tracks[pkt->stream_index];
3288     AVCodecContext *enc = trk->enc;
3289     unsigned int samples_in_chunk = 0;
3290     int size = pkt->size;
3291     uint8_t *reformatted_data = NULL;
3292
3293     if (trk->entry) {
3294         int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
3295         if (duration < 0 || duration > INT_MAX) {
3296             av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
3297                 duration, pkt->dts
3298             );
3299
3300             pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
3301             pkt->pts = AV_NOPTS_VALUE;
3302         }
3303     }
3304     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
3305         int ret;
3306         if (mov->fragments > 0) {
3307             if (!trk->mdat_buf) {
3308                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
3309                     return ret;
3310             }
3311             pb = trk->mdat_buf;
3312         } else {
3313             if (!mov->mdat_buf) {
3314                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
3315                     return ret;
3316             }
3317             pb = mov->mdat_buf;
3318         }
3319     }
3320
3321     if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
3322         /* We must find out how many AMR blocks there are in one packet */
3323         static uint16_t packed_size[16] =
3324             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
3325         int len = 0;
3326
3327         while (len < size && samples_in_chunk < 100) {
3328             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
3329             samples_in_chunk++;
3330         }
3331         if (samples_in_chunk > 1) {
3332             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
3333             return -1;
3334         }
3335     } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
3336                enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
3337         samples_in_chunk = enc->frame_size;
3338     } else if (trk->sample_size)
3339         samples_in_chunk = size / trk->sample_size;
3340     else
3341         samples_in_chunk = 1;
3342
3343     /* copy extradata if it exists */
3344     if (trk->vos_len == 0 && enc->extradata_size > 0) {
3345         trk->vos_len  = enc->extradata_size;
3346         trk->vos_data = av_malloc(trk->vos_len);
3347         memcpy(trk->vos_data, enc->extradata, trk->vos_len);
3348     }
3349
3350     if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
3351         (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
3352         if (!s->streams[pkt->stream_index]->nb_frames) {
3353             av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
3354                    "use audio bitstream filter 'aac_adtstoasc' to fix it "
3355                    "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
3356             return -1;
3357         }
3358         av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
3359     }
3360     if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {
3361         /* from x264 or from bytestream h264 */
3362         /* nal reformating needed */
3363         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3364             ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
3365                                        &size);
3366             avio_write(pb, reformatted_data, size);
3367         } else {
3368             size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
3369         }
3370     } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
3371                (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
3372         /* extradata is Annex B, assume the bitstream is too and convert it */
3373         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3374             ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
3375             avio_write(pb, reformatted_data, size);
3376         } else {
3377             size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
3378         }
3379     } else {
3380         avio_write(pb, pkt->data, size);
3381     }
3382
3383     if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
3384          enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
3385         /* copy frame to create needed atoms */
3386         trk->vos_len  = size;
3387         trk->vos_data = av_malloc(size);
3388         if (!trk->vos_data)
3389             return AVERROR(ENOMEM);
3390         memcpy(trk->vos_data, pkt->data, size);
3391     }
3392
3393     if (trk->entry >= trk->cluster_capacity) {
3394         unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
3395         if (av_reallocp_array(&trk->cluster, new_capacity,
3396                               sizeof(*trk->cluster)))
3397             return AVERROR(ENOMEM);
3398         trk->cluster_capacity = new_capacity;
3399     }
3400
3401     trk->cluster[trk->entry].pos              = avio_tell(pb) - size;
3402     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
3403     trk->cluster[trk->entry].chunkNum         = 0;
3404     trk->cluster[trk->entry].size             = size;
3405     trk->cluster[trk->entry].entries          = samples_in_chunk;
3406     trk->cluster[trk->entry].dts              = pkt->dts;
3407     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
3408         /* First packet of a new fragment. We already wrote the duration
3409          * of the last packet of the previous fragment based on track_duration,
3410          * which might not exactly match our dts. Therefore adjust the dts
3411          * of this packet to be what the previous packets duration implies. */
3412         trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
3413     }
3414     if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !supports_edts(mov)) {
3415         trk->cluster[trk->entry].dts = trk->start_dts = 0;
3416     }
3417     if (trk->start_dts == AV_NOPTS_VALUE)
3418         trk->start_dts = pkt->dts;
3419     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
3420     trk->last_sample_is_subtitle_end = 0;
3421
3422     if (pkt->pts == AV_NOPTS_VALUE) {
3423         av_log(s, AV_LOG_WARNING, "pts has no value\n");
3424         pkt->pts = pkt->dts;
3425     }
3426     if (pkt->dts != pkt->pts)
3427         trk->flags |= MOV_TRACK_CTTS;
3428     trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;
3429     trk->cluster[trk->entry].flags = 0;
3430     if (enc->codec_id == AV_CODEC_ID_VC1) {
3431         mov_parse_vc1_frame(pkt, trk, mov->fragments);
3432     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
3433         if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
3434             trk->entry > 0) { // force sync sample for the first key frame
3435             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
3436             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
3437                 trk->flags |= MOV_TRACK_STPS;
3438         } else {
3439             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
3440         }
3441         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
3442             trk->has_keyframes++;
3443     }
3444     trk->entry++;
3445     trk->sample_count += samples_in_chunk;
3446     mov->mdat_size    += size;
3447
3448     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
3449         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
3450                                  reformatted_data, size);
3451     av_free(reformatted_data);
3452     return 0;
3453 }
3454
3455 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
3456 {
3457         MOVMuxContext *mov = s->priv_data;
3458         MOVTrack *trk = &mov->tracks[pkt->stream_index];
3459         AVCodecContext *enc = trk->enc;
3460         int64_t frag_duration = 0;
3461         int size = pkt->size;
3462
3463         if (!pkt->size)
3464             return 0;             /* Discard 0 sized packets */
3465
3466         if (trk->entry && pkt->stream_index < s->nb_streams)
3467             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
3468                                          s->streams[pkt->stream_index]->time_base,
3469                                          AV_TIME_BASE_Q);
3470         if ((mov->max_fragment_duration &&
3471              frag_duration >= mov->max_fragment_duration) ||
3472              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
3473              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
3474               enc->codec_type == AVMEDIA_TYPE_VIDEO &&
3475               trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
3476             if (frag_duration >= mov->min_fragment_duration)
3477                 mov_flush_fragment(s);
3478         }
3479
3480         return ff_mov_write_packet(s, pkt);
3481 }
3482
3483 static int mov_write_subtitle_end_packet(AVFormatContext *s,
3484                                          int stream_index,
3485                                          int64_t dts) {
3486     AVPacket end;
3487     uint8_t data[2] = {0};
3488     int ret;
3489
3490     av_init_packet(&end);
3491     end.size = sizeof(data);
3492     end.data = data;
3493     end.pts = dts;
3494     end.dts = dts;
3495     end.duration = 0;
3496     end.stream_index = stream_index;
3497
3498     ret = mov_write_single_packet(s, &end);
3499     av_free_packet(&end);
3500
3501     return ret;
3502 }
3503
3504 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3505 {
3506     if (!pkt) {
3507         mov_flush_fragment(s);
3508         return 1;
3509     } else {
3510         int i;
3511         MOVMuxContext *mov = s->priv_data;
3512
3513         if (!pkt->size) return 0; /* Discard 0 sized packets */
3514
3515         /*
3516          * Subtitles require special handling.
3517          *
3518          * 1) For full complaince, every track must have a sample at
3519          * dts == 0, which is rarely true for subtitles. So, as soon
3520          * as we see any packet with dts > 0, write an empty subtitle
3521          * at dts == 0 for any subtitle track with no samples in it.
3522          *
3523          * 2) For each subtitle track, check if the current packet's
3524          * dts is past the duration of the last subtitle sample. If
3525          * so, we now need to write an end sample for that subtitle.
3526          *
3527          * This must be done conditionally to allow for subtitles that
3528          * immediately replace each other, in which case an end sample
3529          * is not needed, and is, in fact, actively harmful.
3530          *
3531          * 3) See mov_write_trailer for how the final end sample is
3532          * handled.
3533          */
3534         for (i = 0; i < mov->nb_streams; i++) {
3535             MOVTrack *trk = &mov->tracks[i];
3536             int ret;
3537
3538             if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
3539                 trk->track_duration < pkt->dts &&
3540                 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
3541                 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
3542                 if (ret < 0) return ret;
3543                 trk->last_sample_is_subtitle_end = 1;
3544             }
3545         }
3546
3547         return mov_write_single_packet(s, pkt);
3548     }
3549 }
3550
3551 // QuickTime chapters involve an additional text track with the chapter names
3552 // as samples, and a tref pointing from the other tracks to the chapter one.
3553 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
3554 {
3555     AVIOContext *pb;
3556
3557     MOVMuxContext *mov = s->priv_data;
3558     MOVTrack *track = &mov->tracks[tracknum];
3559     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
3560     int i, len;
3561
3562     track->mode = mov->mode;
3563     track->tag = MKTAG('t','e','x','t');
3564     track->timescale = MOV_TIMESCALE;
3565     track->enc = avcodec_alloc_context3(NULL);
3566     if (!track->enc)
3567         return AVERROR(ENOMEM);
3568     track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3569 #if 0
3570     // These properties are required to make QT recognize the chapter track
3571     uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
3572     if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
3573         return AVERROR(ENOMEM);
3574     memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
3575 #else
3576     if (avio_open_dyn_buf(&pb) >= 0) {
3577         int size;
3578         uint8_t *buf;
3579
3580         /* Stub header (usually for Quicktime chapter track) */
3581         // TextSampleEntry
3582         avio_wb32(pb, 0x01); // displayFlags
3583         avio_w8(pb, 0x00);   // horizontal justification
3584         avio_w8(pb, 0x00);   // vertical justification
3585         avio_w8(pb, 0x00);   // bgColourRed
3586         avio_w8(pb, 0x00);   // bgColourGreen
3587         avio_w8(pb, 0x00);   // bgColourBlue
3588         avio_w8(pb, 0x00);   // bgColourAlpha
3589         // BoxRecord
3590         avio_wb16(pb, 0x00); // defTextBoxTop
3591         avio_wb16(pb, 0x00); // defTextBoxLeft
3592         avio_wb16(pb, 0x00); // defTextBoxBottom
3593         avio_wb16(pb, 0x00); // defTextBoxRight
3594         // StyleRecord
3595         avio_wb16(pb, 0x00); // startChar
3596         avio_wb16(pb, 0x00); // endChar
3597         avio_wb16(pb, 0x01); // fontID
3598         avio_w8(pb, 0x00);   // fontStyleFlags
3599         avio_w8(pb, 0x00);   // fontSize
3600         avio_w8(pb, 0x00);   // fgColourRed
3601         avio_w8(pb, 0x00);   // fgColourGreen
3602         avio_w8(pb, 0x00);   // fgColourBlue
3603         avio_w8(pb, 0x00);   // fgColourAlpha
3604         // FontTableBox
3605         avio_wb32(pb, 0x0D); // box size
3606         ffio_wfourcc(pb, "ftab"); // box atom name
3607         avio_wb16(pb, 0x01); // entry count
3608         // FontRecord
3609         avio_wb16(pb, 0x01); // font ID
3610         avio_w8(pb, 0x00);   // font name length
3611
3612         if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
3613             track->enc->extradata = buf;
3614             track->enc->extradata_size = size;
3615         } else {
3616             av_freep(&buf);
3617         }
3618     }
3619 #endif
3620
3621     for (i = 0; i < s->nb_chapters; i++) {
3622         AVChapter *c = s->chapters[i];
3623         AVDictionaryEntry *t;
3624
3625         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
3626         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
3627         pkt.duration = end - pkt.dts;
3628
3629         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3630             len      = strlen(t->value);
3631             pkt.size = len + 2;
3632             pkt.data = av_malloc(pkt.size);
3633             if (!pkt.data)
3634                 return AVERROR(ENOMEM);
3635             AV_WB16(pkt.data, len);
3636             memcpy(pkt.data + 2, t->value, len);
3637             ff_mov_write_packet(s, &pkt);
3638             av_freep(&pkt.data);
3639         }
3640     }
3641
3642     return 0;
3643 }
3644
3645 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
3646 {
3647     int ret;
3648     MOVMuxContext *mov  = s->priv_data;
3649     MOVTrack *track     = &mov->tracks[index];
3650     AVStream *src_st    = s->streams[src_index];
3651     AVTimecode tc;
3652     AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
3653     AVRational rate = find_fps(s, src_st);
3654
3655     /* compute the frame number */
3656     ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
3657     if (ret < 0)
3658         return ret;
3659
3660     /* tmcd track based on video stream */
3661     track->mode      = mov->mode;
3662     track->tag       = MKTAG('t','m','c','d');
3663     track->src_track = src_index;
3664     track->timescale = mov->tracks[src_index].timescale;
3665     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
3666         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
3667
3668     /* encode context: tmcd data stream */
3669     track->enc = avcodec_alloc_context3(NULL);
3670     track->enc->codec_type = AVMEDIA_TYPE_DATA;
3671     track->enc->codec_tag  = track->tag;
3672     track->enc->time_base  = av_inv_q(rate);
3673
3674     /* the tmcd track just contains one packet with the frame number */
3675     pkt.data = av_malloc(pkt.size);
3676     AV_WB32(pkt.data, tc.start);
3677     ret = ff_mov_write_packet(s, &pkt);
3678     av_free(pkt.data);
3679     return ret;
3680 }
3681
3682 /*
3683  * st->disposition controls the "enabled" flag in the tkhd tag.
3684  * QuickTime will not play a track if it is not enabled.  So make sure
3685  * that one track of each type (audio, video, subtitle) is enabled.
3686  *
3687  * Subtitles are special.  For audio and video, setting "enabled" also
3688  * makes the track "default" (i.e. it is rendered when played). For
3689  * subtitles, an "enabled" subtitle is not rendered by default, but
3690  * if no subtitle is enabled, the subtitle menu in QuickTime will be
3691  * empty!
3692  */
3693 static void enable_tracks(AVFormatContext *s)
3694 {
3695     MOVMuxContext *mov = s->priv_data;
3696     int i;
3697     uint8_t enabled[AVMEDIA_TYPE_NB];
3698     int first[AVMEDIA_TYPE_NB];
3699
3700     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3701         enabled[i] = 0;
3702         first[i] = -1;
3703     }
3704
3705     for (i = 0; i < s->nb_streams; i++) {
3706         AVStream *st = s->streams[i];
3707
3708         if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
3709             st->codec->codec_type >= AVMEDIA_TYPE_NB)
3710             continue;
3711
3712         if (first[st->codec->codec_type] < 0)
3713             first[st->codec->codec_type] = i;
3714         if (st->disposition & AV_DISPOSITION_DEFAULT) {
3715             mov->tracks[i].flags |= MOV_TRACK_ENABLED;
3716             enabled[st->codec->codec_type] = 1;
3717         }
3718     }
3719
3720     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3721         switch (i) {
3722         case AVMEDIA_TYPE_VIDEO:
3723         case AVMEDIA_TYPE_AUDIO:
3724         case AVMEDIA_TYPE_SUBTITLE:
3725             if (!enabled[i] && first[i] >= 0)
3726                 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
3727             break;
3728         }
3729     }
3730 }
3731
3732 static void mov_free(AVFormatContext *s)
3733 {
3734     MOVMuxContext *mov = s->priv_data;
3735     int i;
3736
3737     if (mov->chapter_track) {
3738         if (mov->tracks[mov->chapter_track].enc)
3739             av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
3740         av_freep(&mov->tracks[mov->chapter_track].enc);
3741     }
3742
3743     for (i = 0; i < mov->nb_streams; i++) {
3744         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
3745             ff_mov_close_hinting(&mov->tracks[i]);
3746         else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
3747             av_freep(&mov->tracks[i].enc);
3748         av_freep(&mov->tracks[i].cluster);
3749         av_freep(&mov->tracks[i].frag_info);
3750
3751         if (mov->tracks[i].vos_len)
3752             av_freep(&mov->tracks[i].vos_data);
3753     }
3754
3755     av_freep(&mov->tracks);
3756 }
3757
3758 static uint32_t rgb_to_yuv(uint32_t rgb)
3759 {
3760     uint8_t r, g, b;
3761     int y, cb, cr;
3762
3763     r = (rgb >> 16) & 0xFF;
3764     g = (rgb >>  8) & 0xFF;
3765     b = (rgb      ) & 0xFF;
3766
3767     y  = av_clip_uint8( 16. +  0.257 * r + 0.504 * g + 0.098 * b);
3768     cb = av_clip_uint8(128. -  0.148 * r - 0.291 * g + 0.439 * b);
3769     cr = av_clip_uint8(128. +  0.439 * r - 0.368 * g - 0.071 * b);
3770
3771     return (y << 16) | (cr << 8) | cb;
3772 }
3773
3774 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
3775                                                     AVStream *st)
3776 {
3777     int i, width = 720, height = 480;
3778     int have_palette = 0, have_size = 0;
3779     uint32_t palette[16];
3780     char *cur = st->codec->extradata;
3781
3782     while (cur && *cur) {
3783         if (strncmp("palette:", cur, 8) == 0) {
3784             int i, count;
3785             count = sscanf(cur + 8,
3786                 "%06x, %06x, %06x, %06x, %06x, %06x, %06x, %06x, "
3787                 "%06x, %06x, %06x, %06x, %06x, %06x, %06x, %06x",
3788                 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
3789                 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
3790                 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
3791                 &palette[12], &palette[13], &palette[14], &palette[15]);
3792
3793             for (i = 0; i < count; i++) {
3794                 palette[i] = rgb_to_yuv(palette[i]);
3795             }
3796             have_palette = 1;
3797         } else if (!strncmp("size:", cur, 5)) {
3798             sscanf(cur + 5, "%dx%d", &width, &height);
3799             have_size = 1;
3800         }
3801         if (have_palette && have_size)
3802             break;
3803         cur += strcspn(cur, "\n\r");
3804         cur += strspn(cur, "\n\r");
3805     }
3806     if (have_palette) {
3807         track->vos_data = av_malloc(16*4);
3808         if (!track->vos_data)
3809             return AVERROR(ENOMEM);
3810         for (i = 0; i < 16; i++) {
3811             AV_WB32(track->vos_data + i * 4, palette[i]);
3812         }
3813         track->vos_len = 16 * 4;
3814     }
3815     st->codec->width = width;
3816     st->codec->height = track->height = height;
3817
3818     return 0;
3819 }
3820
3821 static int mov_write_header(AVFormatContext *s)
3822 {
3823     AVIOContext *pb = s->pb;
3824     MOVMuxContext *mov = s->priv_data;
3825     AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
3826     int i, ret, hint_track = 0, tmcd_track = 0;
3827
3828     /* Default mode == MP4 */
3829     mov->mode = MODE_MP4;
3830
3831     if (s->oformat != NULL) {
3832         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
3833         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
3834         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
3835         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
3836         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
3837         else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
3838         else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
3839     }
3840
3841     for (i = 0; i < s->nb_streams; i++)
3842         if (s->streams[i]->codec->flags & CODEC_FLAG_BITEXACT)
3843             mov->exact = 1;
3844
3845     /* Set the FRAGMENT flag if any of the fragmentation methods are
3846      * enabled. */
3847     if (mov->max_fragment_duration || mov->max_fragment_size ||
3848         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
3849                       FF_MOV_FLAG_FRAG_KEYFRAME |
3850                       FF_MOV_FLAG_FRAG_CUSTOM))
3851         mov->flags |= FF_MOV_FLAG_FRAGMENT;
3852
3853     /* Set other implicit flags immediately */
3854     if (mov->mode == MODE_ISM)
3855         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
3856                       FF_MOV_FLAG_FRAGMENT;
3857
3858     /* faststart: moov at the beginning of the file, if supported */
3859     if (mov->flags & FF_MOV_FLAG_FASTSTART) {
3860         if ((mov->flags & FF_MOV_FLAG_FRAGMENT) ||
3861             (s->flags & AVFMT_FLAG_CUSTOM_IO)) {
3862             av_log(s, AV_LOG_WARNING, "The faststart flag is incompatible "
3863                    "with fragmentation and custom IO, disabling faststart\n");
3864             mov->flags &= ~FF_MOV_FLAG_FASTSTART;
3865         } else
3866             mov->reserved_moov_size = -1;
3867     }
3868
3869     if (!supports_edts(mov) && s->avoid_negative_ts < 0) {
3870         s->avoid_negative_ts = 2;
3871     }
3872
3873     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
3874      * is enabled, we don't support non-seekable output at all. */
3875     if (!s->pb->seekable &&
3876         (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
3877         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
3878         return AVERROR(EINVAL);
3879     }
3880
3881     mov_write_ftyp_tag(pb,s);
3882     if (mov->mode == MODE_PSP) {
3883         int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
3884         for (i = 0; i < s->nb_streams; i++) {
3885             AVStream *st = s->streams[i];
3886             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3887                 video_streams_nb++;
3888             else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3889                 audio_streams_nb++;
3890             else
3891                 other_streams_nb++;
3892             }
3893
3894         if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
3895             av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3896             return AVERROR(EINVAL);
3897         }
3898         mov_write_uuidprof_tag(pb, s);
3899     }
3900
3901     mov->nb_streams = s->nb_streams;
3902     if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
3903         mov->chapter_track = mov->nb_streams++;
3904
3905     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
3906         /* Add hint tracks for each audio and video stream */
3907         hint_track = mov->nb_streams;
3908         for (i = 0; i < s->nb_streams; i++) {
3909             AVStream *st = s->streams[i];
3910             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3911                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3912                 mov->nb_streams++;
3913             }
3914         }
3915     }
3916
3917     if (mov->mode == MODE_MOV) {
3918         tmcd_track = mov->nb_streams;
3919
3920         /* +1 tmcd track for each video stream with a timecode */
3921         for (i = 0; i < s->nb_streams; i++) {
3922             AVStream *st = s->streams[i];
3923             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3924                 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
3925                 mov->nb_meta_tmcd++;
3926         }
3927
3928         /* check if there is already a tmcd track to remux */
3929         if (mov->nb_meta_tmcd) {
3930             for (i = 0; i < s->nb_streams; i++) {
3931                 AVStream *st = s->streams[i];
3932                 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
3933                     av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
3934                            "so timecode metadata are now ignored\n");
3935                     mov->nb_meta_tmcd = 0;
3936                 }
3937             }
3938         }
3939
3940         mov->nb_streams += mov->nb_meta_tmcd;
3941     }
3942
3943     // Reserve an extra stream for chapters for the case where chapters
3944     // are written in the trailer
3945     mov->tracks = av_mallocz((mov->nb_streams + 1) * sizeof(*mov->tracks));
3946     if (!mov->tracks)
3947         return AVERROR(ENOMEM);
3948
3949     for (i = 0; i < s->nb_streams; i++) {
3950         AVStream *st= s->streams[i];
3951         MOVTrack *track= &mov->tracks[i];
3952         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3953
3954         track->enc = st->codec;
3955         track->st = st;
3956         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
3957         if (track->language < 0)
3958             track->language = 0;
3959         track->mode = mov->mode;
3960         track->tag  = mov_find_codec_tag(s, track);
3961         if (!track->tag) {
3962             av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
3963                    "codec not currently supported in container\n",
3964                    avcodec_get_name(st->codec->codec_id), i);
3965             ret = AVERROR(EINVAL);
3966             goto error;
3967         }
3968         /* If hinting of this track is enabled by a later hint track,
3969          * this is updated. */
3970         track->hint_track = -1;
3971         track->start_dts  = AV_NOPTS_VALUE;
3972         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3973             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
3974                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
3975                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
3976                 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
3977                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
3978                     ret = AVERROR(EINVAL);
3979                     goto error;
3980                 }
3981                 track->height = track->tag >> 24 == 'n' ? 486 : 576;
3982             }
3983             if (mov->video_track_timescale) {
3984                 track->timescale = mov->video_track_timescale;
3985             } else {
3986                 track->timescale = st->codec->time_base.den;
3987                 while(track->timescale < 10000)
3988                     track->timescale *= 2;
3989             }
3990             if (track->mode == MODE_MOV && track->timescale > 100000)
3991                 av_log(s, AV_LOG_WARNING,
3992                        "WARNING codec timebase is very high. If duration is too long,\n"
3993                        "file may not be playable by quicktime. Specify a shorter timebase\n"
3994                        "or choose different container.\n");
3995         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3996             track->timescale = st->codec->sample_rate;
3997             if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
3998                 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
3999                 track->audio_vbr = 1;
4000             }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
4001                      st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
4002                      st->codec->codec_id == AV_CODEC_ID_ILBC){
4003                 if (!st->codec->block_align) {
4004                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
4005                     ret = AVERROR(EINVAL);
4006                     goto error;
4007                 }
4008                 track->sample_size = st->codec->block_align;
4009             }else if (st->codec->frame_size > 1){ /* assume compressed audio */
4010                 track->audio_vbr = 1;
4011             }else{
4012                 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
4013             }
4014             if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
4015                 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
4016                 track->audio_vbr = 1;
4017             }
4018             if (track->mode != MODE_MOV &&
4019                 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
4020                 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
4021                        i, track->enc->sample_rate);
4022                 ret = AVERROR(EINVAL);
4023                 goto error;
4024             }
4025         } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4026             track->timescale = st->codec->time_base.den;
4027         } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
4028             track->timescale = st->codec->time_base.den;
4029         } else {
4030             track->timescale = MOV_TIMESCALE;
4031         }
4032         if (!track->height)
4033             track->height = st->codec->height;
4034         /* The ism specific timescale isn't mandatory, but is assumed by
4035          * some tools, such as mp4split. */
4036         if (mov->mode == MODE_ISM)
4037             track->timescale = 10000000;
4038
4039         avpriv_set_pts_info(st, 64, 1, track->timescale);
4040
4041         /* copy extradata if it exists */
4042         if (st->codec->extradata_size) {
4043             if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
4044                 mov_create_dvd_sub_decoder_specific_info(track, st);
4045             else {
4046                 track->vos_len  = st->codec->extradata_size;
4047                 track->vos_data = av_malloc(track->vos_len);
4048                 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
4049             }
4050         }
4051     }
4052
4053     enable_tracks(s);
4054
4055
4056     if (mov->reserved_moov_size){
4057         mov->reserved_moov_pos= avio_tell(pb);
4058         if (mov->reserved_moov_size > 0)
4059             avio_skip(pb, mov->reserved_moov_size);
4060     }
4061
4062     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4063         /* If no fragmentation options have been set, set a default. */
4064         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
4065                             FF_MOV_FLAG_FRAG_CUSTOM)) &&
4066             !mov->max_fragment_duration && !mov->max_fragment_size)
4067             mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
4068     } else {
4069         if (mov->flags & FF_MOV_FLAG_FASTSTART)
4070             mov->reserved_moov_pos = avio_tell(pb);
4071         mov_write_mdat_tag(pb, mov);
4072     }
4073
4074     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
4075         mov->time = ff_iso8601_to_unix_time(t->value);
4076     if (mov->time)
4077         mov->time += 0x7C25B080; // 1970 based -> 1904 based
4078
4079     if (mov->chapter_track)
4080         if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4081             goto error;
4082
4083     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4084         /* Initialize the hint tracks for each audio and video stream */
4085         for (i = 0; i < s->nb_streams; i++) {
4086             AVStream *st = s->streams[i];
4087             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4088                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4089                 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
4090                     goto error;
4091                 hint_track++;
4092             }
4093         }
4094     }
4095
4096     if (mov->nb_meta_tmcd) {
4097         /* Initialize the tmcd tracks */
4098         for (i = 0; i < s->nb_streams; i++) {
4099             AVStream *st = s->streams[i];
4100             t = global_tcr;
4101
4102             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4103                 if (!t)
4104                     t = av_dict_get(st->metadata, "timecode", NULL, 0);
4105                 if (!t)
4106                     continue;
4107                 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
4108                     goto error;
4109                 tmcd_track++;
4110             }
4111         }
4112     }
4113
4114     avio_flush(pb);
4115
4116     if (mov->flags & FF_MOV_FLAG_ISML)
4117         mov_write_isml_manifest(pb, mov);
4118
4119     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4120         mov_write_moov_tag(pb, mov, s);
4121         mov->fragments++;
4122     }
4123
4124     return 0;
4125  error:
4126     mov_free(s);
4127     return ret;
4128 }
4129
4130 static int get_moov_size(AVFormatContext *s)
4131 {
4132     int ret;
4133     AVIOContext *moov_buf;
4134     MOVMuxContext *mov = s->priv_data;
4135
4136     if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
4137         return ret;
4138     mov_write_moov_tag(moov_buf, mov, s);
4139     return ffio_close_null_buf(moov_buf);
4140 }
4141
4142 /*
4143  * This function gets the moov size if moved to the top of the file: the chunk
4144  * offset table can switch between stco (32-bit entries) to co64 (64-bit
4145  * entries) when the moov is moved to the beginning, so the size of the moov
4146  * would change. It also updates the chunk offset tables.
4147  */
4148 static int compute_moov_size(AVFormatContext *s)
4149 {
4150     int i, moov_size, moov_size2;
4151     MOVMuxContext *mov = s->priv_data;
4152
4153     moov_size = get_moov_size(s);
4154     if (moov_size < 0)
4155         return moov_size;
4156
4157     for (i = 0; i < mov->nb_streams; i++)
4158         mov->tracks[i].data_offset += moov_size;
4159
4160     moov_size2 = get_moov_size(s);
4161     if (moov_size2 < 0)
4162         return moov_size2;
4163
4164     /* if the size changed, we just switched from stco to co64 and need to
4165      * update the offsets */
4166     if (moov_size2 != moov_size)
4167         for (i = 0; i < mov->nb_streams; i++)
4168             mov->tracks[i].data_offset += moov_size2 - moov_size;
4169
4170     return moov_size2;
4171 }
4172
4173 static int shift_data(AVFormatContext *s)
4174 {
4175     int ret = 0, moov_size;
4176     MOVMuxContext *mov = s->priv_data;
4177     int64_t pos, pos_end = avio_tell(s->pb);
4178     uint8_t *buf, *read_buf[2];
4179     int read_buf_id = 0;
4180     int read_size[2];
4181     AVIOContext *read_pb;
4182
4183     moov_size = compute_moov_size(s);
4184     if (moov_size < 0)
4185         return moov_size;
4186
4187     buf = av_malloc(moov_size * 2);
4188     if (!buf)
4189         return AVERROR(ENOMEM);
4190     read_buf[0] = buf;
4191     read_buf[1] = buf + moov_size;
4192
4193     /* Shift the data: the AVIO context of the output can only be used for
4194      * writing, so we re-open the same output, but for reading. It also avoids
4195      * a read/seek/write/seek back and forth. */
4196     avio_flush(s->pb);
4197     ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
4198     if (ret < 0) {
4199         av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
4200                "the second pass (faststart)\n", s->filename);
4201         goto end;
4202     }
4203
4204     /* mark the end of the shift to up to the last data we wrote, and get ready
4205      * for writing */
4206     pos_end = avio_tell(s->pb);
4207     avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
4208
4209     /* start reading at where the new moov will be placed */
4210     avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
4211     pos = avio_tell(read_pb);
4212
4213 #define READ_BLOCK do {                                                             \
4214     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size);  \
4215     read_buf_id ^= 1;                                                               \
4216 } while (0)
4217
4218     /* shift data by chunk of at most moov_size */
4219     READ_BLOCK;
4220     do {
4221         int n;
4222         READ_BLOCK;
4223         n = read_size[read_buf_id];
4224         if (n <= 0)
4225             break;
4226         avio_write(s->pb, read_buf[read_buf_id], n);
4227         pos += n;
4228     } while (pos < pos_end);
4229     avio_close(read_pb);
4230
4231 end:
4232     av_free(buf);
4233     return ret;
4234 }
4235
4236 static int mov_write_trailer(AVFormatContext *s)
4237 {
4238     MOVMuxContext *mov = s->priv_data;
4239     AVIOContext *pb = s->pb;
4240     int res = 0;
4241     int i;
4242     int64_t moov_pos;
4243
4244     /*
4245      * Before actually writing the trailer, make sure that there are no
4246      * dangling subtitles, that need a terminating sample.
4247      */
4248     for (i = 0; i < mov->nb_streams; i++) {
4249         MOVTrack *trk = &mov->tracks[i];
4250         if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4251             !trk->last_sample_is_subtitle_end) {
4252             mov_write_subtitle_end_packet(s, i, trk->track_duration);
4253             trk->last_sample_is_subtitle_end = 1;
4254         }
4255     }
4256
4257     // If there were no chapters when the header was written, but there
4258     // are chapters now, write them in the trailer.  This only works
4259     // when we are not doing fragments.
4260     if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4261         if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
4262             mov->chapter_track = mov->nb_streams++;
4263             if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4264                 goto error;
4265         }
4266     }
4267
4268     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4269         moov_pos = avio_tell(pb);
4270
4271         /* Write size of mdat tag */
4272         if (mov->mdat_size + 8 <= UINT32_MAX) {
4273             avio_seek(pb, mov->mdat_pos, SEEK_SET);
4274             avio_wb32(pb, mov->mdat_size + 8);
4275         } else {
4276             /* overwrite 'wide' placeholder atom */
4277             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
4278             /* special value: real atom size will be 64 bit value after
4279              * tag field */
4280             avio_wb32(pb, 1);
4281             ffio_wfourcc(pb, "mdat");
4282             avio_wb64(pb, mov->mdat_size + 16);
4283         }
4284         avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
4285
4286         if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4287             av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
4288             res = shift_data(s);
4289             if (res == 0) {
4290                 avio_seek(s->pb, mov->reserved_moov_pos, SEEK_SET);
4291                 mov_write_moov_tag(pb, mov, s);
4292             }
4293         } else if (mov->reserved_moov_size > 0) {
4294             int64_t size;
4295             mov_write_moov_tag(pb, mov, s);
4296             size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
4297             if (size < 8){
4298                 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
4299                 return -1;
4300             }
4301             avio_wb32(pb, size);
4302             ffio_wfourcc(pb, "free");
4303             for (i = 0; i < size; i++)
4304                 avio_w8(pb, 0);
4305             avio_seek(pb, moov_pos, SEEK_SET);
4306         } else {
4307             mov_write_moov_tag(pb, mov, s);
4308         }
4309     } else {
4310         mov_flush_fragment(s);
4311         mov_write_mfra_tag(pb, mov);
4312     }
4313
4314     for (i = 0; i < mov->nb_streams; i++) {
4315         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
4316             mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
4317             int64_t off = avio_tell(pb);
4318             uint8_t buf[7];
4319             if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
4320                 avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
4321                 avio_write(pb, buf, 7);
4322                 avio_seek(pb, off, SEEK_SET);
4323             }
4324         }
4325     }
4326
4327 error:
4328     mov_free(s);
4329
4330     return res;
4331 }
4332
4333 #if CONFIG_MOV_MUXER
4334 MOV_CLASS(mov)
4335 AVOutputFormat ff_mov_muxer = {
4336     .name              = "mov",
4337     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4338     .extensions        = "mov",
4339     .priv_data_size    = sizeof(MOVMuxContext),
4340     .audio_codec       = AV_CODEC_ID_AAC,
4341     .video_codec       = CONFIG_LIBX264_ENCODER ?
4342                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4343     .write_header      = mov_write_header,
4344     .write_packet      = mov_write_packet,
4345     .write_trailer     = mov_write_trailer,
4346     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4347     .codec_tag         = (const AVCodecTag* const []){
4348         ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
4349     },
4350     .priv_class        = &mov_muxer_class,
4351 };
4352 #endif
4353 #if CONFIG_TGP_MUXER
4354 MOV_CLASS(tgp)
4355 AVOutputFormat ff_tgp_muxer = {
4356     .name              = "3gp",
4357     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
4358     .extensions        = "3gp",
4359     .priv_data_size    = sizeof(MOVMuxContext),
4360     .audio_codec       = AV_CODEC_ID_AMR_NB,
4361     .video_codec       = AV_CODEC_ID_H263,
4362     .write_header      = mov_write_header,
4363     .write_packet      = mov_write_packet,
4364     .write_trailer     = mov_write_trailer,
4365     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4366     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4367     .priv_class        = &tgp_muxer_class,
4368 };
4369 #endif
4370 #if CONFIG_MP4_MUXER
4371 MOV_CLASS(mp4)
4372 AVOutputFormat ff_mp4_muxer = {
4373     .name              = "mp4",
4374     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
4375     .mime_type         = "application/mp4",
4376     .extensions        = "mp4",
4377     .priv_data_size    = sizeof(MOVMuxContext),
4378     .audio_codec       = AV_CODEC_ID_AAC,
4379     .video_codec       = CONFIG_LIBX264_ENCODER ?
4380                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4381     .write_header      = mov_write_header,
4382     .write_packet      = mov_write_packet,
4383     .write_trailer     = mov_write_trailer,
4384     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4385     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4386     .priv_class        = &mp4_muxer_class,
4387 };
4388 #endif
4389 #if CONFIG_PSP_MUXER
4390 MOV_CLASS(psp)
4391 AVOutputFormat ff_psp_muxer = {
4392     .name              = "psp",
4393     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
4394     .extensions        = "mp4,psp",
4395     .priv_data_size    = sizeof(MOVMuxContext),
4396     .audio_codec       = AV_CODEC_ID_AAC,
4397     .video_codec       = CONFIG_LIBX264_ENCODER ?
4398                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4399     .write_header      = mov_write_header,
4400     .write_packet      = mov_write_packet,
4401     .write_trailer     = mov_write_trailer,
4402     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4403     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4404     .priv_class        = &psp_muxer_class,
4405 };
4406 #endif
4407 #if CONFIG_TG2_MUXER
4408 MOV_CLASS(tg2)
4409 AVOutputFormat ff_tg2_muxer = {
4410     .name              = "3g2",
4411     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
4412     .extensions        = "3g2",
4413     .priv_data_size    = sizeof(MOVMuxContext),
4414     .audio_codec       = AV_CODEC_ID_AMR_NB,
4415     .video_codec       = AV_CODEC_ID_H263,
4416     .write_header      = mov_write_header,
4417     .write_packet      = mov_write_packet,
4418     .write_trailer     = mov_write_trailer,
4419     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4420     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4421     .priv_class        = &tg2_muxer_class,
4422 };
4423 #endif
4424 #if CONFIG_IPOD_MUXER
4425 MOV_CLASS(ipod)
4426 AVOutputFormat ff_ipod_muxer = {
4427     .name              = "ipod",
4428     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
4429     .mime_type         = "application/mp4",
4430     .extensions        = "m4v,m4a",
4431     .priv_data_size    = sizeof(MOVMuxContext),
4432     .audio_codec       = AV_CODEC_ID_AAC,
4433     .video_codec       = AV_CODEC_ID_H264,
4434     .write_header      = mov_write_header,
4435     .write_packet      = mov_write_packet,
4436     .write_trailer     = mov_write_trailer,
4437     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4438     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
4439     .priv_class        = &ipod_muxer_class,
4440 };
4441 #endif
4442 #if CONFIG_ISMV_MUXER
4443 MOV_CLASS(ismv)
4444 AVOutputFormat ff_ismv_muxer = {
4445     .name              = "ismv",
4446     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
4447     .mime_type         = "application/mp4",
4448     .extensions        = "ismv,isma",
4449     .priv_data_size    = sizeof(MOVMuxContext),
4450     .audio_codec       = AV_CODEC_ID_AAC,
4451     .video_codec       = AV_CODEC_ID_H264,
4452     .write_header      = mov_write_header,
4453     .write_packet      = mov_write_packet,
4454     .write_trailer     = mov_write_trailer,
4455     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4456     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4457     .priv_class        = &ismv_muxer_class,
4458 };
4459 #endif
4460 #if CONFIG_F4V_MUXER
4461 MOV_CLASS(f4v)
4462 AVOutputFormat ff_f4v_muxer = {
4463     .name              = "f4v",
4464     .long_name         = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
4465     .mime_type         = "application/f4v",
4466     .extensions        = "f4v",
4467     .priv_data_size    = sizeof(MOVMuxContext),
4468     .audio_codec       = AV_CODEC_ID_AAC,
4469     .video_codec       = AV_CODEC_ID_H264,
4470     .write_header      = mov_write_header,
4471     .write_packet      = mov_write_packet,
4472     .write_trailer     = mov_write_trailer,
4473     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
4474     .codec_tag         = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
4475     .priv_class        = &f4v_muxer_class,
4476 };
4477 #endif