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