]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
wavpackenc: simplify "sign = ((sample) < 0) ? 1 : 0;"
[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 or disc number */
2019 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2020                               AVFormatContext *s, int disc)
2021 {
2022     AVDictionaryEntry *t = av_dict_get(s->metadata,
2023                                        disc ? "disc" : "track",
2024                                        NULL, 0);
2025     int size = 0, track = t ? atoi(t->value) : 0;
2026     if (track) {
2027         int tracks = 0;
2028         char *slash = strchr(t->value, '/');
2029         if (slash)
2030             tracks = atoi(slash + 1);
2031         avio_wb32(pb, 32); /* size */
2032         ffio_wfourcc(pb, disc ? "disk" : "trkn");
2033         avio_wb32(pb, 24); /* size */
2034         ffio_wfourcc(pb, "data");
2035         avio_wb32(pb, 0);        // 8 bytes empty
2036         avio_wb32(pb, 0);
2037         avio_wb16(pb, 0);        // empty
2038         avio_wb16(pb, track);    // track / disc number
2039         avio_wb16(pb, tracks);   // total track / disc number
2040         avio_wb16(pb, 0);        // empty
2041         size = 32;
2042     }
2043     return size;
2044 }
2045
2046 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2047                                    const char *name, const char *tag,
2048                                    int len)
2049 {
2050     AVDictionaryEntry *t = NULL;
2051     uint8_t num;
2052     int size = 24 + len;
2053
2054     if (len != 1 && len != 4)
2055         return -1;
2056
2057     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2058         return 0;
2059     num = atoi(t->value);
2060
2061     avio_wb32(pb, size);
2062     ffio_wfourcc(pb, name);
2063     avio_wb32(pb, size - 8);
2064     ffio_wfourcc(pb, "data");
2065     avio_wb32(pb, 0x15);
2066     avio_wb32(pb, 0);
2067     if (len==4) avio_wb32(pb, num);
2068     else        avio_w8 (pb, num);
2069
2070     return size;
2071 }
2072
2073 /* iTunes meta data list */
2074 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2075                               AVFormatContext *s)
2076 {
2077     int64_t pos = avio_tell(pb);
2078     avio_wb32(pb, 0); /* size */
2079     ffio_wfourcc(pb, "ilst");
2080     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
2081     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
2082     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2083     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2084     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
2085     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
2086     mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2087     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
2088     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
2089     mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2090     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2091     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
2092     mov_write_string_metadata(s, pb, "desc",    "description",1);
2093     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
2094     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
2095     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
2096     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
2097     mov_write_int8_metadata  (s, pb, "tves",    "episode_sort",4);
2098     mov_write_int8_metadata  (s, pb, "tvsn",    "season_number",4);
2099     mov_write_int8_metadata  (s, pb, "stik",    "media_type",1);
2100     mov_write_int8_metadata  (s, pb, "hdvd",    "hd_video",  1);
2101     mov_write_int8_metadata  (s, pb, "pgap",    "gapless_playback",1);
2102     mov_write_trkn_tag(pb, mov, s, 0); // track number
2103     mov_write_trkn_tag(pb, mov, s, 1); // disc number
2104     mov_write_tmpo_tag(pb, s);
2105     return update_size(pb, pos);
2106 }
2107
2108 /* iTunes meta data tag */
2109 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2110                               AVFormatContext *s)
2111 {
2112     int size = 0;
2113     int64_t pos = avio_tell(pb);
2114     avio_wb32(pb, 0); /* size */
2115     ffio_wfourcc(pb, "meta");
2116     avio_wb32(pb, 0);
2117     mov_write_itunes_hdlr_tag(pb, mov, s);
2118     mov_write_ilst_tag(pb, mov, s);
2119     size = update_size(pb, pos);
2120     return size;
2121 }
2122
2123 static int utf8len(const uint8_t *b)
2124 {
2125     int len = 0;
2126     int val;
2127     while (*b) {
2128         GET_UTF8(val, *b++, return -1;)
2129         len++;
2130     }
2131     return len;
2132 }
2133
2134 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2135 {
2136     int val;
2137     while (*b) {
2138         GET_UTF8(val, *b++, return -1;)
2139         avio_wb16(pb, val);
2140     }
2141     avio_wb16(pb, 0x00);
2142     return 0;
2143 }
2144
2145 static uint16_t language_code(const char *str)
2146 {
2147     return (((str[0] - 0x60) & 0x1F) << 10) +
2148            (((str[1] - 0x60) & 0x1F) <<  5) +
2149            (( str[2] - 0x60) & 0x1F);
2150 }
2151
2152 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2153                                   const char *tag, const char *str)
2154 {
2155     int64_t pos = avio_tell(pb);
2156     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2157     if (!t || !utf8len(t->value))
2158         return 0;
2159     avio_wb32(pb, 0);   /* size */
2160     ffio_wfourcc(pb, tag); /* type */
2161     avio_wb32(pb, 0);   /* version + flags */
2162     if (!strcmp(tag, "yrrc"))
2163         avio_wb16(pb, atoi(t->value));
2164     else {
2165         avio_wb16(pb, language_code("eng")); /* language */
2166         avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2167         if (!strcmp(tag, "albm") &&
2168             (t = av_dict_get(s->metadata, "track", NULL, 0)))
2169             avio_w8(pb, atoi(t->value));
2170     }
2171     return update_size(pb, pos);
2172 }
2173
2174 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2175 {
2176     int64_t pos = avio_tell(pb);
2177     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2178
2179     avio_wb32(pb, 0);            // size
2180     ffio_wfourcc(pb, "chpl");
2181     avio_wb32(pb, 0x01000000);   // version + flags
2182     avio_wb32(pb, 0);            // unknown
2183     avio_w8(pb, nb_chapters);
2184
2185     for (i = 0; i < nb_chapters; i++) {
2186         AVChapter *c = s->chapters[i];
2187         AVDictionaryEntry *t;
2188         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2189
2190         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2191             int len = FFMIN(strlen(t->value), 255);
2192             avio_w8(pb, len);
2193             avio_write(pb, t->value, len);
2194         } else
2195             avio_w8(pb, 0);
2196     }
2197     return update_size(pb, pos);
2198 }
2199
2200 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2201                               AVFormatContext *s)
2202 {
2203     AVIOContext *pb_buf;
2204     int i, ret, size;
2205     uint8_t *buf;
2206
2207     for (i = 0; i < s->nb_streams; i++)
2208         if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
2209             return 0;
2210         }
2211
2212     ret = avio_open_dyn_buf(&pb_buf);
2213     if (ret < 0)
2214         return ret;
2215
2216     if (mov->mode & MODE_3GP) {
2217         mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2218         mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2219         mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2220         mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2221         mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2222         mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2223         mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2224         mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2225     } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2226         mov_write_string_metadata(s, pb_buf, "\251ART", "artist",      0);
2227         mov_write_string_metadata(s, pb_buf, "\251nam", "title",       0);
2228         mov_write_string_metadata(s, pb_buf, "\251aut", "author",      0);
2229         mov_write_string_metadata(s, pb_buf, "\251alb", "album",       0);
2230         mov_write_string_metadata(s, pb_buf, "\251day", "date",        0);
2231         mov_write_string_metadata(s, pb_buf, "\251swr", "encoder",     0);
2232         // currently ignored by mov.c
2233         mov_write_string_metadata(s, pb_buf, "\251des", "comment",     0);
2234         // add support for libquicktime, this atom is also actually read by mov.c
2235         mov_write_string_metadata(s, pb_buf, "\251cmt", "comment",     0);
2236         mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);
2237         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);
2238     } else {
2239         /* iTunes meta data */
2240         mov_write_meta_tag(pb_buf, mov, s);
2241     }
2242
2243     if (s->nb_chapters)
2244         mov_write_chpl_tag(pb_buf, s);
2245
2246     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2247         avio_wb32(pb, size + 8);
2248         ffio_wfourcc(pb, "udta");
2249         avio_write(pb, buf, size);
2250     }
2251     av_free(buf);
2252
2253     return 0;
2254 }
2255
2256 static void mov_write_psp_udta_tag(AVIOContext *pb,
2257                                    const char *str, const char *lang, int type)
2258 {
2259     int len = utf8len(str) + 1;
2260     if (len <= 0)
2261         return;
2262     avio_wb16(pb, len * 2 + 10);        /* size */
2263     avio_wb32(pb, type);                /* type */
2264     avio_wb16(pb, language_code(lang)); /* language */
2265     avio_wb16(pb, 0x01);                /* ? */
2266     ascii_to_wc(pb, str);
2267 }
2268
2269 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2270 {
2271     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2272     int64_t pos, pos2;
2273
2274     if (title) {
2275         pos = avio_tell(pb);
2276         avio_wb32(pb, 0); /* size placeholder*/
2277         ffio_wfourcc(pb, "uuid");
2278         ffio_wfourcc(pb, "USMT");
2279         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2280         avio_wb32(pb, 0xbb88695c);
2281         avio_wb32(pb, 0xfac9c740);
2282
2283         pos2 = avio_tell(pb);
2284         avio_wb32(pb, 0); /* size placeholder*/
2285         ffio_wfourcc(pb, "MTDT");
2286         avio_wb16(pb, 4);
2287
2288         // ?
2289         avio_wb16(pb, 0x0C);                 /* size */
2290         avio_wb32(pb, 0x0B);                 /* type */
2291         avio_wb16(pb, language_code("und")); /* language */
2292         avio_wb16(pb, 0x0);                  /* ? */
2293         avio_wb16(pb, 0x021C);               /* data */
2294
2295         mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
2296         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
2297         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2298
2299         update_size(pb, pos2);
2300         return update_size(pb, pos);
2301     }
2302
2303     return 0;
2304 }
2305
2306 static void build_chunks(MOVTrack *trk)
2307 {
2308     int i;
2309     MOVIentry *chunk = &trk->cluster[0];
2310     uint64_t chunkSize = chunk->size;
2311     chunk->chunkNum = 1;
2312     if (trk->chunkCount)
2313         return;
2314     trk->chunkCount = 1;
2315     for (i = 1; i<trk->entry; i++){
2316         if (chunk->pos + chunkSize == trk->cluster[i].pos &&
2317             chunkSize + trk->cluster[i].size < (1<<20)){
2318             chunkSize             += trk->cluster[i].size;
2319             chunk->samples_in_chunk += trk->cluster[i].entries;
2320         } else {
2321             trk->cluster[i].chunkNum = chunk->chunkNum+1;
2322             chunk=&trk->cluster[i];
2323             chunkSize = chunk->size;
2324             trk->chunkCount++;
2325         }
2326     }
2327 }
2328
2329 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2330                               AVFormatContext *s)
2331 {
2332     int i;
2333     int64_t pos = avio_tell(pb);
2334     int not_first[AVMEDIA_TYPE_NB]={0};
2335     avio_wb32(pb, 0); /* size placeholder*/
2336     ffio_wfourcc(pb, "moov");
2337
2338     for (i = 0; i < mov->nb_streams; i++) {
2339         if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2340             continue;
2341
2342         mov->tracks[i].time     = mov->time;
2343         mov->tracks[i].track_id = i + 1;
2344
2345         if (mov->tracks[i].entry)
2346             build_chunks(&mov->tracks[i]);
2347     }
2348
2349     if (mov->chapter_track)
2350         for (i = 0; i < s->nb_streams; i++) {
2351             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2352             mov->tracks[i].tref_id  = mov->tracks[mov->chapter_track].track_id;
2353         }
2354     for (i = 0; i < mov->nb_streams; i++) {
2355         if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
2356             mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
2357             mov->tracks[i].tref_id =
2358                 mov->tracks[mov->tracks[i].src_track].track_id;
2359         }
2360     }
2361     for (i = 0; i < mov->nb_streams; i++) {
2362         if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
2363             int src_trk = mov->tracks[i].src_track;
2364             mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
2365             mov->tracks[src_trk].tref_id  = mov->tracks[i].track_id;
2366             mov->tracks[i].track_duration = mov->tracks[src_trk].track_duration;
2367         }
2368     }
2369
2370     mov_write_mvhd_tag(pb, mov);
2371     if (mov->mode != MODE_MOV && !mov->iods_skip)
2372         mov_write_iods_tag(pb, mov);
2373     for (i = 0; i < mov->nb_streams; i++) {
2374         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2375             if (i < s->nb_streams){
2376                 int codec_type= s->streams[i]->codec->codec_type;
2377                 if (codec_type==AVMEDIA_TYPE_AUDIO || codec_type==AVMEDIA_TYPE_SUBTITLE){
2378                     mov->tracks[i].secondary= not_first[codec_type];
2379                     not_first[codec_type]= 1;
2380                 }
2381             }
2382             mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2383         }
2384     }
2385     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2386         mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2387
2388     if (mov->mode == MODE_PSP)
2389         mov_write_uuidusmt_tag(pb, s);
2390     else
2391         mov_write_udta_tag(pb, mov, s);
2392
2393     return update_size(pb, pos);
2394 }
2395
2396 static void param_write_int(AVIOContext *pb, const char *name, int value)
2397 {
2398     avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2399 }
2400
2401 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2402 {
2403     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2404 }
2405
2406 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2407 {
2408     char buf[150];
2409     len = FFMIN(sizeof(buf) / 2 - 1, len);
2410     ff_data_to_hex(buf, value, len, 0);
2411     buf[2 * len] = '\0';
2412     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2413 }
2414
2415 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2416 {
2417     int64_t pos = avio_tell(pb);
2418     int i;
2419     static const uint8_t uuid[] = {
2420         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2421         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2422     };
2423
2424     avio_wb32(pb, 0);
2425     ffio_wfourcc(pb, "uuid");
2426     avio_write(pb, uuid, sizeof(uuid));
2427     avio_wb32(pb, 0);
2428
2429     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2430     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2431     avio_printf(pb, "<head>\n");
2432     avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2433                     LIBAVFORMAT_IDENT);
2434     avio_printf(pb, "</head>\n");
2435     avio_printf(pb, "<body>\n");
2436     avio_printf(pb, "<switch>\n");
2437     for (i = 0; i < mov->nb_streams; i++) {
2438         MOVTrack *track = &mov->tracks[i];
2439         const char *type;
2440         /* track->track_id is initialized in write_moov, and thus isn't known
2441          * here yet */
2442         int track_id = i + 1;
2443
2444         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2445             type = "video";
2446         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2447             type = "audio";
2448         } else {
2449             continue;
2450         }
2451         avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
2452                                                        track->enc->bit_rate);
2453         param_write_int(pb, "systemBitrate", track->enc->bit_rate);
2454         param_write_int(pb, "trackID", track_id);
2455         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2456             if (track->enc->codec_id == AV_CODEC_ID_H264) {
2457                 uint8_t *ptr;
2458                 int size = track->enc->extradata_size;
2459                 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
2460                                                    &size)) {
2461                     param_write_hex(pb, "CodecPrivateData",
2462                                     ptr ? ptr : track->enc->extradata,
2463                                     size);
2464                     av_free(ptr);
2465                 }
2466                 param_write_string(pb, "FourCC", "H264");
2467             } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
2468                 param_write_string(pb, "FourCC", "WVC1");
2469                 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2470                                 track->enc->extradata_size);
2471             }
2472             param_write_int(pb, "MaxWidth", track->enc->width);
2473             param_write_int(pb, "MaxHeight", track->enc->height);
2474             param_write_int(pb, "DisplayWidth", track->enc->width);
2475             param_write_int(pb, "DisplayHeight", track->enc->height);
2476         } else {
2477             if (track->enc->codec_id == AV_CODEC_ID_AAC) {
2478                 param_write_string(pb, "FourCC", "AACL");
2479             } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
2480                 param_write_string(pb, "FourCC", "WMAP");
2481             }
2482             param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2483                             track->enc->extradata_size);
2484             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
2485                                                              track->enc->codec_id));
2486             param_write_int(pb, "Channels", track->enc->channels);
2487             param_write_int(pb, "SamplingRate", track->enc->sample_rate);
2488             param_write_int(pb, "BitsPerSample", 16);
2489             param_write_int(pb, "PacketSize", track->enc->block_align ?
2490                                               track->enc->block_align : 4);
2491         }
2492         avio_printf(pb, "</%s>\n", type);
2493     }
2494     avio_printf(pb, "</switch>\n");
2495     avio_printf(pb, "</body>\n");
2496     avio_printf(pb, "</smil>\n");
2497
2498     return update_size(pb, pos);
2499 }
2500
2501 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2502 {
2503     avio_wb32(pb, 16);
2504     ffio_wfourcc(pb, "mfhd");
2505     avio_wb32(pb, 0);
2506     avio_wb32(pb, mov->fragments);
2507     return 0;
2508 }
2509
2510 static int mov_write_tfhd_tag(AVIOContext *pb, MOVTrack *track,
2511                               int64_t moof_offset)
2512 {
2513     int64_t pos = avio_tell(pb);
2514     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2515                      MOV_TFHD_BASE_DATA_OFFSET;
2516     if (!track->entry) {
2517         flags |= MOV_TFHD_DURATION_IS_EMPTY;
2518     } else {
2519         flags |= MOV_TFHD_DEFAULT_FLAGS;
2520     }
2521
2522     /* Don't set a default sample size, the silverlight player refuses
2523      * to play files with that set. Don't set a default sample duration,
2524      * WMP freaks out if it is set. Don't set a base data offset, PIFF
2525      * file format says it MUST NOT be set. */
2526     if (track->mode == MODE_ISM)
2527         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2528                    MOV_TFHD_BASE_DATA_OFFSET);
2529
2530     avio_wb32(pb, 0); /* size placeholder */
2531     ffio_wfourcc(pb, "tfhd");
2532     avio_w8(pb, 0); /* version */
2533     avio_wb24(pb, flags);
2534
2535     avio_wb32(pb, track->track_id); /* track-id */
2536     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
2537         avio_wb64(pb, moof_offset);
2538     if (flags & MOV_TFHD_DEFAULT_DURATION) {
2539         track->default_duration = get_cluster_duration(track, 0);
2540         avio_wb32(pb, track->default_duration);
2541     }
2542     if (flags & MOV_TFHD_DEFAULT_SIZE) {
2543         track->default_size = track->entry ? track->cluster[0].size : 1;
2544         avio_wb32(pb, track->default_size);
2545     } else
2546         track->default_size = -1;
2547
2548     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
2549         track->default_sample_flags =
2550             track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
2551             (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2552             MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
2553         avio_wb32(pb, track->default_sample_flags);
2554     }
2555
2556     return update_size(pb, pos);
2557 }
2558
2559 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2560 {
2561     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2562            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2563 }
2564
2565 static int mov_write_trun_tag(AVIOContext *pb, MOVTrack *track)
2566 {
2567     int64_t pos = avio_tell(pb);
2568     uint32_t flags = MOV_TRUN_DATA_OFFSET;
2569     int i;
2570
2571     for (i = 0; i < track->entry; i++) {
2572         if (get_cluster_duration(track, i) != track->default_duration)
2573             flags |= MOV_TRUN_SAMPLE_DURATION;
2574         if (track->cluster[i].size != track->default_size)
2575             flags |= MOV_TRUN_SAMPLE_SIZE;
2576         if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
2577             flags |= MOV_TRUN_SAMPLE_FLAGS;
2578     }
2579     if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
2580         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
2581     if (track->flags & MOV_TRACK_CTTS)
2582         flags |= MOV_TRUN_SAMPLE_CTS;
2583
2584     avio_wb32(pb, 0); /* size placeholder */
2585     ffio_wfourcc(pb, "trun");
2586     avio_w8(pb, 0); /* version */
2587     avio_wb24(pb, flags);
2588
2589     avio_wb32(pb, track->entry); /* sample count */
2590     track->moof_size_offset = avio_tell(pb);
2591     avio_wb32(pb, 0); /* data offset */
2592     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
2593         avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
2594
2595     for (i = 0; i < track->entry; i++) {
2596         if (flags & MOV_TRUN_SAMPLE_DURATION)
2597             avio_wb32(pb, get_cluster_duration(track, i));
2598         if (flags & MOV_TRUN_SAMPLE_SIZE)
2599             avio_wb32(pb, track->cluster[i].size);
2600         if (flags & MOV_TRUN_SAMPLE_FLAGS)
2601             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
2602         if (flags & MOV_TRUN_SAMPLE_CTS)
2603             avio_wb32(pb, track->cluster[i].cts);
2604     }
2605
2606     return update_size(pb, pos);
2607 }
2608
2609 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2610 {
2611     int64_t pos = avio_tell(pb);
2612     static const uint8_t uuid[] = {
2613         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2614         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2615     };
2616
2617     avio_wb32(pb, 0); /* size placeholder */
2618     ffio_wfourcc(pb, "uuid");
2619     avio_write(pb, uuid, sizeof(uuid));
2620     avio_w8(pb, 1);
2621     avio_wb24(pb, 0);
2622     avio_wb64(pb, track->frag_start);
2623     avio_wb64(pb, track->start_dts + track->track_duration -
2624                   track->cluster[0].dts);
2625
2626     return update_size(pb, pos);
2627 }
2628
2629 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2630                               MOVTrack *track, int entry)
2631 {
2632     int n = track->nb_frag_info - 1 - entry, i;
2633     int size = 8 + 16 + 4 + 1 + 16*n;
2634     static const uint8_t uuid[] = {
2635         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2636         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2637     };
2638
2639     if (entry < 0)
2640         return 0;
2641
2642     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2643     avio_wb32(pb, size);
2644     ffio_wfourcc(pb, "uuid");
2645     avio_write(pb, uuid, sizeof(uuid));
2646     avio_w8(pb, 1);
2647     avio_wb24(pb, 0);
2648     avio_w8(pb, n);
2649     for (i = 0; i < n; i++) {
2650         int index = entry + 1 + i;
2651         avio_wb64(pb, track->frag_info[index].time);
2652         avio_wb64(pb, track->frag_info[index].duration);
2653     }
2654     if (n < mov->ism_lookahead) {
2655         int free_size = 16 * (mov->ism_lookahead - n);
2656         avio_wb32(pb, free_size);
2657         ffio_wfourcc(pb, "free");
2658         ffio_fill(pb, 0, free_size - 8);
2659     }
2660
2661     return 0;
2662 }
2663
2664 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2665                                MOVTrack *track)
2666 {
2667     int64_t pos = avio_tell(pb);
2668     int i;
2669     for (i = 0; i < mov->ism_lookahead; i++) {
2670         /* Update the tfrf tag for the last ism_lookahead fragments,
2671          * nb_frag_info - 1 is the next fragment to be written. */
2672         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2673     }
2674     avio_seek(pb, pos, SEEK_SET);
2675     return 0;
2676 }
2677
2678 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
2679                               MOVTrack *track, int64_t moof_offset)
2680 {
2681     int64_t pos = avio_tell(pb);
2682     avio_wb32(pb, 0); /* size placeholder */
2683     ffio_wfourcc(pb, "traf");
2684
2685     mov_write_tfhd_tag(pb, track, moof_offset);
2686     mov_write_trun_tag(pb, track);
2687     if (mov->mode == MODE_ISM) {
2688         mov_write_tfxd_tag(pb, track);
2689
2690         if (mov->ism_lookahead) {
2691             int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
2692
2693             track->tfrf_offset = avio_tell(pb);
2694             avio_wb32(pb, 8 + size);
2695             ffio_wfourcc(pb, "free");
2696             for (i = 0; i < size; i++)
2697                 avio_w8(pb, 0);
2698         }
2699     }
2700
2701     return update_size(pb, pos);
2702 }
2703
2704 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
2705 {
2706     int64_t pos = avio_tell(pb), end;
2707     int i, moof_size;
2708
2709     avio_wb32(pb, 0); /* size placeholder */
2710     ffio_wfourcc(pb, "moof");
2711
2712     mov_write_mfhd_tag(pb, mov);
2713     for (i = 0; i < mov->nb_streams; i++) {
2714         MOVTrack *track = &mov->tracks[i];
2715         if (tracks >= 0 && i != tracks)
2716             continue;
2717         if (!track->entry)
2718             continue;
2719         mov_write_traf_tag(pb, mov, track, pos);
2720     }
2721
2722     end = avio_tell(pb);
2723     moof_size = end - pos;
2724     for (i = 0; i < mov->nb_streams; i++) {
2725         MOVTrack *track = &mov->tracks[i];
2726         if (tracks >= 0 && i != tracks)
2727             continue;
2728         if (!track->entry)
2729             continue;
2730         avio_seek(pb, mov->tracks[i].moof_size_offset, SEEK_SET);
2731         avio_wb32(pb, moof_size + 8 + mov->tracks[i].data_offset);
2732     }
2733     avio_seek(pb, end, SEEK_SET);
2734
2735     return update_size(pb, pos);
2736 }
2737
2738 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
2739 {
2740     int64_t pos = avio_tell(pb);
2741     int i;
2742
2743     avio_wb32(pb, 0); /* size placeholder */
2744     ffio_wfourcc(pb, "tfra");
2745     avio_w8(pb, 1); /* version */
2746     avio_wb24(pb, 0);
2747
2748     avio_wb32(pb, track->track_id);
2749     avio_wb32(pb, 0); /* length of traf/trun/sample num */
2750     avio_wb32(pb, track->nb_frag_info);
2751     for (i = 0; i < track->nb_frag_info; i++) {
2752         avio_wb64(pb, track->frag_info[i].time);
2753         avio_wb64(pb, track->frag_info[i].offset);
2754         avio_w8(pb, 1); /* traf number */
2755         avio_w8(pb, 1); /* trun number */
2756         avio_w8(pb, 1); /* sample number */
2757     }
2758
2759     return update_size(pb, pos);
2760 }
2761
2762 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
2763 {
2764     int64_t pos = avio_tell(pb);
2765     int i;
2766
2767     avio_wb32(pb, 0); /* size placeholder */
2768     ffio_wfourcc(pb, "mfra");
2769     /* An empty mfra atom is enough to indicate to the publishing point that
2770      * the stream has ended. */
2771     if (mov->flags & FF_MOV_FLAG_ISML)
2772         return update_size(pb, pos);
2773
2774     for (i = 0; i < mov->nb_streams; i++) {
2775         MOVTrack *track = &mov->tracks[i];
2776         if (track->nb_frag_info)
2777             mov_write_tfra_tag(pb, track);
2778     }
2779
2780     avio_wb32(pb, 16);
2781     ffio_wfourcc(pb, "mfro");
2782     avio_wb32(pb, 0); /* version + flags */
2783     avio_wb32(pb, avio_tell(pb) + 4 - pos);
2784
2785     return update_size(pb, pos);
2786 }
2787
2788 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
2789 {
2790     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
2791     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
2792
2793     mov->mdat_pos = avio_tell(pb);
2794     avio_wb32(pb, 0); /* size placeholder*/
2795     ffio_wfourcc(pb, "mdat");
2796     return 0;
2797 }
2798
2799 /* TODO: This needs to be more general */
2800 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
2801 {
2802     MOVMuxContext *mov = s->priv_data;
2803     int64_t pos = avio_tell(pb);
2804     int has_h264 = 0, has_video = 0;
2805     int minor = 0x200;
2806     int i;
2807
2808     for (i = 0; i < s->nb_streams; i++) {
2809         AVStream *st = s->streams[i];
2810         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2811             has_video = 1;
2812         if (st->codec->codec_id == AV_CODEC_ID_H264)
2813             has_h264 = 1;
2814     }
2815
2816     avio_wb32(pb, 0); /* size */
2817     ffio_wfourcc(pb, "ftyp");
2818
2819     if (mov->mode == MODE_3GP) {
2820         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
2821         minor =     has_h264 ?   0x100 :   0x200;
2822     } else if (mov->mode & MODE_3G2) {
2823         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
2824         minor =     has_h264 ? 0x20000 : 0x10000;
2825     } else if (mov->mode == MODE_PSP)
2826         ffio_wfourcc(pb, "MSNV");
2827     else if (mov->mode == MODE_MP4)
2828         ffio_wfourcc(pb, "isom");
2829     else if (mov->mode == MODE_IPOD)
2830         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
2831     else if (mov->mode == MODE_ISM)
2832         ffio_wfourcc(pb, "isml");
2833     else if (mov->mode == MODE_F4V)
2834         ffio_wfourcc(pb, "f4v ");
2835     else
2836         ffio_wfourcc(pb, "qt  ");
2837
2838     avio_wb32(pb, minor);
2839
2840     if (mov->mode == MODE_MOV)
2841         ffio_wfourcc(pb, "qt  ");
2842     else if (mov->mode == MODE_ISM) {
2843         ffio_wfourcc(pb, "piff");
2844         ffio_wfourcc(pb, "iso2");
2845     } else {
2846         ffio_wfourcc(pb, "isom");
2847         ffio_wfourcc(pb, "iso2");
2848         if (has_h264)
2849             ffio_wfourcc(pb, "avc1");
2850     }
2851
2852     if (mov->mode == MODE_3GP)
2853         ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
2854     else if (mov->mode & MODE_3G2)
2855         ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
2856     else if (mov->mode == MODE_PSP)
2857         ffio_wfourcc(pb, "MSNV");
2858     else if (mov->mode == MODE_MP4)
2859         ffio_wfourcc(pb, "mp41");
2860     return update_size(pb, pos);
2861 }
2862
2863 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
2864 {
2865     AVCodecContext *video_codec = s->streams[0]->codec;
2866     AVCodecContext *audio_codec = s->streams[1]->codec;
2867     int audio_rate = audio_codec->sample_rate;
2868     int frame_rate = ((video_codec->time_base.den) * (0x10000)) / (video_codec->time_base.num);
2869     int audio_kbitrate = audio_codec->bit_rate / 1000;
2870     int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
2871
2872     avio_wb32(pb, 0x94); /* size */
2873     ffio_wfourcc(pb, "uuid");
2874     ffio_wfourcc(pb, "PROF");
2875
2876     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2877     avio_wb32(pb, 0xbb88695c);
2878     avio_wb32(pb, 0xfac9c740);
2879
2880     avio_wb32(pb, 0x0);  /* ? */
2881     avio_wb32(pb, 0x3);  /* 3 sections ? */
2882
2883     avio_wb32(pb, 0x14); /* size */
2884     ffio_wfourcc(pb, "FPRF");
2885     avio_wb32(pb, 0x0);  /* ? */
2886     avio_wb32(pb, 0x0);  /* ? */
2887     avio_wb32(pb, 0x0);  /* ? */
2888
2889     avio_wb32(pb, 0x2c);  /* size */
2890     ffio_wfourcc(pb, "APRF"); /* audio */
2891     avio_wb32(pb, 0x0);
2892     avio_wb32(pb, 0x2);   /* TrackID */
2893     ffio_wfourcc(pb, "mp4a");
2894     avio_wb32(pb, 0x20f);
2895     avio_wb32(pb, 0x0);
2896     avio_wb32(pb, audio_kbitrate);
2897     avio_wb32(pb, audio_kbitrate);
2898     avio_wb32(pb, audio_rate);
2899     avio_wb32(pb, audio_codec->channels);
2900
2901     avio_wb32(pb, 0x34);  /* size */
2902     ffio_wfourcc(pb, "VPRF");   /* video */
2903     avio_wb32(pb, 0x0);
2904     avio_wb32(pb, 0x1);    /* TrackID */
2905     if (video_codec->codec_id == AV_CODEC_ID_H264) {
2906         ffio_wfourcc(pb, "avc1");
2907         avio_wb16(pb, 0x014D);
2908         avio_wb16(pb, 0x0015);
2909     } else {
2910         ffio_wfourcc(pb, "mp4v");
2911         avio_wb16(pb, 0x0000);
2912         avio_wb16(pb, 0x0103);
2913     }
2914     avio_wb32(pb, 0x0);
2915     avio_wb32(pb, video_kbitrate);
2916     avio_wb32(pb, video_kbitrate);
2917     avio_wb32(pb, frame_rate);
2918     avio_wb32(pb, frame_rate);
2919     avio_wb16(pb, video_codec->width);
2920     avio_wb16(pb, video_codec->height);
2921     avio_wb32(pb, 0x010001); /* ? */
2922 }
2923
2924 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
2925 {
2926     uint32_t c = -1;
2927     int i, closed_gop = 0;
2928
2929     for (i = 0; i < pkt->size - 4; i++) {
2930         c = (c << 8) + pkt->data[i];
2931         if (c == 0x1b8) { // gop
2932             closed_gop = pkt->data[i + 4] >> 6 & 0x01;
2933         } else if (c == 0x100) { // pic
2934             int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
2935             if (!temp_ref || closed_gop) // I picture is not reordered
2936                 *flags = MOV_SYNC_SAMPLE;
2937             else
2938                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
2939             break;
2940         }
2941     }
2942     return 0;
2943 }
2944
2945 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
2946 {
2947     const uint8_t *start, *next, *end = pkt->data + pkt->size;
2948     int seq = 0, entry = 0;
2949     int key = pkt->flags & AV_PKT_FLAG_KEY;
2950     start = find_next_marker(pkt->data, end);
2951     for (next = start; next < end; start = next) {
2952         next = find_next_marker(start + 4, end);
2953         switch (AV_RB32(start)) {
2954         case VC1_CODE_SEQHDR:
2955             seq = 1;
2956             break;
2957         case VC1_CODE_ENTRYPOINT:
2958             entry = 1;
2959             break;
2960         case VC1_CODE_SLICE:
2961             trk->vc1_info.slices = 1;
2962             break;
2963         }
2964     }
2965     if (!trk->entry && !fragment) {
2966         /* First packet in first fragment */
2967         trk->vc1_info.first_packet_seq   = seq;
2968         trk->vc1_info.first_packet_entry = entry;
2969     } else if ((seq && !trk->vc1_info.packet_seq) ||
2970                (entry && !trk->vc1_info.packet_entry)) {
2971         int i;
2972         for (i = 0; i < trk->entry; i++)
2973             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
2974         trk->has_keyframes = 0;
2975         if (seq)
2976             trk->vc1_info.packet_seq = 1;
2977         if (entry)
2978             trk->vc1_info.packet_entry = 1;
2979         if (!fragment) {
2980             /* First fragment */
2981             if ((!seq   || trk->vc1_info.first_packet_seq) &&
2982                 (!entry || trk->vc1_info.first_packet_entry)) {
2983                 /* First packet had the same headers as this one, readd the
2984                  * sync sample flag. */
2985                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
2986                 trk->has_keyframes = 1;
2987             }
2988         }
2989     }
2990     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
2991         key = seq && entry;
2992     else if (trk->vc1_info.packet_seq)
2993         key = seq;
2994     else if (trk->vc1_info.packet_entry)
2995         key = entry;
2996     if (key) {
2997         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
2998         trk->has_keyframes++;
2999     }
3000 }
3001
3002 static int get_moov_size(AVFormatContext *s)
3003 {
3004     int ret;
3005     uint8_t *buf;
3006     AVIOContext *moov_buf;
3007     MOVMuxContext *mov = s->priv_data;
3008
3009     if ((ret = avio_open_dyn_buf(&moov_buf)) < 0)
3010         return ret;
3011     mov_write_moov_tag(moov_buf, mov, s);
3012     ret = avio_close_dyn_buf(moov_buf, &buf);
3013     av_free(buf);
3014     return ret;
3015 }
3016
3017 static int mov_flush_fragment(AVFormatContext *s)
3018 {
3019     MOVMuxContext *mov = s->priv_data;
3020     int i, first_track = -1;
3021     int64_t mdat_size = 0;
3022
3023     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3024         return 0;
3025
3026     if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
3027         int64_t pos = avio_tell(s->pb);
3028         uint8_t *buf;
3029         int buf_size, moov_size;
3030
3031         for (i = 0; i < mov->nb_streams; i++)
3032             if (!mov->tracks[i].entry)
3033                 break;
3034         /* Don't write the initial moov unless all tracks have data */
3035         if (i < mov->nb_streams)
3036             return 0;
3037
3038         moov_size = get_moov_size(s);
3039         for (i = 0; i < mov->nb_streams; i++)
3040             mov->tracks[i].data_offset = pos + moov_size + 8;
3041
3042         mov_write_moov_tag(s->pb, mov, s);
3043
3044         buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
3045         mov->mdat_buf = NULL;
3046         avio_wb32(s->pb, buf_size + 8);
3047         ffio_wfourcc(s->pb, "mdat");
3048         avio_write(s->pb, buf, buf_size);
3049         av_free(buf);
3050
3051         mov->fragments++;
3052         mov->mdat_size = 0;
3053         for (i = 0; i < mov->nb_streams; i++) {
3054             if (mov->tracks[i].entry)
3055                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
3056                                              mov->tracks[i].track_duration -
3057                                              mov->tracks[i].cluster[0].dts;
3058             mov->tracks[i].entry = 0;
3059         }
3060         avio_flush(s->pb);
3061         return 0;
3062     }
3063
3064     for (i = 0; i < mov->nb_streams; i++) {
3065         MOVTrack *track = &mov->tracks[i];
3066         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
3067             track->data_offset = 0;
3068         else
3069             track->data_offset = mdat_size;
3070         if (!track->mdat_buf)
3071             continue;
3072         mdat_size += avio_tell(track->mdat_buf);
3073         if (first_track < 0)
3074             first_track = i;
3075     }
3076
3077     if (!mdat_size)
3078         return 0;
3079
3080     for (i = 0; i < mov->nb_streams; i++) {
3081         MOVTrack *track = &mov->tracks[i];
3082         int buf_size, write_moof = 1, moof_tracks = -1;
3083         uint8_t *buf;
3084         int64_t duration = 0;
3085
3086         if (track->entry)
3087             duration = track->start_dts + track->track_duration -
3088                        track->cluster[0].dts;
3089         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
3090             if (!track->mdat_buf)
3091                 continue;
3092             mdat_size = avio_tell(track->mdat_buf);
3093             moof_tracks = i;
3094         } else {
3095             write_moof = i == first_track;
3096         }
3097
3098         if (write_moof) {
3099             MOVFragmentInfo *info;
3100             avio_flush(s->pb);
3101             track->nb_frag_info++;
3102             if (track->nb_frag_info >= track->frag_info_capacity) {
3103                 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3104                 if (av_reallocp_array(&track->frag_info,
3105                                       new_capacity,
3106                                       sizeof(*track->frag_info)))
3107                     return AVERROR(ENOMEM);
3108                 track->frag_info_capacity = new_capacity;
3109             }
3110             info = &track->frag_info[track->nb_frag_info - 1];
3111             info->offset   = avio_tell(s->pb);
3112             info->time     = mov->tracks[i].frag_start;
3113             info->duration = duration;
3114             mov_write_tfrf_tags(s->pb, mov, track);
3115
3116             mov_write_moof_tag(s->pb, mov, moof_tracks);
3117             info->tfrf_offset = track->tfrf_offset;
3118             mov->fragments++;
3119
3120             avio_wb32(s->pb, mdat_size + 8);
3121             ffio_wfourcc(s->pb, "mdat");
3122         }
3123
3124         if (track->entry)
3125             track->frag_start += duration;
3126         track->entry = 0;
3127         if (!track->mdat_buf)
3128             continue;
3129         buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
3130         track->mdat_buf = NULL;
3131
3132         avio_write(s->pb, buf, buf_size);
3133         av_free(buf);
3134     }
3135
3136     mov->mdat_size = 0;
3137
3138     avio_flush(s->pb);
3139     return 0;
3140 }
3141
3142 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3143 {
3144     MOVMuxContext *mov = s->priv_data;
3145     AVIOContext *pb = s->pb;
3146     MOVTrack *trk = &mov->tracks[pkt->stream_index];
3147     AVCodecContext *enc = trk->enc;
3148     unsigned int samples_in_chunk = 0;
3149     int size = pkt->size;
3150     uint8_t *reformatted_data = NULL;
3151
3152     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
3153         int ret;
3154         if (mov->fragments > 0) {
3155             if (!trk->mdat_buf) {
3156                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
3157                     return ret;
3158             }
3159             pb = trk->mdat_buf;
3160         } else {
3161             if (!mov->mdat_buf) {
3162                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
3163                     return ret;
3164             }
3165             pb = mov->mdat_buf;
3166         }
3167     }
3168
3169     if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
3170         /* We must find out how many AMR blocks there are in one packet */
3171         static uint16_t packed_size[16] =
3172             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
3173         int len = 0;
3174
3175         while (len < size && samples_in_chunk < 100) {
3176             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
3177             samples_in_chunk++;
3178         }
3179         if (samples_in_chunk > 1) {
3180             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
3181             return -1;
3182         }
3183     } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
3184                enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
3185         samples_in_chunk = enc->frame_size;
3186     } else if (trk->sample_size)
3187         samples_in_chunk = size / trk->sample_size;
3188     else
3189         samples_in_chunk = 1;
3190
3191     /* copy extradata if it exists */
3192     if (trk->vos_len == 0 && enc->extradata_size > 0) {
3193         trk->vos_len  = enc->extradata_size;
3194         trk->vos_data = av_malloc(trk->vos_len);
3195         memcpy(trk->vos_data, enc->extradata, trk->vos_len);
3196     }
3197
3198     if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
3199         (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
3200         if (!s->streams[pkt->stream_index]->nb_frames) {
3201             av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
3202                    "use audio bitstream filter 'aac_adtstoasc' to fix it "
3203                    "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
3204             return -1;
3205         }
3206         av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
3207     }
3208     if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {
3209         /* from x264 or from bytestream h264 */
3210         /* nal reformating needed */
3211         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3212             ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
3213                                        &size);
3214             avio_write(pb, reformatted_data, size);
3215         } else {
3216             size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
3217         }
3218     } else {
3219         avio_write(pb, pkt->data, size);
3220     }
3221
3222     if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
3223          enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
3224         /* copy frame to create needed atoms */
3225         trk->vos_len  = size;
3226         trk->vos_data = av_malloc(size);
3227         if (!trk->vos_data)
3228             return AVERROR(ENOMEM);
3229         memcpy(trk->vos_data, pkt->data, size);
3230     }
3231
3232     if (trk->entry >= trk->cluster_capacity) {
3233         unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
3234         if (av_reallocp_array(&trk->cluster, new_capacity,
3235                               sizeof(*trk->cluster)))
3236             return AVERROR(ENOMEM);
3237         trk->cluster_capacity = new_capacity;
3238     }
3239
3240     trk->cluster[trk->entry].pos              = avio_tell(pb) - size;
3241     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
3242     trk->cluster[trk->entry].chunkNum         = 0;
3243     trk->cluster[trk->entry].size             = size;
3244     trk->cluster[trk->entry].entries          = samples_in_chunk;
3245     trk->cluster[trk->entry].dts              = pkt->dts;
3246     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
3247         /* First packet of a new fragment. We already wrote the duration
3248          * of the last packet of the previous fragment based on track_duration,
3249          * which might not exactly match our dts. Therefore adjust the dts
3250          * of this packet to be what the previous packets duration implies. */
3251         trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
3252     }
3253     if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !supports_edts(mov)) {
3254         trk->cluster[trk->entry].dts = trk->start_dts = 0;
3255     }
3256     if (trk->start_dts == AV_NOPTS_VALUE)
3257         trk->start_dts = pkt->dts;
3258     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
3259     trk->last_sample_is_subtitle_end = 0;
3260
3261     if (pkt->pts == AV_NOPTS_VALUE) {
3262         av_log(s, AV_LOG_WARNING, "pts has no value\n");
3263         pkt->pts = pkt->dts;
3264     }
3265     if (pkt->dts != pkt->pts)
3266         trk->flags |= MOV_TRACK_CTTS;
3267     trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;
3268     trk->cluster[trk->entry].flags = 0;
3269     if (enc->codec_id == AV_CODEC_ID_VC1) {
3270         mov_parse_vc1_frame(pkt, trk, mov->fragments);
3271     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
3272         if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
3273             trk->entry > 0) { // force sync sample for the first key frame
3274             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
3275             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
3276                 trk->flags |= MOV_TRACK_STPS;
3277         } else {
3278             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
3279         }
3280         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
3281             trk->has_keyframes++;
3282     }
3283     trk->entry++;
3284     trk->sample_count += samples_in_chunk;
3285     mov->mdat_size    += size;
3286
3287     avio_flush(pb);
3288
3289     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
3290         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
3291                                  reformatted_data, size);
3292     av_free(reformatted_data);
3293     return 0;
3294 }
3295
3296 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
3297 {
3298         MOVMuxContext *mov = s->priv_data;
3299         MOVTrack *trk = &mov->tracks[pkt->stream_index];
3300         AVCodecContext *enc = trk->enc;
3301         int64_t frag_duration = 0;
3302         int size = pkt->size;
3303
3304         if (!pkt->size)
3305             return 0;             /* Discard 0 sized packets */
3306
3307         if (trk->entry && pkt->stream_index < s->nb_streams)
3308             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
3309                                          s->streams[pkt->stream_index]->time_base,
3310                                          AV_TIME_BASE_Q);
3311         if ((mov->max_fragment_duration &&
3312              frag_duration >= mov->max_fragment_duration) ||
3313              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
3314              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
3315               enc->codec_type == AVMEDIA_TYPE_VIDEO &&
3316               trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
3317             if (frag_duration >= mov->min_fragment_duration)
3318                 mov_flush_fragment(s);
3319         }
3320
3321         return ff_mov_write_packet(s, pkt);
3322 }
3323
3324 static int mov_write_subtitle_end_packet(AVFormatContext *s,
3325                                          int stream_index,
3326                                          int64_t dts) {
3327     AVPacket end;
3328     uint8_t data[2] = {0};
3329     int ret;
3330
3331     av_init_packet(&end);
3332     end.size = sizeof(data);
3333     end.data = data;
3334     end.pts = dts;
3335     end.dts = dts;
3336     end.duration = 0;
3337     end.stream_index = stream_index;
3338
3339     ret = mov_write_single_packet(s, &end);
3340     av_free_packet(&end);
3341
3342     return ret;
3343 }
3344
3345 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3346 {
3347     if (!pkt) {
3348         mov_flush_fragment(s);
3349         return 1;
3350     } else {
3351         int i;
3352         MOVMuxContext *mov = s->priv_data;
3353
3354         if (!pkt->size) return 0; /* Discard 0 sized packets */
3355
3356         /*
3357          * Subtitles require special handling.
3358          *
3359          * 1) For full complaince, every track must have a sample at
3360          * dts == 0, which is rarely true for subtitles. So, as soon
3361          * as we see any packet with dts > 0, write an empty subtitle
3362          * at dts == 0 for any subtitle track with no samples in it.
3363          *
3364          * 2) For each subtitle track, check if the current packet's
3365          * dts is past the duration of the last subtitle sample. If
3366          * so, we now need to write an end sample for that subtitle.
3367          *
3368          * This must be done conditionally to allow for subtitles that
3369          * immediately replace each other, in which case an end sample
3370          * is not needed, and is, in fact, actively harmful.
3371          *
3372          * 3) See mov_write_trailer for how the final end sample is
3373          * handled.
3374          */
3375         for (i = 0; i < mov->nb_streams; i++) {
3376             MOVTrack *trk = &mov->tracks[i];
3377             int ret;
3378
3379             if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
3380                 trk->track_duration < pkt->dts &&
3381                 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
3382                 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
3383                 if (ret < 0) return ret;
3384                 trk->last_sample_is_subtitle_end = 1;
3385             }
3386         }
3387
3388         return mov_write_single_packet(s, pkt);
3389     }
3390 }
3391
3392 // QuickTime chapters involve an additional text track with the chapter names
3393 // as samples, and a tref pointing from the other tracks to the chapter one.
3394 static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
3395 {
3396     AVIOContext *pb;
3397
3398     MOVMuxContext *mov = s->priv_data;
3399     MOVTrack *track = &mov->tracks[tracknum];
3400     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
3401     int i, len;
3402
3403     track->mode = mov->mode;
3404     track->tag = MKTAG('t','e','x','t');
3405     track->timescale = MOV_TIMESCALE;
3406     track->enc = avcodec_alloc_context3(NULL);
3407     track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3408
3409     if (avio_open_dyn_buf(&pb) >= 0) {
3410         int size;
3411         uint8_t *buf;
3412
3413         /* Stub header (usually for Quicktime chapter track) */
3414         // TextSampleEntry
3415         avio_wb32(pb, 0x01); // displayFlags
3416         avio_w8(pb, 0x00);   // horizontal justification
3417         avio_w8(pb, 0x00);   // vertical justification
3418         avio_w8(pb, 0x00);   // bgColourRed
3419         avio_w8(pb, 0x00);   // bgColourGreen
3420         avio_w8(pb, 0x00);   // bgColourBlue
3421         avio_w8(pb, 0x00);   // bgColourAlpha
3422         // BoxRecord
3423         avio_wb16(pb, 0x00); // defTextBoxTop
3424         avio_wb16(pb, 0x00); // defTextBoxLeft
3425         avio_wb16(pb, 0x00); // defTextBoxBottom
3426         avio_wb16(pb, 0x00); // defTextBoxRight
3427         // StyleRecord
3428         avio_wb16(pb, 0x00); // startChar
3429         avio_wb16(pb, 0x00); // endChar
3430         avio_wb16(pb, 0x01); // fontID
3431         avio_w8(pb, 0x00);   // fontStyleFlags
3432         avio_w8(pb, 0x00);   // fontSize
3433         avio_w8(pb, 0x00);   // fgColourRed
3434         avio_w8(pb, 0x00);   // fgColourGreen
3435         avio_w8(pb, 0x00);   // fgColourBlue
3436         avio_w8(pb, 0x00);   // fgColourAlpha
3437         // FontTableBox
3438         avio_wb32(pb, 0x0D); // box size
3439         ffio_wfourcc(pb, "ftab"); // box atom name
3440         avio_wb16(pb, 0x01); // entry count
3441         // FontRecord
3442         avio_wb16(pb, 0x01); // font ID
3443         avio_w8(pb, 0x00);   // font name length
3444
3445         if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
3446             track->enc->extradata = buf;
3447             track->enc->extradata_size = size;
3448         } else {
3449             av_free(&buf);
3450         }
3451     }
3452
3453     for (i = 0; i < s->nb_chapters; i++) {
3454         AVChapter *c = s->chapters[i];
3455         AVDictionaryEntry *t;
3456
3457         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
3458         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
3459         pkt.duration = end - pkt.dts;
3460
3461         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3462             len      = strlen(t->value);
3463             pkt.size = len + 2;
3464             pkt.data = av_malloc(pkt.size);
3465             AV_WB16(pkt.data, len);
3466             memcpy(pkt.data + 2, t->value, len);
3467             ff_mov_write_packet(s, &pkt);
3468             av_freep(&pkt.data);
3469         }
3470     }
3471 }
3472
3473 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
3474 {
3475     int ret;
3476     MOVMuxContext *mov  = s->priv_data;
3477     MOVTrack *track     = &mov->tracks[index];
3478     AVStream *src_st    = s->streams[src_index];
3479     AVTimecode tc;
3480     AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
3481     AVRational rate = {src_st->codec->time_base.den, src_st->codec->time_base.num};
3482
3483     /* if the codec time base makes no sense, try to fallback on stream frame rate */
3484     if (av_timecode_check_frame_rate(rate) < 0) {
3485         av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
3486                rate.num, rate.den, src_st->avg_frame_rate.num, src_st->avg_frame_rate.den);
3487         rate = src_st->avg_frame_rate;
3488     }
3489
3490     /* compute the frame number */
3491     ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
3492     if (ret < 0)
3493         return ret;
3494
3495     /* tmcd track based on video stream */
3496     track->mode      = mov->mode;
3497     track->tag       = MKTAG('t','m','c','d');
3498     track->src_track = src_index;
3499     track->timescale = mov->tracks[src_index].timescale;
3500     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
3501         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
3502
3503     /* encode context: tmcd data stream */
3504     track->enc = avcodec_alloc_context3(NULL);
3505     track->enc->codec_type = AVMEDIA_TYPE_DATA;
3506     track->enc->codec_tag  = track->tag;
3507     track->enc->time_base  = src_st->codec->time_base;
3508
3509     /* the tmcd track just contains one packet with the frame number */
3510     pkt.data = av_malloc(pkt.size);
3511     AV_WB32(pkt.data, tc.start);
3512     ret = ff_mov_write_packet(s, &pkt);
3513     av_free(pkt.data);
3514     return ret;
3515 }
3516
3517 static int mov_write_header(AVFormatContext *s)
3518 {
3519     AVIOContext *pb = s->pb;
3520     MOVMuxContext *mov = s->priv_data;
3521     AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
3522     int i, hint_track = 0, tmcd_track = 0;
3523
3524     /* Set the FRAGMENT flag if any of the fragmentation methods are
3525      * enabled. */
3526     if (mov->max_fragment_duration || mov->max_fragment_size ||
3527         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
3528                       FF_MOV_FLAG_FRAG_KEYFRAME |
3529                       FF_MOV_FLAG_FRAG_CUSTOM))
3530         mov->flags |= FF_MOV_FLAG_FRAGMENT;
3531
3532     /* faststart: moov at the beginning of the file, if supported */
3533     if (mov->flags & FF_MOV_FLAG_FASTSTART) {
3534         if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3535             mov->flags &= ~FF_MOV_FLAG_FASTSTART;
3536         else
3537             mov->reserved_moov_size = -1;
3538     }
3539
3540     if (!supports_edts(mov) && s->avoid_negative_ts < 0) {
3541         s->avoid_negative_ts = 1;
3542     }
3543
3544     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
3545      * is enabled, we don't support non-seekable output at all. */
3546     if (!s->pb->seekable &&
3547         ((!(mov->flags & FF_MOV_FLAG_FRAGMENT) &&
3548           strcmp(s->oformat->name, "ismv"))
3549          || mov->ism_lookahead)) {
3550         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
3551         return -1;
3552     }
3553
3554     /* Default mode == MP4 */
3555     mov->mode = MODE_MP4;
3556
3557     if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
3558     else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
3559     else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
3560     else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
3561     else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
3562     else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
3563     else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
3564
3565     mov_write_ftyp_tag(pb,s);
3566     if (mov->mode == MODE_PSP) {
3567         int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
3568         for (i = 0; i < s->nb_streams; i++) {
3569             AVStream *st = s->streams[i];
3570             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3571                 video_streams_nb++;
3572             else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3573                 audio_streams_nb++;
3574             else
3575                 other_streams_nb++;
3576             }
3577
3578         if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
3579             av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3580             return -1;
3581         }
3582         mov_write_uuidprof_tag(pb, s);
3583     }
3584
3585     mov->nb_streams = s->nb_streams;
3586     if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
3587         mov->chapter_track = mov->nb_streams++;
3588
3589     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
3590         /* Add hint tracks for each audio and video stream */
3591         hint_track = mov->nb_streams;
3592         for (i = 0; i < s->nb_streams; i++) {
3593             AVStream *st = s->streams[i];
3594             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3595                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3596                 mov->nb_streams++;
3597             }
3598         }
3599     }
3600
3601     if (mov->mode == MODE_MOV) {
3602         tmcd_track = mov->nb_streams;
3603
3604         /* +1 tmcd track for each video stream with a timecode */
3605         for (i = 0; i < s->nb_streams; i++) {
3606             AVStream *st = s->streams[i];
3607             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3608                 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
3609                 mov->nb_meta_tmcd++;
3610         }
3611
3612         /* check if there is already a tmcd track to remux */
3613         if (mov->nb_meta_tmcd) {
3614             for (i = 0; i < s->nb_streams; i++) {
3615                 AVStream *st = s->streams[i];
3616                 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
3617                     av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
3618                            "so timecode metadata are now ignored\n");
3619                     mov->nb_meta_tmcd = 0;
3620                 }
3621             }
3622         }
3623
3624         mov->nb_streams += mov->nb_meta_tmcd;
3625     }
3626
3627     mov->tracks = av_mallocz(mov->nb_streams * sizeof(*mov->tracks));
3628     if (!mov->tracks)
3629         return AVERROR(ENOMEM);
3630
3631     for (i = 0; i < s->nb_streams; i++) {
3632         AVStream *st= s->streams[i];
3633         MOVTrack *track= &mov->tracks[i];
3634         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3635
3636         track->enc = st->codec;
3637         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
3638         if (track->language < 0)
3639             track->language = 0;
3640         track->mode = mov->mode;
3641         track->tag  = mov_find_codec_tag(s, track);
3642         if (!track->tag) {
3643             av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
3644                    "codec not currently supported in container\n", i);
3645             goto error;
3646         }
3647         /* If hinting of this track is enabled by a later hint track,
3648          * this is updated. */
3649         track->hint_track = -1;
3650         track->start_dts  = AV_NOPTS_VALUE;
3651         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3652             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
3653                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
3654                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
3655                 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
3656                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
3657                     goto error;
3658                 }
3659                 track->height = track->tag >> 24 == 'n' ? 486 : 576;
3660             }
3661             if (mov->video_track_timescale) {
3662                 track->timescale = mov->video_track_timescale;
3663             } else {
3664                 track->timescale = st->codec->time_base.den;
3665                 while(track->timescale < 10000)
3666                     track->timescale *= 2;
3667             }
3668             if (track->mode == MODE_MOV && track->timescale > 100000)
3669                 av_log(s, AV_LOG_WARNING,
3670                        "WARNING codec timebase is very high. If duration is too long,\n"
3671                        "file may not be playable by quicktime. Specify a shorter timebase\n"
3672                        "or choose different container.\n");
3673         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3674             track->timescale = st->codec->sample_rate;
3675             if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
3676                 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
3677                 track->audio_vbr = 1;
3678             }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
3679                      st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
3680                      st->codec->codec_id == AV_CODEC_ID_ILBC){
3681                 if (!st->codec->block_align) {
3682                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
3683                     goto error;
3684                 }
3685                 track->sample_size = st->codec->block_align;
3686             }else if (st->codec->frame_size > 1){ /* assume compressed audio */
3687                 track->audio_vbr = 1;
3688             }else{
3689                 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
3690             }
3691             if (track->mode != MODE_MOV &&
3692                 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
3693                 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
3694                        i, track->enc->sample_rate);
3695                 goto error;
3696             }
3697         } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3698             track->timescale = st->codec->time_base.den;
3699         }else{
3700             track->timescale = MOV_TIMESCALE;
3701         }
3702         if (!track->height)
3703             track->height = st->codec->height;
3704         /* The ism specific timescale isn't mandatory, but is assumed by
3705          * some tools, such as mp4split. */
3706         if (mov->mode == MODE_ISM)
3707             track->timescale = 10000000;
3708
3709         avpriv_set_pts_info(st, 64, 1, track->timescale);
3710
3711         /* copy extradata if it exists */
3712         if (st->codec->extradata_size) {
3713             track->vos_len  = st->codec->extradata_size;
3714             track->vos_data = av_malloc(track->vos_len);
3715             memcpy(track->vos_data, st->codec->extradata, track->vos_len);
3716         }
3717     }
3718
3719     if (mov->mode == MODE_ISM) {
3720         /* If no fragmentation options have been set, set a default. */
3721         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
3722                             FF_MOV_FLAG_FRAG_CUSTOM)) &&
3723             !mov->max_fragment_duration && !mov->max_fragment_size)
3724             mov->max_fragment_duration = 5000000;
3725         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
3726                       FF_MOV_FLAG_FRAGMENT;
3727     }
3728
3729     if (mov->reserved_moov_size){
3730         mov->reserved_moov_pos= avio_tell(pb);
3731         if (mov->reserved_moov_size > 0)
3732             avio_skip(pb, mov->reserved_moov_size);
3733     }
3734
3735     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3736         mov_write_mdat_tag(pb, mov);
3737
3738     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
3739         mov->time = ff_iso8601_to_unix_time(t->value);
3740     if (mov->time)
3741         mov->time += 0x7C25B080; // 1970 based -> 1904 based
3742
3743     if (mov->chapter_track)
3744         mov_create_chapter_track(s, mov->chapter_track);
3745
3746     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
3747         /* Initialize the hint tracks for each audio and video stream */
3748         for (i = 0; i < s->nb_streams; i++) {
3749             AVStream *st = s->streams[i];
3750             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3751                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3752                 if (ff_mov_init_hinting(s, hint_track, i) < 0)
3753                     goto error;
3754                 hint_track++;
3755             }
3756         }
3757     }
3758
3759     if (mov->nb_meta_tmcd) {
3760         /* Initialize the tmcd tracks */
3761         for (i = 0; i < s->nb_streams; i++) {
3762             AVStream *st = s->streams[i];
3763             t = global_tcr;
3764
3765             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3766                 if (!t)
3767                     t = av_dict_get(st->metadata, "timecode", NULL, 0);
3768                 if (!t)
3769                     continue;
3770                 if (mov_create_timecode_track(s, tmcd_track, i, t->value) < 0)
3771                     goto error;
3772                 tmcd_track++;
3773             }
3774         }
3775     }
3776
3777     avio_flush(pb);
3778
3779     if (mov->flags & FF_MOV_FLAG_ISML)
3780         mov_write_isml_manifest(pb, mov);
3781
3782     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3783         mov_write_moov_tag(pb, mov, s);
3784         mov->fragments++;
3785     }
3786
3787     return 0;
3788  error:
3789     av_freep(&mov->tracks);
3790     return -1;
3791 }
3792
3793 /**
3794  * This function gets the moov size if moved to the top of the file: the chunk
3795  * offset table can switch between stco (32-bit entries) to co64 (64-bit
3796  * entries) when the moov is moved to the top, so the size of the moov would
3797  * change. It also updates the chunk offset tables.
3798  */
3799 static int compute_moov_size(AVFormatContext *s)
3800 {
3801     int i, moov_size, moov_size2;
3802     MOVMuxContext *mov = s->priv_data;
3803
3804     moov_size = get_moov_size(s);
3805     if (moov_size < 0)
3806         return moov_size;
3807
3808     for (i = 0; i < mov->nb_streams; i++)
3809         mov->tracks[i].data_offset += moov_size;
3810
3811     moov_size2 = get_moov_size(s);
3812     if (moov_size2 < 0)
3813         return moov_size2;
3814
3815     /* if the size changed, we just switched from stco to co64 and needs to
3816      * update the offsets */
3817     if (moov_size2 != moov_size)
3818         for (i = 0; i < mov->nb_streams; i++)
3819             mov->tracks[i].data_offset += moov_size2 - moov_size;
3820
3821     return moov_size2;
3822 }
3823
3824 static int shift_data(AVFormatContext *s)
3825 {
3826     int ret = 0, moov_size;
3827     MOVMuxContext *mov = s->priv_data;
3828     int64_t pos, pos_end = avio_tell(s->pb);
3829     uint8_t *buf, *read_buf[2];
3830     int read_buf_id = 0;
3831     int read_size[2];
3832     AVIOContext *read_pb;
3833
3834     moov_size = compute_moov_size(s);
3835     if (moov_size < 0)
3836         return moov_size;
3837
3838     buf = av_malloc(moov_size * 2);
3839     if (!buf)
3840         return AVERROR(ENOMEM);
3841     read_buf[0] = buf;
3842     read_buf[1] = buf + moov_size;
3843
3844     /* Shift the data: the AVIO context of the output can only be used for
3845      * writing, so we re-open the same output, but for reading. It also avoids
3846      * a read/seek/write/seek back and forth. */
3847     avio_flush(s->pb);
3848     ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
3849     if (ret < 0) {
3850         av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
3851                "the second pass (faststart)\n", s->filename);
3852         goto end;
3853     }
3854
3855     /* mark the end of the shift to up to the last data we wrote, and get ready
3856      * for writing */
3857     pos_end = avio_tell(s->pb);
3858     avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
3859
3860     /* start reading at where the new moov will be placed */
3861     avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
3862     pos = avio_tell(read_pb);
3863
3864 #define READ_BLOCK do {                                                             \
3865     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size);  \
3866     read_buf_id ^= 1;                                                               \
3867 } while (0)
3868
3869     /* shift data by chunk of at most moov_size */
3870     READ_BLOCK;
3871     do {
3872         int n;
3873         READ_BLOCK;
3874         n = read_size[read_buf_id];
3875         if (n <= 0)
3876             break;
3877         avio_write(s->pb, read_buf[read_buf_id], n);
3878         pos += n;
3879     } while (pos < pos_end);
3880     avio_close(read_pb);
3881
3882 end:
3883     av_free(buf);
3884     return ret;
3885 }
3886
3887 static int mov_write_trailer(AVFormatContext *s)
3888 {
3889     MOVMuxContext *mov = s->priv_data;
3890     AVIOContext *pb = s->pb;
3891     int64_t moov_pos;
3892     int res = 0;
3893     int i;
3894
3895     /*
3896      * Before actually writing the trailer, make sure that there are no
3897      * dangling subtitles, that need a terminating sample.
3898      */
3899     for (i = 0; i < mov->nb_streams; i++) {
3900         MOVTrack *trk = &mov->tracks[i];
3901         if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
3902             !trk->last_sample_is_subtitle_end) {
3903             mov_write_subtitle_end_packet(s, i, trk->track_duration);
3904             trk->last_sample_is_subtitle_end = 1;
3905         }
3906     }
3907
3908     moov_pos = avio_tell(pb);
3909
3910     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
3911         /* Write size of mdat tag */
3912         if (mov->mdat_size + 8 <= UINT32_MAX) {
3913             avio_seek(pb, mov->mdat_pos, SEEK_SET);
3914             avio_wb32(pb, mov->mdat_size + 8);
3915         } else {
3916             /* overwrite 'wide' placeholder atom */
3917             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
3918             /* special value: real atom size will be 64 bit value after
3919              * tag field */
3920             avio_wb32(pb, 1);
3921             ffio_wfourcc(pb, "mdat");
3922             avio_wb64(pb, mov->mdat_size + 16);
3923         }
3924         avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
3925
3926         if (mov->reserved_moov_size == -1) {
3927             av_log(s, AV_LOG_INFO, "Starting second pass: moving header on top of the file\n");
3928             res = shift_data(s);
3929             if (res == 0) {
3930                 avio_seek(s->pb, mov->reserved_moov_pos, SEEK_SET);
3931                 mov_write_moov_tag(pb, mov, s);
3932             }
3933         } else if (mov->reserved_moov_size > 0) {
3934             int64_t size;
3935             mov_write_moov_tag(pb, mov, s);
3936             size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
3937             if (size < 8){
3938                 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
3939                 return -1;
3940             }
3941             avio_wb32(pb, size);
3942             ffio_wfourcc(pb, "free");
3943             for (i = 0; i < size; i++)
3944                 avio_w8(pb, 0);
3945             avio_seek(pb, moov_pos, SEEK_SET);
3946         } else {
3947             mov_write_moov_tag(pb, mov, s);
3948         }
3949     } else {
3950         mov_flush_fragment(s);
3951         mov_write_mfra_tag(pb, mov);
3952     }
3953
3954     if (mov->chapter_track)
3955         av_freep(&mov->tracks[mov->chapter_track].enc);
3956
3957     for (i = 0; i < mov->nb_streams; i++) {
3958         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
3959             ff_mov_close_hinting(&mov->tracks[i]);
3960         else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
3961             av_freep(&mov->tracks[i].enc);
3962         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
3963             mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
3964             int64_t off = avio_tell(pb);
3965             uint8_t buf[7];
3966             if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
3967                 avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
3968                 avio_write(pb, buf, 7);
3969                 avio_seek(pb, off, SEEK_SET);
3970             }
3971         }
3972         av_freep(&mov->tracks[i].cluster);
3973         av_freep(&mov->tracks[i].frag_info);
3974
3975         if (mov->tracks[i].vos_len)
3976             av_free(mov->tracks[i].vos_data);
3977     }
3978
3979     av_freep(&mov->tracks);
3980
3981     return res;
3982 }
3983
3984 #if CONFIG_MOV_MUXER
3985 MOV_CLASS(mov)
3986 AVOutputFormat ff_mov_muxer = {
3987     .name              = "mov",
3988     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3989     .extensions        = "mov",
3990     .priv_data_size    = sizeof(MOVMuxContext),
3991     .audio_codec       = AV_CODEC_ID_AAC,
3992     .video_codec       = CONFIG_LIBX264_ENCODER ?
3993                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
3994     .write_header      = mov_write_header,
3995     .write_packet      = mov_write_packet,
3996     .write_trailer     = mov_write_trailer,
3997     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
3998     .codec_tag         = (const AVCodecTag* const []){
3999         ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
4000     },
4001     .priv_class        = &mov_muxer_class,
4002 };
4003 #endif
4004 #if CONFIG_TGP_MUXER
4005 MOV_CLASS(tgp)
4006 AVOutputFormat ff_tgp_muxer = {
4007     .name              = "3gp",
4008     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
4009     .extensions        = "3gp",
4010     .priv_data_size    = sizeof(MOVMuxContext),
4011     .audio_codec       = AV_CODEC_ID_AMR_NB,
4012     .video_codec       = AV_CODEC_ID_H263,
4013     .write_header      = mov_write_header,
4014     .write_packet      = mov_write_packet,
4015     .write_trailer     = mov_write_trailer,
4016     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4017     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4018     .priv_class        = &tgp_muxer_class,
4019 };
4020 #endif
4021 #if CONFIG_MP4_MUXER
4022 MOV_CLASS(mp4)
4023 AVOutputFormat ff_mp4_muxer = {
4024     .name              = "mp4",
4025     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
4026     .mime_type         = "application/mp4",
4027     .extensions        = "mp4",
4028     .priv_data_size    = sizeof(MOVMuxContext),
4029     .audio_codec       = AV_CODEC_ID_AAC,
4030     .video_codec       = CONFIG_LIBX264_ENCODER ?
4031                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4032     .write_header      = mov_write_header,
4033     .write_packet      = mov_write_packet,
4034     .write_trailer     = mov_write_trailer,
4035     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4036     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4037     .priv_class        = &mp4_muxer_class,
4038 };
4039 #endif
4040 #if CONFIG_PSP_MUXER
4041 MOV_CLASS(psp)
4042 AVOutputFormat ff_psp_muxer = {
4043     .name              = "psp",
4044     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
4045     .extensions        = "mp4,psp",
4046     .priv_data_size    = sizeof(MOVMuxContext),
4047     .audio_codec       = AV_CODEC_ID_AAC,
4048     .video_codec       = CONFIG_LIBX264_ENCODER ?
4049                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4050     .write_header      = mov_write_header,
4051     .write_packet      = mov_write_packet,
4052     .write_trailer     = mov_write_trailer,
4053     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
4054     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4055     .priv_class        = &psp_muxer_class,
4056 };
4057 #endif
4058 #if CONFIG_TG2_MUXER
4059 MOV_CLASS(tg2)
4060 AVOutputFormat ff_tg2_muxer = {
4061     .name              = "3g2",
4062     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
4063     .extensions        = "3g2",
4064     .priv_data_size    = sizeof(MOVMuxContext),
4065     .audio_codec       = AV_CODEC_ID_AMR_NB,
4066     .video_codec       = AV_CODEC_ID_H263,
4067     .write_header      = mov_write_header,
4068     .write_packet      = mov_write_packet,
4069     .write_trailer     = mov_write_trailer,
4070     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4071     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4072     .priv_class        = &tg2_muxer_class,
4073 };
4074 #endif
4075 #if CONFIG_IPOD_MUXER
4076 MOV_CLASS(ipod)
4077 AVOutputFormat ff_ipod_muxer = {
4078     .name              = "ipod",
4079     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
4080     .mime_type         = "application/mp4",
4081     .extensions        = "m4v,m4a",
4082     .priv_data_size    = sizeof(MOVMuxContext),
4083     .audio_codec       = AV_CODEC_ID_AAC,
4084     .video_codec       = AV_CODEC_ID_H264,
4085     .write_header      = mov_write_header,
4086     .write_packet      = mov_write_packet,
4087     .write_trailer     = mov_write_trailer,
4088     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4089     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
4090     .priv_class        = &ipod_muxer_class,
4091 };
4092 #endif
4093 #if CONFIG_ISMV_MUXER
4094 MOV_CLASS(ismv)
4095 AVOutputFormat ff_ismv_muxer = {
4096     .name              = "ismv",
4097     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
4098     .mime_type         = "application/mp4",
4099     .extensions        = "ismv,isma",
4100     .priv_data_size    = sizeof(MOVMuxContext),
4101     .audio_codec       = AV_CODEC_ID_AAC,
4102     .video_codec       = AV_CODEC_ID_H264,
4103     .write_header      = mov_write_header,
4104     .write_packet      = mov_write_packet,
4105     .write_trailer     = mov_write_trailer,
4106     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
4107     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4108     .priv_class        = &ismv_muxer_class,
4109 };
4110 #endif
4111 #if CONFIG_F4V_MUXER
4112 MOV_CLASS(f4v)
4113 AVOutputFormat ff_f4v_muxer = {
4114     .name              = "f4v",
4115     .long_name         = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
4116     .mime_type         = "application/f4v",
4117     .extensions        = "f4v",
4118     .priv_data_size    = sizeof(MOVMuxContext),
4119     .audio_codec       = AV_CODEC_ID_AAC,
4120     .video_codec       = AV_CODEC_ID_H264,
4121     .write_header      = mov_write_header,
4122     .write_packet      = mov_write_packet,
4123     .write_trailer     = mov_write_trailer,
4124     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
4125     .codec_tag         = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
4126     .priv_class        = &f4v_muxer_class,
4127 };
4128 #endif