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