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