]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
movenc: Indicate that negative timestamps are supported
[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 Libav.
8  *
9  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include "movenc.h"
25 #include "avformat.h"
26 #include "avio_internal.h"
27 #include "riff.h"
28 #include "avio.h"
29 #include "isom.h"
30 #include "avc.h"
31 #include "libavcodec/get_bits.h"
32 #include "libavcodec/put_bits.h"
33 #include "libavcodec/vc1.h"
34 #include "internal.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/intfloat.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/dict.h"
40 #include "rtpenc.h"
41 #include "mov_chan.h"
42
43 #undef NDEBUG
44 #include <assert.h>
45
46 static const AVOption options[] = {
47     { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
48     { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
49     { "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" },
50     { "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" },
51     { "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" },
52     { "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" },
53     { "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" },
54     FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
55     { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
56     { "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},
57     { "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},
58     { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
59     { "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},
60     { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
61     { "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},
62     { NULL },
63 };
64
65 #define MOV_CLASS(flavor)\
66 static const AVClass flavor ## _muxer_class = {\
67     .class_name = #flavor " muxer",\
68     .item_name  = av_default_item_name,\
69     .option     = options,\
70     .version    = LIBAVUTIL_VERSION_INT,\
71 };
72
73 //FIXME support 64 bit variant with wide placeholders
74 static int64_t update_size(AVIOContext *pb, int64_t pos)
75 {
76     int64_t curpos = avio_tell(pb);
77     avio_seek(pb, pos, SEEK_SET);
78     avio_wb32(pb, curpos - pos); /* rewrite size */
79     avio_seek(pb, curpos, SEEK_SET);
80
81     return curpos - pos;
82 }
83
84 /* Chunk offset atom */
85 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
86 {
87     int i;
88     int mode64 = 0; //   use 32 bit size variant if possible
89     int64_t pos = avio_tell(pb);
90     avio_wb32(pb, 0); /* size */
91     if (pos > UINT32_MAX) {
92         mode64 = 1;
93         ffio_wfourcc(pb, "co64");
94     } else
95         ffio_wfourcc(pb, "stco");
96     avio_wb32(pb, 0); /* version & flags */
97     avio_wb32(pb, track->entry); /* entry count */
98     for (i = 0; i < track->entry; i++) {
99         if (mode64 == 1)
100             avio_wb64(pb, track->cluster[i].pos + track->data_offset);
101         else
102             avio_wb32(pb, track->cluster[i].pos + track->data_offset);
103     }
104     return update_size(pb, pos);
105 }
106
107 /* Sample size atom */
108 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
109 {
110     int equalChunks = 1;
111     int i, j, entries = 0, tst = -1, oldtst = -1;
112
113     int64_t pos = avio_tell(pb);
114     avio_wb32(pb, 0); /* size */
115     ffio_wfourcc(pb, "stsz");
116     avio_wb32(pb, 0); /* version & flags */
117
118     for (i = 0; i < track->entry; i++) {
119         tst = track->cluster[i].size / track->cluster[i].entries;
120         if (oldtst != -1 && tst != oldtst)
121             equalChunks = 0;
122         oldtst = tst;
123         entries += track->cluster[i].entries;
124     }
125     if (equalChunks && track->entry) {
126         int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
127         sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
128         avio_wb32(pb, sSize); // sample size
129         avio_wb32(pb, entries); // sample count
130     } else {
131         avio_wb32(pb, 0); // sample size
132         avio_wb32(pb, entries); // sample count
133         for (i = 0; i < track->entry; i++) {
134             for (j = 0; j < track->cluster[i].entries; j++) {
135                 avio_wb32(pb, track->cluster[i].size /
136                           track->cluster[i].entries);
137             }
138         }
139     }
140     return update_size(pb, pos);
141 }
142
143 /* Sample to chunk atom */
144 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
145 {
146     int index = 0, oldval = -1, i;
147     int64_t entryPos, curpos;
148
149     int64_t pos = avio_tell(pb);
150     avio_wb32(pb, 0); /* size */
151     ffio_wfourcc(pb, "stsc");
152     avio_wb32(pb, 0); // version & flags
153     entryPos = avio_tell(pb);
154     avio_wb32(pb, track->entry); // entry count
155     for (i = 0; i < track->entry; i++) {
156         if (oldval != track->cluster[i].samples_in_chunk) {
157             avio_wb32(pb, i + 1); // first chunk
158             avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
159             avio_wb32(pb, 0x1); // sample description index
160             oldval = track->cluster[i].samples_in_chunk;
161             index++;
162         }
163     }
164     curpos = avio_tell(pb);
165     avio_seek(pb, entryPos, SEEK_SET);
166     avio_wb32(pb, index); // rewrite size
167     avio_seek(pb, curpos, SEEK_SET);
168
169     return update_size(pb, pos);
170 }
171
172 /* Sync sample atom */
173 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
174 {
175     int64_t curpos, entryPos;
176     int i, index = 0;
177     int64_t pos = avio_tell(pb);
178     avio_wb32(pb, 0); // size
179     ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
180     avio_wb32(pb, 0); // version & flags
181     entryPos = avio_tell(pb);
182     avio_wb32(pb, track->entry); // entry count
183     for (i = 0; i < track->entry; i++) {
184         if (track->cluster[i].flags & flag) {
185             avio_wb32(pb, i + 1);
186             index++;
187         }
188     }
189     curpos = avio_tell(pb);
190     avio_seek(pb, entryPos, SEEK_SET);
191     avio_wb32(pb, index); // rewrite size
192     avio_seek(pb, curpos, SEEK_SET);
193     return update_size(pb, pos);
194 }
195
196 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
197 {
198     avio_wb32(pb, 0x11); /* size */
199     if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
200     else                         ffio_wfourcc(pb, "damr");
201     ffio_wfourcc(pb, "FFMP");
202     avio_w8(pb, 0); /* decoder version */
203
204     avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
205     avio_w8(pb, 0x00); /* Mode change period (no restriction) */
206     avio_w8(pb, 0x01); /* Frames per sample */
207     return 0x11;
208 }
209
210 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
211 {
212     GetBitContext gbc;
213     PutBitContext pbc;
214     uint8_t buf[3];
215     int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
216
217     if (track->vos_len < 7)
218         return -1;
219
220     avio_wb32(pb, 11);
221     ffio_wfourcc(pb, "dac3");
222
223     init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
224     fscod      = get_bits(&gbc, 2);
225     frmsizecod = get_bits(&gbc, 6);
226     bsid       = get_bits(&gbc, 5);
227     bsmod      = get_bits(&gbc, 3);
228     acmod      = get_bits(&gbc, 3);
229     if (acmod == 2) {
230         skip_bits(&gbc, 2); // dsurmod
231     } else {
232         if ((acmod & 1) && acmod != 1)
233             skip_bits(&gbc, 2); // cmixlev
234         if (acmod & 4)
235             skip_bits(&gbc, 2); // surmixlev
236     }
237     lfeon = get_bits1(&gbc);
238
239     init_put_bits(&pbc, buf, sizeof(buf));
240     put_bits(&pbc, 2, fscod);
241     put_bits(&pbc, 5, bsid);
242     put_bits(&pbc, 3, bsmod);
243     put_bits(&pbc, 3, acmod);
244     put_bits(&pbc, 1, lfeon);
245     put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
246     put_bits(&pbc, 5, 0); // reserved
247
248     flush_put_bits(&pbc);
249     avio_write(pb, buf, sizeof(buf));
250
251     return 11;
252 }
253
254 /**
255  * This function writes extradata "as is".
256  * Extradata must be formatted like a valid atom (with size and tag).
257  */
258 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
259 {
260     avio_write(pb, track->enc->extradata, track->enc->extradata_size);
261     return track->enc->extradata_size;
262 }
263
264 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
265 {
266     int i = 3;
267     avio_w8(pb, tag);
268     for (; i > 0; i--)
269         avio_w8(pb, (size >> (7 * i)) | 0x80);
270     avio_w8(pb, size & 0x7F);
271 }
272
273 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
274 {
275     int64_t pos = avio_tell(pb);
276     int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
277
278     avio_wb32(pb, 0); // size
279     ffio_wfourcc(pb, "esds");
280     avio_wb32(pb, 0); // Version
281
282     // ES descriptor
283     put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
284     avio_wb16(pb, track->track_id);
285     avio_w8(pb, 0x00); // flags (= no flags)
286
287     // DecoderConfig descriptor
288     put_descr(pb, 0x04, 13 + decoder_specific_info_len);
289
290     // Object type indication
291     if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
292          track->enc->codec_id == AV_CODEC_ID_MP3) &&
293         track->enc->sample_rate > 24000)
294         avio_w8(pb, 0x6B); // 11172-3
295     else
296         avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
297
298     // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
299     // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
300     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
301         avio_w8(pb, 0x15); // flags (= Audiostream)
302     else
303         avio_w8(pb, 0x11); // flags (= Visualstream)
304
305     avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
306
307     avio_wb32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
308     if (track->enc->rc_max_rate != track->enc->rc_min_rate ||
309         track->enc->rc_min_rate == 0)
310         avio_wb32(pb, 0); // vbr
311     else
312         avio_wb32(pb, track->enc->rc_max_rate); // avg bitrate
313
314     if (track->vos_len) {
315         // DecoderSpecific info descriptor
316         put_descr(pb, 0x05, track->vos_len);
317         avio_write(pb, track->vos_data, track->vos_len);
318     }
319
320     // SL descriptor
321     put_descr(pb, 0x06, 1);
322     avio_w8(pb, 0x02);
323     return update_size(pb, pos);
324 }
325
326 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
327 {
328     int64_t pos = avio_tell(pb);
329     avio_wb32(pb, 0);
330     avio_wl32(pb, track->tag); // store it byteswapped
331     track->enc->codec_tag = av_bswap16(track->tag >> 16);
332     ff_put_wav_header(pb, track->enc);
333     return update_size(pb, pos);
334 }
335
336 static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
337 {
338     int64_t pos = avio_tell(pb);
339     avio_wb32(pb, 0);
340     ffio_wfourcc(pb, "wfex");
341     ff_put_wav_header(pb, track->enc);
342     return update_size(pb, pos);
343 }
344
345 static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
346 {
347     uint32_t layout_tag, bitmap;
348     int64_t pos = avio_tell(pb);
349
350     layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
351                                                track->enc->channel_layout,
352                                                &bitmap);
353     if (!layout_tag) {
354         av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
355                "lack of channel information\n");
356         return 0;
357     }
358
359     avio_wb32(pb, 0);           // Size
360     ffio_wfourcc(pb, "chan");   // Type
361     avio_w8(pb, 0);             // Version
362     avio_wb24(pb, 0);           // Flags
363     avio_wb32(pb, layout_tag);  // mChannelLayoutTag
364     avio_wb32(pb, bitmap);      // mChannelBitmap
365     avio_wb32(pb, 0);           // mNumberChannelDescriptions
366
367     return update_size(pb, pos);
368 }
369
370 static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
371 {
372     int64_t pos = avio_tell(pb);
373
374     avio_wb32(pb, 0);     /* size */
375     ffio_wfourcc(pb, "wave");
376
377     avio_wb32(pb, 12);    /* size */
378     ffio_wfourcc(pb, "frma");
379     avio_wl32(pb, track->tag);
380
381     if (track->enc->codec_id == AV_CODEC_ID_AAC) {
382         /* useless atom needed by mplayer, ipod, not needed by quicktime */
383         avio_wb32(pb, 12); /* size */
384         ffio_wfourcc(pb, "mp4a");
385         avio_wb32(pb, 0);
386         mov_write_esds_tag(pb, track);
387     } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
388         mov_write_amr_tag(pb, track);
389     } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
390         mov_write_ac3_tag(pb, track);
391     } else if (track->enc->codec_id == AV_CODEC_ID_ALAC) {
392         mov_write_extradata_tag(pb, track);
393     } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
394                track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
395         mov_write_ms_tag(pb, track);
396     }
397
398     avio_wb32(pb, 8);     /* size */
399     avio_wb32(pb, 0);     /* null tag */
400
401     return update_size(pb, pos);
402 }
403
404 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
405 {
406     uint8_t *unescaped;
407     const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
408     int unescaped_size, seq_found = 0;
409     int level = 0, interlace = 0;
410     int packet_seq   = track->vc1_info.packet_seq;
411     int packet_entry = track->vc1_info.packet_entry;
412     int slices       = track->vc1_info.slices;
413     PutBitContext pbc;
414
415     if (track->start_dts == AV_NOPTS_VALUE) {
416         /* No packets written yet, vc1_info isn't authoritative yet. */
417         /* Assume inline sequence and entry headers. This will be
418          * overwritten at the end if the file is seekable. */
419         packet_seq = packet_entry = 1;
420     }
421
422     unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
423     if (!unescaped)
424         return AVERROR(ENOMEM);
425     start = find_next_marker(track->vos_data, end);
426     for (next = start; next < end; start = next) {
427         GetBitContext gb;
428         int size;
429         next = find_next_marker(start + 4, end);
430         size = next - start - 4;
431         if (size <= 0)
432             continue;
433         unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
434         init_get_bits(&gb, unescaped, 8 * unescaped_size);
435         if (AV_RB32(start) == VC1_CODE_SEQHDR) {
436             int profile = get_bits(&gb, 2);
437             if (profile != PROFILE_ADVANCED) {
438                 av_free(unescaped);
439                 return AVERROR(ENOSYS);
440             }
441             seq_found = 1;
442             level = get_bits(&gb, 3);
443             /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
444              * width, height */
445             skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
446             skip_bits(&gb, 1); /* broadcast */
447             interlace = get_bits1(&gb);
448             skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
449         }
450     }
451     if (!seq_found) {
452         av_free(unescaped);
453         return AVERROR(ENOSYS);
454     }
455
456     init_put_bits(&pbc, buf, 7);
457     /* VC1DecSpecStruc */
458     put_bits(&pbc, 4, 12); /* profile - advanced */
459     put_bits(&pbc, 3, level);
460     put_bits(&pbc, 1, 0); /* reserved */
461     /* VC1AdvDecSpecStruc */
462     put_bits(&pbc, 3, level);
463     put_bits(&pbc, 1, 0); /* cbr */
464     put_bits(&pbc, 6, 0); /* reserved */
465     put_bits(&pbc, 1, !interlace); /* no interlace */
466     put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
467     put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
468     put_bits(&pbc, 1, !slices); /* no slice code */
469     put_bits(&pbc, 1, 0); /* no bframe */
470     put_bits(&pbc, 1, 0); /* reserved */
471     put_bits32(&pbc, track->enc->time_base.den); /* framerate */
472     flush_put_bits(&pbc);
473
474     av_free(unescaped);
475
476     return 0;
477 }
478
479 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
480 {
481     uint8_t buf[7] = { 0 };
482     int ret;
483
484     if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
485         return ret;
486
487     avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
488     ffio_wfourcc(pb, "dvc1");
489     track->vc1_info.struct_offset = avio_tell(pb);
490     avio_write(pb, buf, sizeof(buf));
491     avio_write(pb, track->vos_data, track->vos_len);
492
493     return 0;
494 }
495
496 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
497 {
498     avio_wb32(pb, track->vos_len + 8);
499     ffio_wfourcc(pb, "glbl");
500     avio_write(pb, track->vos_data, track->vos_len);
501     return 8 + track->vos_len;
502 }
503
504 /**
505  * Compute flags for 'lpcm' tag.
506  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
507  */
508 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
509 {
510     switch (codec_id) {
511     case AV_CODEC_ID_PCM_F32BE:
512     case AV_CODEC_ID_PCM_F64BE:
513         return 11;
514     case AV_CODEC_ID_PCM_F32LE:
515     case AV_CODEC_ID_PCM_F64LE:
516         return 9;
517     case AV_CODEC_ID_PCM_U8:
518         return 10;
519     case AV_CODEC_ID_PCM_S16BE:
520     case AV_CODEC_ID_PCM_S24BE:
521     case AV_CODEC_ID_PCM_S32BE:
522         return 14;
523     case AV_CODEC_ID_PCM_S8:
524     case AV_CODEC_ID_PCM_S16LE:
525     case AV_CODEC_ID_PCM_S24LE:
526     case AV_CODEC_ID_PCM_S32LE:
527         return 12;
528     default:
529         return 0;
530     }
531 }
532
533 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
534 {
535     int64_t next_dts;
536
537     if (cluster_idx >= track->entry)
538         return 0;
539
540     if (cluster_idx + 1 == track->entry)
541         next_dts = track->track_duration + track->start_dts;
542     else
543         next_dts = track->cluster[cluster_idx + 1].dts;
544
545     return next_dts - track->cluster[cluster_idx].dts;
546 }
547
548 static int get_samples_per_packet(MOVTrack *track)
549 {
550     int i, first_duration;
551
552     /* use 1 for raw PCM */
553     if (!track->audio_vbr)
554         return 1;
555
556     /* check to see if duration is constant for all clusters */
557     if (!track->entry)
558         return 0;
559     first_duration = get_cluster_duration(track, 0);
560     for (i = 1; i < track->entry; i++) {
561         if (get_cluster_duration(track, i) != first_duration)
562             return 0;
563     }
564     return first_duration;
565 }
566
567 static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
568 {
569     int64_t pos = avio_tell(pb);
570     int version = 0;
571     uint32_t tag = track->tag;
572
573     if (track->mode == MODE_MOV) {
574         if (mov_get_lpcm_flags(track->enc->codec_id))
575             tag = AV_RL32("lpcm");
576         version = 2;
577     }
578
579     avio_wb32(pb, 0); /* size */
580     avio_wl32(pb, tag); // store it byteswapped
581     avio_wb32(pb, 0); /* Reserved */
582     avio_wb16(pb, 0); /* Reserved */
583     avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */
584
585     /* SoundDescription */
586     avio_wb16(pb, version); /* Version */
587     avio_wb16(pb, 0); /* Revision level */
588     avio_wb32(pb, 0); /* Reserved */
589
590     if (version == 2) {
591         avio_wb16(pb, 3);
592         avio_wb16(pb, 16);
593         avio_wb16(pb, 0xfffe);
594         avio_wb16(pb, 0);
595         avio_wb32(pb, 0x00010000);
596         avio_wb32(pb, 72);
597         avio_wb64(pb, av_double2int(track->enc->sample_rate));
598         avio_wb32(pb, track->enc->channels);
599         avio_wb32(pb, 0x7F000000);
600         avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
601         avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
602         avio_wb32(pb, track->sample_size);
603         avio_wb32(pb, get_samples_per_packet(track));
604     } else {
605         /* reserved for mp4/3gp */
606         avio_wb16(pb, 2);
607         avio_wb16(pb, 16);
608         avio_wb16(pb, 0);
609
610         avio_wb16(pb, 0); /* packet size (= 0) */
611         avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
612                       track->enc->sample_rate : 0);
613         avio_wb16(pb, 0); /* Reserved */
614     }
615
616     if (track->mode == MODE_MOV &&
617         (track->enc->codec_id == AV_CODEC_ID_AAC           ||
618          track->enc->codec_id == AV_CODEC_ID_AC3           ||
619          track->enc->codec_id == AV_CODEC_ID_AMR_NB        ||
620          track->enc->codec_id == AV_CODEC_ID_ALAC          ||
621          track->enc->codec_id == AV_CODEC_ID_ADPCM_MS      ||
622          track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV))
623         mov_write_wave_tag(pb, track);
624     else if (track->tag == MKTAG('m','p','4','a'))
625         mov_write_esds_tag(pb, track);
626     else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
627         mov_write_amr_tag(pb, track);
628     else if (track->enc->codec_id == AV_CODEC_ID_AC3)
629         mov_write_ac3_tag(pb, track);
630     else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
631         mov_write_extradata_tag(pb, track);
632     else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
633         mov_write_wfex_tag(pb, track);
634     else if (track->vos_len > 0)
635         mov_write_glbl_tag(pb, track);
636
637     if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
638         mov_write_chan_tag(pb, track);
639
640     return update_size(pb, pos);
641 }
642
643 static int mov_write_d263_tag(AVIOContext *pb)
644 {
645     avio_wb32(pb, 0xf); /* size */
646     ffio_wfourcc(pb, "d263");
647     ffio_wfourcc(pb, "FFMP");
648     avio_w8(pb, 0); /* decoder version */
649     /* FIXME use AVCodecContext level/profile, when encoder will set values */
650     avio_w8(pb, 0xa); /* level */
651     avio_w8(pb, 0); /* profile */
652     return 0xf;
653 }
654
655 /* TODO: No idea about these values */
656 static int mov_write_svq3_tag(AVIOContext *pb)
657 {
658     avio_wb32(pb, 0x15);
659     ffio_wfourcc(pb, "SMI ");
660     ffio_wfourcc(pb, "SEQH");
661     avio_wb32(pb, 0x5);
662     avio_wb32(pb, 0xe2c0211d);
663     avio_wb32(pb, 0xc0000000);
664     avio_w8(pb, 0);
665     return 0x15;
666 }
667
668 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
669 {
670     int64_t pos = avio_tell(pb);
671
672     avio_wb32(pb, 0);
673     ffio_wfourcc(pb, "avcC");
674     ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
675     return update_size(pb, pos);
676 }
677
678 /* also used by all avid codecs (dv, imx, meridien) and their variants */
679 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
680 {
681     int i;
682     avio_wb32(pb, 24); /* size */
683     ffio_wfourcc(pb, "ACLR");
684     ffio_wfourcc(pb, "ACLR");
685     ffio_wfourcc(pb, "0001");
686     avio_wb32(pb, 2); /* yuv range: full 1 / normal 2 */
687     avio_wb32(pb, 0); /* unknown */
688
689     avio_wb32(pb, 24); /* size */
690     ffio_wfourcc(pb, "APRG");
691     ffio_wfourcc(pb, "APRG");
692     ffio_wfourcc(pb, "0001");
693     avio_wb32(pb, 1); /* unknown */
694     avio_wb32(pb, 0); /* unknown */
695
696     avio_wb32(pb, 120); /* size */
697     ffio_wfourcc(pb, "ARES");
698     ffio_wfourcc(pb, "ARES");
699     ffio_wfourcc(pb, "0001");
700     avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
701     avio_wb32(pb, track->enc->width);
702     /* values below are based on samples created with quicktime and avid codecs */
703     if (track->vos_data[5] & 2) { // interlaced
704         avio_wb32(pb, track->enc->height / 2);
705         avio_wb32(pb, 2); /* unknown */
706         avio_wb32(pb, 0); /* unknown */
707         avio_wb32(pb, 4); /* unknown */
708     } else {
709         avio_wb32(pb, track->enc->height);
710         avio_wb32(pb, 1); /* unknown */
711         avio_wb32(pb, 0); /* unknown */
712         if (track->enc->height == 1080)
713             avio_wb32(pb, 5); /* unknown */
714         else
715             avio_wb32(pb, 6); /* unknown */
716     }
717     /* padding */
718     for (i = 0; i < 10; i++)
719         avio_wb64(pb, 0);
720
721     /* extra padding for stsd needed */
722     avio_wb32(pb, 0);
723     return 0;
724 }
725
726 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
727 {
728     int tag = track->enc->codec_tag;
729
730     if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
731         return 0;
732
733     if      (track->enc->codec_id == AV_CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
734     else if (track->enc->codec_id == AV_CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
735     else if (track->enc->codec_id == AV_CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
736     else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
737     else if (track->enc->codec_id == AV_CODEC_ID_VC1)       tag = MKTAG('v','c','-','1');
738     else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)  tag = MKTAG('m','p','4','v');
739     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)  tag = MKTAG('m','p','4','a');
740
741     return tag;
742 }
743
744 static const AVCodecTag codec_ipod_tags[] = {
745     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
746     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
747     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
748     { AV_CODEC_ID_ALAC,     MKTAG('a','l','a','c') },
749     { AV_CODEC_ID_AC3,      MKTAG('a','c','-','3') },
750     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
751     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
752     { AV_CODEC_ID_NONE, 0 },
753 };
754
755 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
756 {
757     int tag = track->enc->codec_tag;
758
759     // keep original tag for subs, ipod supports both formats
760     if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
761           (tag == MKTAG('t', 'x', '3', 'g') ||
762            tag == MKTAG('t', 'e', 'x', 't'))))
763         tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
764
765     if (!av_match_ext(s->filename, "m4a") && !av_match_ext(s->filename, "m4v"))
766         av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
767                "Quicktime/Ipod might not play the file\n");
768
769     return tag;
770 }
771
772 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
773 {
774     int tag;
775
776     if (track->enc->width == 720) /* SD */
777         if (track->enc->height == 480) /* NTSC */
778             if  (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
779             else                                            tag = MKTAG('d','v','c',' ');
780         else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
781         else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
782         else                                                tag = MKTAG('d','v','p','p');
783     else if (track->enc->height == 720) /* HD 720 line */
784         if  (track->enc->time_base.den == 50)               tag = MKTAG('d','v','h','q');
785         else                                                tag = MKTAG('d','v','h','p');
786     else if (track->enc->height == 1080) /* HD 1080 line */
787         if  (track->enc->time_base.den == 25)               tag = MKTAG('d','v','h','5');
788         else                                                tag = MKTAG('d','v','h','6');
789     else {
790         av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
791         return 0;
792     }
793
794     return tag;
795 }
796
797 static const struct {
798     enum AVPixelFormat pix_fmt;
799     uint32_t tag;
800     unsigned bps;
801 } mov_pix_fmt_tags[] = {
802     { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
803     { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
804     { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
805     { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
806     { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
807     { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
808     { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
809     { AV_PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
810     { AV_PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
811     { AV_PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
812     { AV_PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
813     { AV_PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
814     { AV_PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
815     { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
816 };
817
818 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
819 {
820     int tag = track->enc->codec_tag;
821     int i;
822
823     for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
824         if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
825             tag = mov_pix_fmt_tags[i].tag;
826             track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
827             break;
828         }
829     }
830
831     return tag;
832 }
833
834 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
835 {
836     int tag = track->enc->codec_tag;
837
838     if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
839                  (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
840                   track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
841                   track->enc->codec_id == AV_CODEC_ID_H263 ||
842                   av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
843         if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
844             tag = mov_get_dv_codec_tag(s, track);
845         else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
846             tag = mov_get_rawvideo_codec_tag(s, track);
847         else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
848             tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
849             if (!tag) { // if no mac fcc found, try with Microsoft tags
850                 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
851                 if (tag)
852                     av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
853                            "the file may be unplayable!\n");
854             }
855         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
856             tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
857             if (!tag) { // if no mac fcc found, try with Microsoft tags
858                 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
859                 if (ms_tag) {
860                     tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
861                     av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
862                            "the file may be unplayable!\n");
863                 }
864             }
865         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
866             tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
867     }
868
869     return tag;
870 }
871
872 static const AVCodecTag codec_3gp_tags[] = {
873     { AV_CODEC_ID_H263,     MKTAG('s','2','6','3') },
874     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
875     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
876     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
877     { AV_CODEC_ID_AMR_NB,   MKTAG('s','a','m','r') },
878     { AV_CODEC_ID_AMR_WB,   MKTAG('s','a','w','b') },
879     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
880     { AV_CODEC_ID_NONE, 0 },
881 };
882
883 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
884 {
885     int tag;
886
887     if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
888         tag = mp4_get_codec_tag(s, track);
889     else if (track->mode == MODE_ISM) {
890         tag = mp4_get_codec_tag(s, track);
891         if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
892             tag = MKTAG('w', 'm', 'a', ' ');
893     } else if (track->mode == MODE_IPOD)
894         tag = ipod_get_codec_tag(s, track);
895     else if (track->mode & MODE_3GP)
896         tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
897     else
898         tag = mov_get_codec_tag(s, track);
899
900     return tag;
901 }
902
903 /** Write uuid atom.
904  * Needed to make file play in iPods running newest firmware
905  * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
906  */
907 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
908 {
909     avio_wb32(pb, 28);
910     ffio_wfourcc(pb, "uuid");
911     avio_wb32(pb, 0x6b6840f2);
912     avio_wb32(pb, 0x5f244fc5);
913     avio_wb32(pb, 0xba39a51b);
914     avio_wb32(pb, 0xcf0323f3);
915     avio_wb32(pb, 0x0);
916     return 28;
917 }
918
919 static const uint16_t fiel_data[] = {
920     0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
921 };
922
923 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
924 {
925     unsigned mov_field_order = 0;
926     if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
927         mov_field_order = fiel_data[track->enc->field_order];
928     else
929         return 0;
930     avio_wb32(pb, 10);
931     ffio_wfourcc(pb, "fiel");
932     avio_wb16(pb, mov_field_order);
933     return 10;
934 }
935
936 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
937 {
938     int64_t pos = avio_tell(pb);
939     avio_wb32(pb, 0);    /* size */
940     avio_wl32(pb, track->tag); // store it byteswapped
941     avio_wb32(pb, 0);    /* Reserved */
942     avio_wb16(pb, 0);    /* Reserved */
943     avio_wb16(pb, 1);    /* Data-reference index */
944
945     if (track->enc->extradata_size)
946         avio_write(pb, track->enc->extradata, track->enc->extradata_size);
947
948     return update_size(pb, pos);
949 }
950
951 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
952 {
953     AVRational sar;
954     av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
955               track->enc->sample_aspect_ratio.den, INT_MAX);
956
957     avio_wb32(pb, 16);
958     ffio_wfourcc(pb, "pasp");
959     avio_wb32(pb, sar.num);
960     avio_wb32(pb, sar.den);
961     return 16;
962 }
963
964 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
965 {
966     int64_t pos = avio_tell(pb);
967     char compressor_name[32] = { 0 };
968
969     avio_wb32(pb, 0); /* size */
970     avio_wl32(pb, track->tag); // store it byteswapped
971     avio_wb32(pb, 0); /* Reserved */
972     avio_wb16(pb, 0); /* Reserved */
973     avio_wb16(pb, 1); /* Data-reference index */
974
975     avio_wb16(pb, 0); /* Codec stream version */
976     avio_wb16(pb, 0); /* Codec stream revision (=0) */
977     if (track->mode == MODE_MOV) {
978         ffio_wfourcc(pb, "FFMP"); /* Vendor */
979         if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
980             avio_wb32(pb, 0); /* Temporal Quality */
981             avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
982         } else {
983             avio_wb32(pb, 0x200); /* Temporal Quality = normal */
984             avio_wb32(pb, 0x200); /* Spatial Quality = normal */
985         }
986     } else {
987         avio_wb32(pb, 0); /* Reserved */
988         avio_wb32(pb, 0); /* Reserved */
989         avio_wb32(pb, 0); /* Reserved */
990     }
991     avio_wb16(pb, track->enc->width); /* Video width */
992     avio_wb16(pb, track->height); /* Video height */
993     avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
994     avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
995     avio_wb32(pb, 0); /* Data size (= 0) */
996     avio_wb16(pb, 1); /* Frame count (= 1) */
997
998     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
999     if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
1000         av_strlcpy(compressor_name, track->enc->codec->name, 32);
1001     avio_w8(pb, strlen(compressor_name));
1002     avio_write(pb, compressor_name, 31);
1003
1004     if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1005         avio_wb16(pb, track->enc->bits_per_coded_sample);
1006     else
1007         avio_wb16(pb, 0x18); /* Reserved */
1008     avio_wb16(pb, 0xffff); /* Reserved */
1009     if (track->tag == MKTAG('m','p','4','v'))
1010         mov_write_esds_tag(pb, track);
1011     else if (track->enc->codec_id == AV_CODEC_ID_H263)
1012         mov_write_d263_tag(pb);
1013     else if (track->enc->codec_id == AV_CODEC_ID_SVQ3)
1014         mov_write_svq3_tag(pb);
1015     else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
1016         mov_write_avid_tag(pb, track);
1017     else if (track->enc->codec_id == AV_CODEC_ID_H264) {
1018         mov_write_avcc_tag(pb, track);
1019         if (track->mode == MODE_IPOD)
1020             mov_write_uuid_tag_ipod(pb);
1021     } else if (track->enc->field_order != AV_FIELD_UNKNOWN)
1022         mov_write_fiel_tag(pb, track);
1023     else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1024         mov_write_dvc1_tag(pb, track);
1025     else if (track->vos_len > 0)
1026         mov_write_glbl_tag(pb, track);
1027
1028     if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1029         track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1030         mov_write_pasp_tag(pb, track);
1031     }
1032
1033     return update_size(pb, pos);
1034 }
1035
1036 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1037 {
1038     int64_t pos = avio_tell(pb);
1039     avio_wb32(pb, 0); /* size */
1040     ffio_wfourcc(pb, "rtp ");
1041     avio_wb32(pb, 0); /* Reserved */
1042     avio_wb16(pb, 0); /* Reserved */
1043     avio_wb16(pb, 1); /* Data-reference index */
1044
1045     avio_wb16(pb, 1); /* Hint track version */
1046     avio_wb16(pb, 1); /* Highest compatible version */
1047     avio_wb32(pb, track->max_packet_size); /* Max packet size */
1048
1049     avio_wb32(pb, 12); /* size */
1050     ffio_wfourcc(pb, "tims");
1051     avio_wb32(pb, track->timescale);
1052
1053     return update_size(pb, pos);
1054 }
1055
1056 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
1057 {
1058     int64_t pos = avio_tell(pb);
1059     avio_wb32(pb, 0); /* size */
1060     ffio_wfourcc(pb, "stsd");
1061     avio_wb32(pb, 0); /* version & flags */
1062     avio_wb32(pb, 1); /* entry count */
1063     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1064         mov_write_video_tag(pb, track);
1065     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1066         mov_write_audio_tag(pb, track);
1067     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1068         mov_write_subtitle_tag(pb, track);
1069     else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1070         mov_write_rtp_tag(pb, track);
1071     return update_size(pb, pos);
1072 }
1073
1074 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1075 {
1076     MOVStts *ctts_entries;
1077     uint32_t entries = 0;
1078     uint32_t atom_size;
1079     int i;
1080
1081     ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
1082     ctts_entries[0].count = 1;
1083     ctts_entries[0].duration = track->cluster[0].cts;
1084     for (i = 1; i < track->entry; i++) {
1085         if (track->cluster[i].cts == ctts_entries[entries].duration) {
1086             ctts_entries[entries].count++; /* compress */
1087         } else {
1088             entries++;
1089             ctts_entries[entries].duration = track->cluster[i].cts;
1090             ctts_entries[entries].count = 1;
1091         }
1092     }
1093     entries++; /* last one */
1094     atom_size = 16 + (entries * 8);
1095     avio_wb32(pb, atom_size); /* size */
1096     ffio_wfourcc(pb, "ctts");
1097     avio_wb32(pb, 0); /* version & flags */
1098     avio_wb32(pb, entries); /* entry count */
1099     for (i = 0; i < entries; i++) {
1100         avio_wb32(pb, ctts_entries[i].count);
1101         avio_wb32(pb, ctts_entries[i].duration);
1102     }
1103     av_free(ctts_entries);
1104     return atom_size;
1105 }
1106
1107 /* Time to sample atom */
1108 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1109 {
1110     MOVStts *stts_entries;
1111     uint32_t entries = -1;
1112     uint32_t atom_size;
1113     int i;
1114
1115     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1116         stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1117         stts_entries[0].count = track->sample_count;
1118         stts_entries[0].duration = 1;
1119         entries = 1;
1120     } else {
1121         stts_entries = track->entry ?
1122                        av_malloc(track->entry * sizeof(*stts_entries)) : /* worst case */
1123                        NULL;
1124         for (i = 0; i < track->entry; i++) {
1125             int duration = get_cluster_duration(track, i);
1126             if (i && duration == stts_entries[entries].duration) {
1127                 stts_entries[entries].count++; /* compress */
1128             } else {
1129                 entries++;
1130                 stts_entries[entries].duration = duration;
1131                 stts_entries[entries].count = 1;
1132             }
1133         }
1134         entries++; /* last one */
1135     }
1136     atom_size = 16 + (entries * 8);
1137     avio_wb32(pb, atom_size); /* size */
1138     ffio_wfourcc(pb, "stts");
1139     avio_wb32(pb, 0); /* version & flags */
1140     avio_wb32(pb, entries); /* entry count */
1141     for (i = 0; i < entries; i++) {
1142         avio_wb32(pb, stts_entries[i].count);
1143         avio_wb32(pb, stts_entries[i].duration);
1144     }
1145     av_free(stts_entries);
1146     return atom_size;
1147 }
1148
1149 static int mov_write_dref_tag(AVIOContext *pb)
1150 {
1151     avio_wb32(pb, 28); /* size */
1152     ffio_wfourcc(pb, "dref");
1153     avio_wb32(pb, 0); /* version & flags */
1154     avio_wb32(pb, 1); /* entry count */
1155
1156     avio_wb32(pb, 0xc); /* size */
1157     ffio_wfourcc(pb, "url ");
1158     avio_wb32(pb, 1); /* version & flags */
1159
1160     return 28;
1161 }
1162
1163 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1164 {
1165     int64_t pos = avio_tell(pb);
1166     avio_wb32(pb, 0); /* size */
1167     ffio_wfourcc(pb, "stbl");
1168     mov_write_stsd_tag(pb, track);
1169     mov_write_stts_tag(pb, track);
1170     if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1171          track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1172         track->has_keyframes && track->has_keyframes < track->entry)
1173         mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1174     if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1175         mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1176     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1177         track->flags & MOV_TRACK_CTTS)
1178         mov_write_ctts_tag(pb, track);
1179     mov_write_stsc_tag(pb, track);
1180     mov_write_stsz_tag(pb, track);
1181     mov_write_stco_tag(pb, track);
1182     return update_size(pb, pos);
1183 }
1184
1185 static int mov_write_dinf_tag(AVIOContext *pb)
1186 {
1187     int64_t pos = avio_tell(pb);
1188     avio_wb32(pb, 0); /* size */
1189     ffio_wfourcc(pb, "dinf");
1190     mov_write_dref_tag(pb);
1191     return update_size(pb, pos);
1192 }
1193
1194 static int mov_write_nmhd_tag(AVIOContext *pb)
1195 {
1196     avio_wb32(pb, 12);
1197     ffio_wfourcc(pb, "nmhd");
1198     avio_wb32(pb, 0);
1199     return 12;
1200 }
1201
1202 static int mov_write_gmhd_tag(AVIOContext *pb)
1203 {
1204     avio_wb32(pb, 0x20);   /* size */
1205     ffio_wfourcc(pb, "gmhd");
1206     avio_wb32(pb, 0x18);   /* gmin size */
1207     ffio_wfourcc(pb, "gmin");/* generic media info */
1208     avio_wb32(pb, 0);      /* version & flags */
1209     avio_wb16(pb, 0x40);   /* graphics mode = */
1210     avio_wb16(pb, 0x8000); /* opColor (r?) */
1211     avio_wb16(pb, 0x8000); /* opColor (g?) */
1212     avio_wb16(pb, 0x8000); /* opColor (b?) */
1213     avio_wb16(pb, 0);      /* balance */
1214     avio_wb16(pb, 0);      /* reserved */
1215     return 0x20;
1216 }
1217
1218 static int mov_write_smhd_tag(AVIOContext *pb)
1219 {
1220     avio_wb32(pb, 16); /* size */
1221     ffio_wfourcc(pb, "smhd");
1222     avio_wb32(pb, 0); /* version & flags */
1223     avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1224     avio_wb16(pb, 0); /* reserved */
1225     return 16;
1226 }
1227
1228 static int mov_write_vmhd_tag(AVIOContext *pb)
1229 {
1230     avio_wb32(pb, 0x14); /* size (always 0x14) */
1231     ffio_wfourcc(pb, "vmhd");
1232     avio_wb32(pb, 0x01); /* version & flags */
1233     avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1234     return 0x14;
1235 }
1236
1237 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1238 {
1239     const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1240     int64_t pos = avio_tell(pb);
1241
1242     if (!track) { /* no media --> data handler */
1243         hdlr      = "dhlr";
1244         hdlr_type = "url ";
1245         descr     = "DataHandler";
1246     } else {
1247         hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1248         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1249             hdlr_type = "vide";
1250             descr     = "VideoHandler";
1251         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1252             hdlr_type = "soun";
1253             descr     = "SoundHandler";
1254         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1255             if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
1256             else                                      hdlr_type = "text";
1257             descr = "SubtitleHandler";
1258         } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1259             hdlr_type = "hint";
1260             descr     = "HintHandler";
1261         }
1262     }
1263
1264     avio_wb32(pb, 0); /* size */
1265     ffio_wfourcc(pb, "hdlr");
1266     avio_wb32(pb, 0); /* Version & flags */
1267     avio_write(pb, hdlr, 4); /* handler */
1268     ffio_wfourcc(pb, hdlr_type); /* handler type */
1269     avio_wb32(pb, 0); /* reserved */
1270     avio_wb32(pb, 0); /* reserved */
1271     avio_wb32(pb, 0); /* reserved */
1272     if (!track || track->mode == MODE_MOV)
1273         avio_w8(pb, strlen(descr)); /* pascal string */
1274     avio_write(pb, descr, strlen(descr)); /* handler description */
1275     if (track && track->mode != MODE_MOV)
1276         avio_w8(pb, 0); /* c string */
1277     return update_size(pb, pos);
1278 }
1279
1280 static int mov_write_hmhd_tag(AVIOContext *pb)
1281 {
1282     /* This atom must be present, but leaving the values at zero
1283      * seems harmless. */
1284     avio_wb32(pb, 28); /* size */
1285     ffio_wfourcc(pb, "hmhd");
1286     avio_wb32(pb, 0); /* version, flags */
1287     avio_wb16(pb, 0); /* maxPDUsize */
1288     avio_wb16(pb, 0); /* avgPDUsize */
1289     avio_wb32(pb, 0); /* maxbitrate */
1290     avio_wb32(pb, 0); /* avgbitrate */
1291     avio_wb32(pb, 0); /* reserved */
1292     return 28;
1293 }
1294
1295 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1296 {
1297     int64_t pos = avio_tell(pb);
1298     avio_wb32(pb, 0); /* size */
1299     ffio_wfourcc(pb, "minf");
1300     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1301         mov_write_vmhd_tag(pb);
1302     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1303         mov_write_smhd_tag(pb);
1304     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1305         if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb);
1306         else                                      mov_write_nmhd_tag(pb);
1307     } else if (track->tag == MKTAG('r','t','p',' ')) {
1308         mov_write_hmhd_tag(pb);
1309     }
1310     if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1311         mov_write_hdlr_tag(pb, NULL);
1312     mov_write_dinf_tag(pb);
1313     mov_write_stbl_tag(pb, track);
1314     return update_size(pb, pos);
1315 }
1316
1317 static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1318 {
1319     int version = track->track_duration < INT32_MAX ? 0 : 1;
1320
1321     if (track->mode == MODE_ISM)
1322         version = 1;
1323
1324     (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1325     ffio_wfourcc(pb, "mdhd");
1326     avio_w8(pb, version);
1327     avio_wb24(pb, 0); /* flags */
1328     if (version == 1) {
1329         avio_wb64(pb, track->time);
1330         avio_wb64(pb, track->time);
1331     } else {
1332         avio_wb32(pb, track->time); /* creation time */
1333         avio_wb32(pb, track->time); /* modification time */
1334     }
1335     avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1336     if (!track->entry)
1337         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1338     else
1339         (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
1340     avio_wb16(pb, track->language); /* language */
1341     avio_wb16(pb, 0); /* reserved (quality) */
1342
1343     if (version != 0 && track->mode == MODE_MOV) {
1344         av_log(NULL, AV_LOG_ERROR,
1345                "FATAL error, file duration too long for timebase, this file will not be\n"
1346                "playable with quicktime. Choose a different timebase or a different\n"
1347                "container format\n");
1348     }
1349
1350     return 32;
1351 }
1352
1353 static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1354 {
1355     int64_t pos = avio_tell(pb);
1356     avio_wb32(pb, 0); /* size */
1357     ffio_wfourcc(pb, "mdia");
1358     mov_write_mdhd_tag(pb, track);
1359     mov_write_hdlr_tag(pb, track);
1360     mov_write_minf_tag(pb, track);
1361     return update_size(pb, pos);
1362 }
1363
1364 static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1365 {
1366     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1367                                       track->timescale, AV_ROUND_UP);
1368     int version = duration < INT32_MAX ? 0 : 1;
1369
1370     if (track->mode == MODE_ISM)
1371         version = 1;
1372
1373     (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1374     ffio_wfourcc(pb, "tkhd");
1375     avio_w8(pb, version);
1376     avio_wb24(pb, 0xf); /* flags (track enabled) */
1377     if (version == 1) {
1378         avio_wb64(pb, track->time);
1379         avio_wb64(pb, track->time);
1380     } else {
1381         avio_wb32(pb, track->time); /* creation time */
1382         avio_wb32(pb, track->time); /* modification time */
1383     }
1384     avio_wb32(pb, track->track_id); /* track-id */
1385     avio_wb32(pb, 0); /* reserved */
1386     if (!track->entry)
1387         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1388     else
1389         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1390
1391     avio_wb32(pb, 0); /* reserved */
1392     avio_wb32(pb, 0); /* reserved */
1393     avio_wb16(pb, 0); /* layer */
1394     avio_wb16(pb, st ? st->codec->codec_type : 0); /* alternate group) */
1395     /* Volume, only for audio */
1396     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1397         avio_wb16(pb, 0x0100);
1398     else
1399         avio_wb16(pb, 0);
1400     avio_wb16(pb, 0); /* reserved */
1401
1402     /* Matrix structure */
1403     avio_wb32(pb, 0x00010000); /* reserved */
1404     avio_wb32(pb, 0x0); /* reserved */
1405     avio_wb32(pb, 0x0); /* reserved */
1406     avio_wb32(pb, 0x0); /* reserved */
1407     avio_wb32(pb, 0x00010000); /* reserved */
1408     avio_wb32(pb, 0x0); /* reserved */
1409     avio_wb32(pb, 0x0); /* reserved */
1410     avio_wb32(pb, 0x0); /* reserved */
1411     avio_wb32(pb, 0x40000000); /* reserved */
1412
1413     /* Track width and height, for visual only */
1414     if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1415                track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1416         if (track->mode == MODE_MOV) {
1417             avio_wb32(pb, track->enc->width << 16);
1418             avio_wb32(pb, track->height << 16);
1419         } else {
1420             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1421             if (!sample_aspect_ratio || track->height != track->enc->height)
1422                 sample_aspect_ratio = 1;
1423             avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
1424             avio_wb32(pb, track->height * 0x10000);
1425         }
1426     } else {
1427         avio_wb32(pb, 0);
1428         avio_wb32(pb, 0);
1429     }
1430     return 0x5c;
1431 }
1432
1433 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1434 {
1435     int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1436                                track->enc->sample_aspect_ratio.den);
1437
1438     int64_t pos = avio_tell(pb);
1439
1440     avio_wb32(pb, 0); /* size */
1441     ffio_wfourcc(pb, "tapt");
1442
1443     avio_wb32(pb, 20);
1444     ffio_wfourcc(pb, "clef");
1445     avio_wb32(pb, 0);
1446     avio_wb32(pb, width << 16);
1447     avio_wb32(pb, track->enc->height << 16);
1448
1449     avio_wb32(pb, 20);
1450     ffio_wfourcc(pb, "enof");
1451     avio_wb32(pb, 0);
1452     avio_wb32(pb, track->enc->width << 16);
1453     avio_wb32(pb, track->enc->height << 16);
1454
1455     return update_size(pb, pos);
1456 }
1457
1458 // This box seems important for the psp playback ... without it the movie seems to hang
1459 static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1460 {
1461     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1462                                       track->timescale, AV_ROUND_UP);
1463     int version = duration < INT32_MAX ? 0 : 1;
1464     int entry_size, entry_count, size;
1465     int64_t delay, start_ct = track->cluster[0].cts;
1466     delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
1467                            track->timescale, AV_ROUND_DOWN);
1468     version |= delay < INT32_MAX ? 0 : 1;
1469
1470     entry_size = (version == 1) ? 20 : 12;
1471     entry_count = 1 + (delay > 0);
1472     size = 24 + entry_count * entry_size;
1473
1474     /* write the atom data */
1475     avio_wb32(pb, size);
1476     ffio_wfourcc(pb, "edts");
1477     avio_wb32(pb, size - 8);
1478     ffio_wfourcc(pb, "elst");
1479     avio_w8(pb, version);
1480     avio_wb24(pb, 0); /* flags */
1481
1482     avio_wb32(pb, entry_count);
1483     if (delay > 0) { /* add an empty edit to delay presentation */
1484         if (version == 1) {
1485             avio_wb64(pb, delay);
1486             avio_wb64(pb, -1);
1487         } else {
1488             avio_wb32(pb, delay);
1489             avio_wb32(pb, -1);
1490         }
1491         avio_wb32(pb, 0x00010000);
1492     }
1493
1494     /* duration */
1495     if (version == 1) {
1496         avio_wb64(pb, duration);
1497         avio_wb64(pb, start_ct);
1498     } else {
1499         avio_wb32(pb, duration);
1500         avio_wb32(pb, start_ct);
1501     }
1502     avio_wb32(pb, 0x00010000);
1503     return size;
1504 }
1505
1506 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1507 {
1508     avio_wb32(pb, 20);   // size
1509     ffio_wfourcc(pb, "tref");
1510     avio_wb32(pb, 12);   // size (subatom)
1511     avio_wl32(pb, track->tref_tag);
1512     avio_wb32(pb, track->tref_id);
1513     return 20;
1514 }
1515
1516 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1517 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1518 {
1519     avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1520     ffio_wfourcc(pb, "uuid");
1521     ffio_wfourcc(pb, "USMT");
1522     avio_wb32(pb, 0x21d24fce);
1523     avio_wb32(pb, 0xbb88695c);
1524     avio_wb32(pb, 0xfac9c740);
1525     avio_wb32(pb, 0x1c);     // another size here!
1526     ffio_wfourcc(pb, "MTDT");
1527     avio_wb32(pb, 0x00010012);
1528     avio_wb32(pb, 0x0a);
1529     avio_wb32(pb, 0x55c40000);
1530     avio_wb32(pb, 0x1);
1531     avio_wb32(pb, 0x0);
1532     return 0x34;
1533 }
1534
1535 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
1536 {
1537     AVFormatContext *ctx = track->rtp_ctx;
1538     char buf[1000] = "";
1539     int len;
1540
1541     ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
1542                        NULL, NULL, 0, 0, ctx);
1543     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
1544     len = strlen(buf);
1545
1546     avio_wb32(pb, len + 24);
1547     ffio_wfourcc(pb, "udta");
1548     avio_wb32(pb, len + 16);
1549     ffio_wfourcc(pb, "hnti");
1550     avio_wb32(pb, len + 8);
1551     ffio_wfourcc(pb, "sdp ");
1552     avio_write(pb, buf, len);
1553     return len + 24;
1554 }
1555
1556 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
1557                               MOVTrack *track, AVStream *st)
1558 {
1559     int64_t pos = avio_tell(pb);
1560     avio_wb32(pb, 0); /* size */
1561     ffio_wfourcc(pb, "trak");
1562     mov_write_tkhd_tag(pb, track, st);
1563     if (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS ||
1564         (track->entry && track->cluster[0].dts)) {
1565         if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
1566             mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1567     }
1568     if (track->tref_tag)
1569         mov_write_tref_tag(pb, track);
1570     mov_write_mdia_tag(pb, track);
1571     if (track->mode == MODE_PSP)
1572         mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
1573     if (track->tag == MKTAG('r','t','p',' '))
1574         mov_write_udta_sdp(pb, track);
1575     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO && track->mode == MODE_MOV) {
1576         double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1577         if (0.0 != sample_aspect_ratio && 1.0 != sample_aspect_ratio)
1578             mov_write_tapt_tag(pb, track);
1579     }
1580     return update_size(pb, pos);
1581 }
1582
1583 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1584 {
1585     int i, has_audio = 0, has_video = 0;
1586     int64_t pos = avio_tell(pb);
1587     int audio_profile = mov->iods_audio_profile;
1588     int video_profile = mov->iods_video_profile;
1589     for (i = 0; i < mov->nb_streams; i++) {
1590         if (mov->tracks[i].entry > 0) {
1591             has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
1592             has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
1593         }
1594     }
1595     if (audio_profile < 0)
1596         audio_profile = 0xFF - has_audio;
1597     if (video_profile < 0)
1598         video_profile = 0xFF - has_video;
1599     avio_wb32(pb, 0x0); /* size */
1600     ffio_wfourcc(pb, "iods");
1601     avio_wb32(pb, 0);    /* version & flags */
1602     put_descr(pb, 0x10, 7);
1603     avio_wb16(pb, 0x004f);
1604     avio_w8(pb, 0xff);
1605     avio_w8(pb, 0xff);
1606     avio_w8(pb, audio_profile);
1607     avio_w8(pb, video_profile);
1608     avio_w8(pb, 0xff);
1609     return update_size(pb, pos);
1610 }
1611
1612 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
1613 {
1614     avio_wb32(pb, 0x20); /* size */
1615     ffio_wfourcc(pb, "trex");
1616     avio_wb32(pb, 0);   /* version & flags */
1617     avio_wb32(pb, track->track_id); /* track ID */
1618     avio_wb32(pb, 1);   /* default sample description index */
1619     avio_wb32(pb, 0);   /* default sample duration */
1620     avio_wb32(pb, 0);   /* default sample size */
1621     avio_wb32(pb, 0);   /* default sample flags */
1622     return 0;
1623 }
1624
1625 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
1626 {
1627     int64_t pos = avio_tell(pb);
1628     int i;
1629     avio_wb32(pb, 0x0); /* size */
1630     ffio_wfourcc(pb, "mvex");
1631     for (i = 0; i < mov->nb_streams; i++)
1632         mov_write_trex_tag(pb, &mov->tracks[i]);
1633     return update_size(pb, pos);
1634 }
1635
1636 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
1637 {
1638     int max_track_id = 1, i;
1639     int64_t max_track_len_temp, max_track_len = 0;
1640     int version;
1641
1642     for (i = 0; i < mov->nb_streams; i++) {
1643         if (mov->tracks[i].entry > 0) {
1644             max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
1645                                                 MOV_TIMESCALE,
1646                                                 mov->tracks[i].timescale,
1647                                                 AV_ROUND_UP);
1648             if (max_track_len < max_track_len_temp)
1649                 max_track_len = max_track_len_temp;
1650             if (max_track_id < mov->tracks[i].track_id)
1651                 max_track_id = mov->tracks[i].track_id;
1652         }
1653     }
1654
1655     version = max_track_len < UINT32_MAX ? 0 : 1;
1656     (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
1657     ffio_wfourcc(pb, "mvhd");
1658     avio_w8(pb, version);
1659     avio_wb24(pb, 0); /* flags */
1660     if (version == 1) {
1661         avio_wb64(pb, mov->time);
1662         avio_wb64(pb, mov->time);
1663     } else {
1664         avio_wb32(pb, mov->time); /* creation time */
1665         avio_wb32(pb, mov->time); /* modification time */
1666     }
1667     avio_wb32(pb, MOV_TIMESCALE);
1668     (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
1669
1670     avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1671     avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1672     avio_wb16(pb, 0); /* reserved */
1673     avio_wb32(pb, 0); /* reserved */
1674     avio_wb32(pb, 0); /* reserved */
1675
1676     /* Matrix structure */
1677     avio_wb32(pb, 0x00010000); /* reserved */
1678     avio_wb32(pb, 0x0); /* reserved */
1679     avio_wb32(pb, 0x0); /* reserved */
1680     avio_wb32(pb, 0x0); /* reserved */
1681     avio_wb32(pb, 0x00010000); /* reserved */
1682     avio_wb32(pb, 0x0); /* reserved */
1683     avio_wb32(pb, 0x0); /* reserved */
1684     avio_wb32(pb, 0x0); /* reserved */
1685     avio_wb32(pb, 0x40000000); /* reserved */
1686
1687     avio_wb32(pb, 0); /* reserved (preview time) */
1688     avio_wb32(pb, 0); /* reserved (preview duration) */
1689     avio_wb32(pb, 0); /* reserved (poster time) */
1690     avio_wb32(pb, 0); /* reserved (selection time) */
1691     avio_wb32(pb, 0); /* reserved (selection duration) */
1692     avio_wb32(pb, 0); /* reserved (current time) */
1693     avio_wb32(pb, max_track_id + 1); /* Next track id */
1694     return 0x6c;
1695 }
1696
1697 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
1698                                      AVFormatContext *s)
1699 {
1700     avio_wb32(pb, 33); /* size */
1701     ffio_wfourcc(pb, "hdlr");
1702     avio_wb32(pb, 0);
1703     avio_wb32(pb, 0);
1704     ffio_wfourcc(pb, "mdir");
1705     ffio_wfourcc(pb, "appl");
1706     avio_wb32(pb, 0);
1707     avio_wb32(pb, 0);
1708     avio_w8(pb, 0);
1709     return 33;
1710 }
1711
1712 /* helper function to write a data tag with the specified string as data */
1713 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
1714 {
1715     if (long_style) {
1716         int size = 16 + strlen(data);
1717         avio_wb32(pb, size); /* size */
1718         ffio_wfourcc(pb, "data");
1719         avio_wb32(pb, 1);
1720         avio_wb32(pb, 0);
1721         avio_write(pb, data, strlen(data));
1722         return size;
1723     } else {
1724         if (!lang)
1725             lang = ff_mov_iso639_to_lang("und", 1);
1726         avio_wb16(pb, strlen(data)); /* string length */
1727         avio_wb16(pb, lang);
1728         avio_write(pb, data, strlen(data));
1729         return strlen(data) + 4;
1730     }
1731 }
1732
1733 static int mov_write_string_tag(AVIOContext *pb, const char *name,
1734                                 const char *value, int lang, int long_style)
1735 {
1736     int size = 0;
1737     if (value && value[0]) {
1738         int64_t pos = avio_tell(pb);
1739         avio_wb32(pb, 0); /* size */
1740         ffio_wfourcc(pb, name);
1741         mov_write_string_data_tag(pb, value, lang, long_style);
1742         size = update_size(pb, pos);
1743     }
1744     return size;
1745 }
1746
1747 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
1748                                      const char *name, const char *tag,
1749                                      int long_style)
1750 {
1751     int l, lang = 0, len, len2;
1752     AVDictionaryEntry *t, *t2 = NULL;
1753     char tag2[16];
1754
1755     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
1756         return 0;
1757
1758     len = strlen(t->key);
1759     snprintf(tag2, sizeof(tag2), "%s-", tag);
1760     while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
1761         len2 = strlen(t2->key);
1762         if (len2 == len + 4 && !strcmp(t->value, t2->value)
1763             && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
1764             lang = l;
1765             break;
1766         }
1767     }
1768     return mov_write_string_tag(pb, name, t->value, lang, long_style);
1769 }
1770
1771 /* iTunes track number */
1772 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
1773                               AVFormatContext *s)
1774 {
1775     AVDictionaryEntry *t = av_dict_get(s->metadata, "track", NULL, 0);
1776     int size = 0, track = t ? atoi(t->value) : 0;
1777     if (track) {
1778         avio_wb32(pb, 32); /* size */
1779         ffio_wfourcc(pb, "trkn");
1780         avio_wb32(pb, 24); /* size */
1781         ffio_wfourcc(pb, "data");
1782         avio_wb32(pb, 0);        // 8 bytes empty
1783         avio_wb32(pb, 0);
1784         avio_wb16(pb, 0);        // empty
1785         avio_wb16(pb, track);    // track number
1786         avio_wb16(pb, 0);        // total track number
1787         avio_wb16(pb, 0);        // empty
1788         size = 32;
1789     }
1790     return size;
1791 }
1792
1793 /* iTunes meta data list */
1794 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
1795                               AVFormatContext *s)
1796 {
1797     int64_t pos = avio_tell(pb);
1798     avio_wb32(pb, 0); /* size */
1799     ffio_wfourcc(pb, "ilst");
1800     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1801     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
1802     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
1803     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1804     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1805     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
1806     mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1807     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1808     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1809     mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1810     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
1811     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
1812     mov_write_string_metadata(s, pb, "desc",    "description",1);
1813     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
1814     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
1815     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
1816     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
1817     mov_write_trkn_tag(pb, mov, s);
1818     return update_size(pb, pos);
1819 }
1820
1821 /* iTunes meta data tag */
1822 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
1823                               AVFormatContext *s)
1824 {
1825     int size = 0;
1826     int64_t pos = avio_tell(pb);
1827     avio_wb32(pb, 0); /* size */
1828     ffio_wfourcc(pb, "meta");
1829     avio_wb32(pb, 0);
1830     mov_write_itunes_hdlr_tag(pb, mov, s);
1831     mov_write_ilst_tag(pb, mov, s);
1832     size = update_size(pb, pos);
1833     return size;
1834 }
1835
1836 static int utf8len(const uint8_t *b)
1837 {
1838     int len = 0;
1839     int val;
1840     while (*b) {
1841         GET_UTF8(val, *b++, return -1;)
1842         len++;
1843     }
1844     return len;
1845 }
1846
1847 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
1848 {
1849     int val;
1850     while (*b) {
1851         GET_UTF8(val, *b++, return -1;)
1852         avio_wb16(pb, val);
1853     }
1854     avio_wb16(pb, 0x00);
1855     return 0;
1856 }
1857
1858 static uint16_t language_code(const char *str)
1859 {
1860     return (((str[0] - 0x60) & 0x1F) << 10) +
1861            (((str[1] - 0x60) & 0x1F) <<  5) +
1862            (( str[2] - 0x60) & 0x1F);
1863 }
1864
1865 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
1866                                   const char *tag, const char *str)
1867 {
1868     int64_t pos = avio_tell(pb);
1869     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
1870     if (!t || !utf8len(t->value))
1871         return 0;
1872     avio_wb32(pb, 0);   /* size */
1873     ffio_wfourcc(pb, tag); /* type */
1874     avio_wb32(pb, 0);   /* version + flags */
1875     if (!strcmp(tag, "yrrc"))
1876         avio_wb16(pb, atoi(t->value));
1877     else {
1878         avio_wb16(pb, language_code("eng")); /* language */
1879         avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
1880         if (!strcmp(tag, "albm") &&
1881             (t = av_dict_get(s->metadata, "track", NULL, 0)))
1882             avio_w8(pb, atoi(t->value));
1883     }
1884     return update_size(pb, pos);
1885 }
1886
1887 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
1888 {
1889     int64_t pos = avio_tell(pb);
1890     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
1891
1892     avio_wb32(pb, 0);            // size
1893     ffio_wfourcc(pb, "chpl");
1894     avio_wb32(pb, 0x01000000);   // version + flags
1895     avio_wb32(pb, 0);            // unknown
1896     avio_w8(pb, nb_chapters);
1897
1898     for (i = 0; i < nb_chapters; i++) {
1899         AVChapter *c = s->chapters[i];
1900         AVDictionaryEntry *t;
1901         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
1902
1903         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1904             int len = FFMIN(strlen(t->value), 255);
1905             avio_w8(pb, len);
1906             avio_write(pb, t->value, len);
1907         } else
1908             avio_w8(pb, 0);
1909     }
1910     return update_size(pb, pos);
1911 }
1912
1913 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
1914                               AVFormatContext *s)
1915 {
1916     AVIOContext *pb_buf;
1917     int i, ret, size;
1918     uint8_t *buf;
1919
1920     for (i = 0; i < s->nb_streams; i++)
1921         if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1922             return 0;
1923         }
1924
1925     ret = avio_open_dyn_buf(&pb_buf);
1926     if (ret < 0)
1927         return ret;
1928
1929     if (mov->mode & MODE_3GP) {
1930         mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
1931         mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1932         mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1933         mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1934         mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1935         mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1936         mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1937         mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
1938     } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1939         mov_write_string_metadata(s, pb_buf, "\251ART", "artist",      0);
1940         mov_write_string_metadata(s, pb_buf, "\251nam", "title",       0);
1941         mov_write_string_metadata(s, pb_buf, "\251aut", "author",      0);
1942         mov_write_string_metadata(s, pb_buf, "\251alb", "album",       0);
1943         mov_write_string_metadata(s, pb_buf, "\251day", "date",        0);
1944         mov_write_string_metadata(s, pb_buf, "\251swr", "encoder",     0);
1945         mov_write_string_metadata(s, pb_buf, "\251des", "comment",     0);
1946         mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);
1947         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);
1948     } else {
1949         /* iTunes meta data */
1950         mov_write_meta_tag(pb_buf, mov, s);
1951     }
1952
1953     if (s->nb_chapters)
1954         mov_write_chpl_tag(pb_buf, s);
1955
1956     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
1957         avio_wb32(pb, size + 8);
1958         ffio_wfourcc(pb, "udta");
1959         avio_write(pb, buf, size);
1960     }
1961     av_free(buf);
1962
1963     return 0;
1964 }
1965
1966 static void mov_write_psp_udta_tag(AVIOContext *pb,
1967                                    const char *str, const char *lang, int type)
1968 {
1969     int len = utf8len(str) + 1;
1970     if (len <= 0)
1971         return;
1972     avio_wb16(pb, len * 2 + 10);        /* size */
1973     avio_wb32(pb, type);                /* type */
1974     avio_wb16(pb, language_code(lang)); /* language */
1975     avio_wb16(pb, 0x01);                /* ? */
1976     ascii_to_wc(pb, str);
1977 }
1978
1979 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
1980 {
1981     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
1982     int64_t pos, pos2;
1983
1984     if (title) {
1985         pos = avio_tell(pb);
1986         avio_wb32(pb, 0); /* size placeholder*/
1987         ffio_wfourcc(pb, "uuid");
1988         ffio_wfourcc(pb, "USMT");
1989         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
1990         avio_wb32(pb, 0xbb88695c);
1991         avio_wb32(pb, 0xfac9c740);
1992
1993         pos2 = avio_tell(pb);
1994         avio_wb32(pb, 0); /* size placeholder*/
1995         ffio_wfourcc(pb, "MTDT");
1996         avio_wb16(pb, 4);
1997
1998         // ?
1999         avio_wb16(pb, 0x0C);                 /* size */
2000         avio_wb32(pb, 0x0B);                 /* type */
2001         avio_wb16(pb, language_code("und")); /* language */
2002         avio_wb16(pb, 0x0);                  /* ? */
2003         avio_wb16(pb, 0x021C);               /* data */
2004
2005         mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
2006         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
2007         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2008
2009         update_size(pb, pos2);
2010         return update_size(pb, pos);
2011     }
2012
2013     return 0;
2014 }
2015
2016 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2017                               AVFormatContext *s)
2018 {
2019     int i;
2020     int64_t pos = avio_tell(pb);
2021     avio_wb32(pb, 0); /* size placeholder*/
2022     ffio_wfourcc(pb, "moov");
2023
2024     for (i = 0; i < mov->nb_streams; i++) {
2025         if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2026             continue;
2027
2028         mov->tracks[i].time     = mov->time;
2029         mov->tracks[i].track_id = i + 1;
2030     }
2031
2032     if (mov->chapter_track)
2033         for (i = 0; i < s->nb_streams; i++) {
2034             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2035             mov->tracks[i].tref_id  = mov->tracks[mov->chapter_track].track_id;
2036         }
2037     for (i = 0; i < mov->nb_streams; i++) {
2038         if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
2039             mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
2040             mov->tracks[i].tref_id =
2041                 mov->tracks[mov->tracks[i].src_track].track_id;
2042         }
2043     }
2044
2045     mov_write_mvhd_tag(pb, mov);
2046     if (mov->mode != MODE_MOV && !mov->iods_skip)
2047         mov_write_iods_tag(pb, mov);
2048     for (i = 0; i < mov->nb_streams; i++) {
2049         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2050             mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2051         }
2052     }
2053     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2054         mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2055
2056     if (mov->mode == MODE_PSP)
2057         mov_write_uuidusmt_tag(pb, s);
2058     else
2059         mov_write_udta_tag(pb, mov, s);
2060
2061     return update_size(pb, pos);
2062 }
2063
2064 static void param_write_int(AVIOContext *pb, const char *name, int value)
2065 {
2066     avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2067 }
2068
2069 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2070 {
2071     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2072 }
2073
2074 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2075 {
2076     char buf[150];
2077     len = FFMIN(sizeof(buf) / 2 - 1, len);
2078     ff_data_to_hex(buf, value, len, 0);
2079     buf[2 * len] = '\0';
2080     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2081 }
2082
2083 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2084 {
2085     int64_t pos = avio_tell(pb);
2086     int i;
2087     const uint8_t uuid[] = {
2088         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2089         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2090     };
2091
2092     avio_wb32(pb, 0);
2093     ffio_wfourcc(pb, "uuid");
2094     avio_write(pb, uuid, sizeof(uuid));
2095     avio_wb32(pb, 0);
2096
2097     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2098     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2099     avio_printf(pb, "<head>\n");
2100     avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2101                     LIBAVFORMAT_IDENT);
2102     avio_printf(pb, "</head>\n");
2103     avio_printf(pb, "<body>\n");
2104     avio_printf(pb, "<switch>\n");
2105     for (i = 0; i < mov->nb_streams; i++) {
2106         MOVTrack *track = &mov->tracks[i];
2107         const char *type;
2108         /* track->track_id is initialized in write_moov, and thus isn't known
2109          * here yet */
2110         int track_id = i + 1;
2111
2112         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2113             type = "video";
2114         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2115             type = "audio";
2116         } else {
2117             continue;
2118         }
2119         avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
2120                                                        track->enc->bit_rate);
2121         param_write_int(pb, "systemBitrate", track->enc->bit_rate);
2122         param_write_int(pb, "trackID", track_id);
2123         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2124             if (track->enc->codec_id == AV_CODEC_ID_H264) {
2125                 uint8_t *ptr;
2126                 int size = track->enc->extradata_size;
2127                 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
2128                                                    &size)) {
2129                     param_write_hex(pb, "CodecPrivateData",
2130                                     ptr ? ptr : track->enc->extradata,
2131                                     size);
2132                     av_free(ptr);
2133                 }
2134                 param_write_string(pb, "FourCC", "H264");
2135             } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
2136                 param_write_string(pb, "FourCC", "WVC1");
2137                 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2138                                 track->enc->extradata_size);
2139             }
2140             param_write_int(pb, "MaxWidth", track->enc->width);
2141             param_write_int(pb, "MaxHeight", track->enc->height);
2142             param_write_int(pb, "DisplayWidth", track->enc->width);
2143             param_write_int(pb, "DisplayHeight", track->enc->height);
2144         } else {
2145             if (track->enc->codec_id == AV_CODEC_ID_AAC) {
2146                 param_write_string(pb, "FourCC", "AACL");
2147             } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
2148                 param_write_string(pb, "FourCC", "WMAP");
2149             }
2150             param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2151                             track->enc->extradata_size);
2152             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
2153                                                              track->enc->codec_id));
2154             param_write_int(pb, "Channels", track->enc->channels);
2155             param_write_int(pb, "SamplingRate", track->enc->sample_rate);
2156             param_write_int(pb, "BitsPerSample", 16);
2157             param_write_int(pb, "PacketSize", track->enc->block_align ?
2158                                               track->enc->block_align : 4);
2159         }
2160         avio_printf(pb, "</%s>\n", type);
2161     }
2162     avio_printf(pb, "</switch>\n");
2163     avio_printf(pb, "</body>\n");
2164     avio_printf(pb, "</smil>\n");
2165
2166     return update_size(pb, pos);
2167 }
2168
2169 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2170 {
2171     avio_wb32(pb, 16);
2172     ffio_wfourcc(pb, "mfhd");
2173     avio_wb32(pb, 0);
2174     avio_wb32(pb, mov->fragments);
2175     return 0;
2176 }
2177
2178 static int mov_write_tfhd_tag(AVIOContext *pb, MOVTrack *track,
2179                               int64_t moof_offset)
2180 {
2181     int64_t pos = avio_tell(pb);
2182     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2183                      MOV_TFHD_BASE_DATA_OFFSET;
2184     if (!track->entry) {
2185         flags |= MOV_TFHD_DURATION_IS_EMPTY;
2186     } else {
2187         flags |= MOV_TFHD_DEFAULT_FLAGS;
2188     }
2189
2190     /* Don't set a default sample size, the silverlight player refuses
2191      * to play files with that set. Don't set a default sample duration,
2192      * WMP freaks out if it is set. Don't set a base data offset, PIFF
2193      * file format says it MUST NOT be set. */
2194     if (track->mode == MODE_ISM)
2195         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2196                    MOV_TFHD_BASE_DATA_OFFSET);
2197
2198     avio_wb32(pb, 0); /* size placeholder */
2199     ffio_wfourcc(pb, "tfhd");
2200     avio_w8(pb, 0); /* version */
2201     avio_wb24(pb, flags);
2202
2203     avio_wb32(pb, track->track_id); /* track-id */
2204     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
2205         avio_wb64(pb, moof_offset);
2206     if (flags & MOV_TFHD_DEFAULT_DURATION) {
2207         track->default_duration = get_cluster_duration(track, 0);
2208         avio_wb32(pb, track->default_duration);
2209     }
2210     if (flags & MOV_TFHD_DEFAULT_SIZE) {
2211         track->default_size = track->entry ? track->cluster[0].size : 1;
2212         avio_wb32(pb, track->default_size);
2213     } else
2214         track->default_size = -1;
2215
2216     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
2217         track->default_sample_flags =
2218             track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
2219             (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2220             MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
2221         avio_wb32(pb, track->default_sample_flags);
2222     }
2223
2224     return update_size(pb, pos);
2225 }
2226
2227 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2228 {
2229     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2230            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2231 }
2232
2233 static int mov_write_trun_tag(AVIOContext *pb, MOVTrack *track)
2234 {
2235     int64_t pos = avio_tell(pb);
2236     uint32_t flags = MOV_TRUN_DATA_OFFSET;
2237     int i;
2238
2239     for (i = 0; i < track->entry; i++) {
2240         if (get_cluster_duration(track, i) != track->default_duration)
2241             flags |= MOV_TRUN_SAMPLE_DURATION;
2242         if (track->cluster[i].size != track->default_size)
2243             flags |= MOV_TRUN_SAMPLE_SIZE;
2244         if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
2245             flags |= MOV_TRUN_SAMPLE_FLAGS;
2246     }
2247     if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
2248         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
2249     if (track->flags & MOV_TRACK_CTTS)
2250         flags |= MOV_TRUN_SAMPLE_CTS;
2251
2252     avio_wb32(pb, 0); /* size placeholder */
2253     ffio_wfourcc(pb, "trun");
2254     avio_w8(pb, 0); /* version */
2255     avio_wb24(pb, flags);
2256
2257     avio_wb32(pb, track->entry); /* sample count */
2258     track->moof_size_offset = avio_tell(pb);
2259     avio_wb32(pb, 0); /* data offset */
2260     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
2261         avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
2262
2263     for (i = 0; i < track->entry; i++) {
2264         if (flags & MOV_TRUN_SAMPLE_DURATION)
2265             avio_wb32(pb, get_cluster_duration(track, i));
2266         if (flags & MOV_TRUN_SAMPLE_SIZE)
2267             avio_wb32(pb, track->cluster[i].size);
2268         if (flags & MOV_TRUN_SAMPLE_FLAGS)
2269             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
2270         if (flags & MOV_TRUN_SAMPLE_CTS)
2271             avio_wb32(pb, track->cluster[i].cts);
2272     }
2273
2274     return update_size(pb, pos);
2275 }
2276
2277 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2278 {
2279     int64_t pos = avio_tell(pb);
2280     const uint8_t uuid[] = {
2281         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2282         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2283     };
2284
2285     avio_wb32(pb, 0); /* size placeholder */
2286     ffio_wfourcc(pb, "uuid");
2287     avio_write(pb, uuid, sizeof(uuid));
2288     avio_w8(pb, 1);
2289     avio_wb24(pb, 0);
2290     avio_wb64(pb, track->frag_start);
2291     avio_wb64(pb, track->start_dts + track->track_duration -
2292                   track->cluster[0].dts);
2293
2294     return update_size(pb, pos);
2295 }
2296
2297 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2298                               MOVTrack *track, int entry)
2299 {
2300     int n = track->nb_frag_info - 1 - entry, i;
2301     int size = 8 + 16 + 4 + 1 + 16*n;
2302     const uint8_t uuid[] = {
2303         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2304         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2305     };
2306
2307     if (entry < 0)
2308         return 0;
2309
2310     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2311     avio_wb32(pb, size);
2312     ffio_wfourcc(pb, "uuid");
2313     avio_write(pb, uuid, sizeof(uuid));
2314     avio_w8(pb, 1);
2315     avio_wb24(pb, 0);
2316     avio_w8(pb, n);
2317     for (i = 0; i < n; i++) {
2318         int index = entry + 1 + i;
2319         avio_wb64(pb, track->frag_info[index].time);
2320         avio_wb64(pb, track->frag_info[index].duration);
2321     }
2322     if (n < mov->ism_lookahead) {
2323         int free_size = 16 * (mov->ism_lookahead - n);
2324         avio_wb32(pb, free_size);
2325         ffio_wfourcc(pb, "free");
2326         for (i = 0; i < free_size - 8; i++)
2327             avio_w8(pb, 0);
2328     }
2329
2330     return 0;
2331 }
2332
2333 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2334                                MOVTrack *track)
2335 {
2336     int64_t pos = avio_tell(pb);
2337     int i;
2338     for (i = 0; i < mov->ism_lookahead; i++) {
2339         /* Update the tfrf tag for the last ism_lookahead fragments,
2340          * nb_frag_info - 1 is the next fragment to be written. */
2341         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2342     }
2343     avio_seek(pb, pos, SEEK_SET);
2344     return 0;
2345 }
2346
2347 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
2348                               MOVTrack *track, int64_t moof_offset)
2349 {
2350     int64_t pos = avio_tell(pb);
2351     avio_wb32(pb, 0); /* size placeholder */
2352     ffio_wfourcc(pb, "traf");
2353
2354     mov_write_tfhd_tag(pb, track, moof_offset);
2355     mov_write_trun_tag(pb, track);
2356     if (mov->mode == MODE_ISM) {
2357         mov_write_tfxd_tag(pb, track);
2358
2359         if (mov->ism_lookahead) {
2360             int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
2361
2362             track->tfrf_offset = avio_tell(pb);
2363             avio_wb32(pb, 8 + size);
2364             ffio_wfourcc(pb, "free");
2365             for (i = 0; i < size; i++)
2366                 avio_w8(pb, 0);
2367         }
2368     }
2369
2370     return update_size(pb, pos);
2371 }
2372
2373 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
2374 {
2375     int64_t pos = avio_tell(pb), end;
2376     int i, moof_size;
2377
2378     avio_wb32(pb, 0); /* size placeholder */
2379     ffio_wfourcc(pb, "moof");
2380
2381     mov_write_mfhd_tag(pb, mov);
2382     for (i = 0; i < mov->nb_streams; i++) {
2383         MOVTrack *track = &mov->tracks[i];
2384         if (tracks >= 0 && i != tracks)
2385             continue;
2386         if (!track->entry)
2387             continue;
2388         mov_write_traf_tag(pb, mov, track, pos);
2389     }
2390
2391     end = avio_tell(pb);
2392     moof_size = end - pos;
2393     for (i = 0; i < mov->nb_streams; i++) {
2394         MOVTrack *track = &mov->tracks[i];
2395         if (tracks >= 0 && i != tracks)
2396             continue;
2397         if (!track->entry)
2398             continue;
2399         avio_seek(pb, mov->tracks[i].moof_size_offset, SEEK_SET);
2400         avio_wb32(pb, moof_size + 8 + mov->tracks[i].data_offset);
2401     }
2402     avio_seek(pb, end, SEEK_SET);
2403
2404     return update_size(pb, pos);
2405 }
2406
2407 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
2408 {
2409     int64_t pos = avio_tell(pb);
2410     int i;
2411
2412     avio_wb32(pb, 0); /* size placeholder */
2413     ffio_wfourcc(pb, "tfra");
2414     avio_w8(pb, 1); /* version */
2415     avio_wb24(pb, 0);
2416
2417     avio_wb32(pb, track->track_id);
2418     avio_wb32(pb, 0); /* length of traf/trun/sample num */
2419     avio_wb32(pb, track->nb_frag_info);
2420     for (i = 0; i < track->nb_frag_info; i++) {
2421         avio_wb64(pb, track->frag_info[i].time);
2422         avio_wb64(pb, track->frag_info[i].offset);
2423         avio_w8(pb, 1); /* traf number */
2424         avio_w8(pb, 1); /* trun number */
2425         avio_w8(pb, 1); /* sample number */
2426     }
2427
2428     return update_size(pb, pos);
2429 }
2430
2431 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
2432 {
2433     int64_t pos = avio_tell(pb);
2434     int i;
2435
2436     avio_wb32(pb, 0); /* size placeholder */
2437     ffio_wfourcc(pb, "mfra");
2438     /* An empty mfra atom is enough to indicate to the publishing point that
2439      * the stream has ended. */
2440     if (mov->flags & FF_MOV_FLAG_ISML)
2441         return update_size(pb, pos);
2442
2443     for (i = 0; i < mov->nb_streams; i++) {
2444         MOVTrack *track = &mov->tracks[i];
2445         if (track->nb_frag_info)
2446             mov_write_tfra_tag(pb, track);
2447     }
2448
2449     avio_wb32(pb, 16);
2450     ffio_wfourcc(pb, "mfro");
2451     avio_wb32(pb, 0); /* version + flags */
2452     avio_wb32(pb, avio_tell(pb) + 4 - pos);
2453
2454     return update_size(pb, pos);
2455 }
2456
2457 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
2458 {
2459     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
2460     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
2461
2462     mov->mdat_pos = avio_tell(pb);
2463     avio_wb32(pb, 0); /* size placeholder*/
2464     ffio_wfourcc(pb, "mdat");
2465     return 0;
2466 }
2467
2468 /* TODO: This needs to be more general */
2469 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
2470 {
2471     MOVMuxContext *mov = s->priv_data;
2472     int64_t pos = avio_tell(pb);
2473     int has_h264 = 0, has_video = 0;
2474     int minor = 0x200;
2475     int i;
2476
2477     for (i = 0; i < s->nb_streams; i++) {
2478         AVStream *st = s->streams[i];
2479         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2480             has_video = 1;
2481         if (st->codec->codec_id == AV_CODEC_ID_H264)
2482             has_h264 = 1;
2483     }
2484
2485     avio_wb32(pb, 0); /* size */
2486     ffio_wfourcc(pb, "ftyp");
2487
2488     if (mov->mode == MODE_3GP) {
2489         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
2490         minor =     has_h264 ?   0x100 :   0x200;
2491     } else if (mov->mode & MODE_3G2) {
2492         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
2493         minor =     has_h264 ? 0x20000 : 0x10000;
2494     } else if (mov->mode == MODE_PSP)
2495         ffio_wfourcc(pb, "MSNV");
2496     else if (mov->mode == MODE_MP4)
2497         ffio_wfourcc(pb, "isom");
2498     else if (mov->mode == MODE_IPOD)
2499         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
2500     else if (mov->mode == MODE_ISM)
2501         ffio_wfourcc(pb, "isml");
2502     else
2503         ffio_wfourcc(pb, "qt  ");
2504
2505     avio_wb32(pb, minor);
2506
2507     if (mov->mode == MODE_MOV)
2508         ffio_wfourcc(pb, "qt  ");
2509     else if (mov->mode == MODE_ISM) {
2510         ffio_wfourcc(pb, "piff");
2511         ffio_wfourcc(pb, "iso2");
2512     } else {
2513         ffio_wfourcc(pb, "isom");
2514         ffio_wfourcc(pb, "iso2");
2515         if (has_h264)
2516             ffio_wfourcc(pb, "avc1");
2517     }
2518
2519     if (mov->mode == MODE_3GP)
2520         ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
2521     else if (mov->mode & MODE_3G2)
2522         ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
2523     else if (mov->mode == MODE_PSP)
2524         ffio_wfourcc(pb, "MSNV");
2525     else if (mov->mode == MODE_MP4)
2526         ffio_wfourcc(pb, "mp41");
2527     return update_size(pb, pos);
2528 }
2529
2530 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
2531 {
2532     AVCodecContext *video_codec = s->streams[0]->codec;
2533     AVCodecContext *audio_codec = s->streams[1]->codec;
2534     int audio_rate = audio_codec->sample_rate;
2535     int frame_rate = ((video_codec->time_base.den) * (0x10000)) / (video_codec->time_base.num);
2536     int audio_kbitrate = audio_codec->bit_rate / 1000;
2537     int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
2538
2539     avio_wb32(pb, 0x94); /* size */
2540     ffio_wfourcc(pb, "uuid");
2541     ffio_wfourcc(pb, "PROF");
2542
2543     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2544     avio_wb32(pb, 0xbb88695c);
2545     avio_wb32(pb, 0xfac9c740);
2546
2547     avio_wb32(pb, 0x0);  /* ? */
2548     avio_wb32(pb, 0x3);  /* 3 sections ? */
2549
2550     avio_wb32(pb, 0x14); /* size */
2551     ffio_wfourcc(pb, "FPRF");
2552     avio_wb32(pb, 0x0);  /* ? */
2553     avio_wb32(pb, 0x0);  /* ? */
2554     avio_wb32(pb, 0x0);  /* ? */
2555
2556     avio_wb32(pb, 0x2c);  /* size */
2557     ffio_wfourcc(pb, "APRF"); /* audio */
2558     avio_wb32(pb, 0x0);
2559     avio_wb32(pb, 0x2);   /* TrackID */
2560     ffio_wfourcc(pb, "mp4a");
2561     avio_wb32(pb, 0x20f);
2562     avio_wb32(pb, 0x0);
2563     avio_wb32(pb, audio_kbitrate);
2564     avio_wb32(pb, audio_kbitrate);
2565     avio_wb32(pb, audio_rate);
2566     avio_wb32(pb, audio_codec->channels);
2567
2568     avio_wb32(pb, 0x34);  /* size */
2569     ffio_wfourcc(pb, "VPRF");   /* video */
2570     avio_wb32(pb, 0x0);
2571     avio_wb32(pb, 0x1);    /* TrackID */
2572     if (video_codec->codec_id == AV_CODEC_ID_H264) {
2573         ffio_wfourcc(pb, "avc1");
2574         avio_wb16(pb, 0x014D);
2575         avio_wb16(pb, 0x0015);
2576     } else {
2577         ffio_wfourcc(pb, "mp4v");
2578         avio_wb16(pb, 0x0000);
2579         avio_wb16(pb, 0x0103);
2580     }
2581     avio_wb32(pb, 0x0);
2582     avio_wb32(pb, video_kbitrate);
2583     avio_wb32(pb, video_kbitrate);
2584     avio_wb32(pb, frame_rate);
2585     avio_wb32(pb, frame_rate);
2586     avio_wb16(pb, video_codec->width);
2587     avio_wb16(pb, video_codec->height);
2588     avio_wb32(pb, 0x010001); /* ? */
2589 }
2590
2591 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
2592 {
2593     uint32_t c = -1;
2594     int i, closed_gop = 0;
2595
2596     for (i = 0; i < pkt->size - 4; i++) {
2597         c = (c << 8) + pkt->data[i];
2598         if (c == 0x1b8) { // gop
2599             closed_gop = pkt->data[i + 4] >> 6 & 0x01;
2600         } else if (c == 0x100) { // pic
2601             int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
2602             if (!temp_ref || closed_gop) // I picture is not reordered
2603                 *flags = MOV_SYNC_SAMPLE;
2604             else
2605                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
2606             break;
2607         }
2608     }
2609     return 0;
2610 }
2611
2612 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
2613 {
2614     const uint8_t *start, *next, *end = pkt->data + pkt->size;
2615     int seq = 0, entry = 0;
2616     int key = pkt->flags & AV_PKT_FLAG_KEY;
2617     start = find_next_marker(pkt->data, end);
2618     for (next = start; next < end; start = next) {
2619         next = find_next_marker(start + 4, end);
2620         switch (AV_RB32(start)) {
2621         case VC1_CODE_SEQHDR:
2622             seq = 1;
2623             break;
2624         case VC1_CODE_ENTRYPOINT:
2625             entry = 1;
2626             break;
2627         case VC1_CODE_SLICE:
2628             trk->vc1_info.slices = 1;
2629             break;
2630         }
2631     }
2632     if (!trk->entry && !fragment) {
2633         /* First packet in first fragment */
2634         trk->vc1_info.first_packet_seq   = seq;
2635         trk->vc1_info.first_packet_entry = entry;
2636     } else if ((seq && !trk->vc1_info.packet_seq) ||
2637                (entry && !trk->vc1_info.packet_entry)) {
2638         int i;
2639         for (i = 0; i < trk->entry; i++)
2640             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
2641         trk->has_keyframes = 0;
2642         if (seq)
2643             trk->vc1_info.packet_seq = 1;
2644         if (entry)
2645             trk->vc1_info.packet_entry = 1;
2646         if (!fragment) {
2647             /* First fragment */
2648             if ((!seq   || trk->vc1_info.first_packet_seq) &&
2649                 (!entry || trk->vc1_info.first_packet_entry)) {
2650                 /* First packet had the same headers as this one, readd the
2651                  * sync sample flag. */
2652                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
2653                 trk->has_keyframes = 1;
2654             }
2655         }
2656     }
2657     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
2658         key = seq && entry;
2659     else if (trk->vc1_info.packet_seq)
2660         key = seq;
2661     else if (trk->vc1_info.packet_entry)
2662         key = entry;
2663     if (key) {
2664         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
2665         trk->has_keyframes++;
2666     }
2667 }
2668
2669 static int mov_flush_fragment(AVFormatContext *s)
2670 {
2671     MOVMuxContext *mov = s->priv_data;
2672     int i, first_track = -1;
2673     int64_t mdat_size = 0;
2674
2675     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
2676         return 0;
2677
2678     if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
2679         int64_t pos = avio_tell(s->pb);
2680         int ret;
2681         AVIOContext *moov_buf;
2682         uint8_t *buf;
2683         int buf_size;
2684
2685         for (i = 0; i < mov->nb_streams; i++)
2686             if (!mov->tracks[i].entry)
2687                 break;
2688         /* Don't write the initial moov unless all tracks have data */
2689         if (i < mov->nb_streams)
2690             return 0;
2691
2692         if ((ret = avio_open_dyn_buf(&moov_buf)) < 0)
2693             return ret;
2694         mov_write_moov_tag(moov_buf, mov, s);
2695         buf_size = avio_close_dyn_buf(moov_buf, &buf);
2696         av_free(buf);
2697         for (i = 0; i < mov->nb_streams; i++)
2698             mov->tracks[i].data_offset = pos + buf_size + 8;
2699
2700         mov_write_moov_tag(s->pb, mov, s);
2701
2702         buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
2703         mov->mdat_buf = NULL;
2704         avio_wb32(s->pb, buf_size + 8);
2705         ffio_wfourcc(s->pb, "mdat");
2706         avio_write(s->pb, buf, buf_size);
2707         av_free(buf);
2708
2709         mov->fragments++;
2710         mov->mdat_size = 0;
2711         for (i = 0; i < mov->nb_streams; i++) {
2712             if (mov->tracks[i].entry)
2713                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
2714                                              mov->tracks[i].track_duration -
2715                                              mov->tracks[i].cluster[0].dts;
2716             mov->tracks[i].entry = 0;
2717         }
2718         avio_flush(s->pb);
2719         return 0;
2720     }
2721
2722     for (i = 0; i < mov->nb_streams; i++) {
2723         MOVTrack *track = &mov->tracks[i];
2724         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
2725             track->data_offset = 0;
2726         else
2727             track->data_offset = mdat_size;
2728         if (!track->mdat_buf)
2729             continue;
2730         mdat_size += avio_tell(track->mdat_buf);
2731         if (first_track < 0)
2732             first_track = i;
2733     }
2734
2735     if (!mdat_size)
2736         return 0;
2737
2738     for (i = 0; i < mov->nb_streams; i++) {
2739         MOVTrack *track = &mov->tracks[i];
2740         int buf_size, write_moof = 1, moof_tracks = -1;
2741         uint8_t *buf;
2742         int64_t duration = 0;
2743
2744         if (track->entry)
2745             duration = track->start_dts + track->track_duration -
2746                        track->cluster[0].dts;
2747         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
2748             if (!track->mdat_buf)
2749                 continue;
2750             mdat_size = avio_tell(track->mdat_buf);
2751             moof_tracks = i;
2752         } else {
2753             write_moof = i == first_track;
2754         }
2755
2756         if (write_moof) {
2757             MOVFragmentInfo *info;
2758             avio_flush(s->pb);
2759             track->nb_frag_info++;
2760             if (track->nb_frag_info >= track->frag_info_capacity) {
2761                 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
2762                 if (av_reallocp_array(&track->frag_info,
2763                                       new_capacity,
2764                                       sizeof(*track->frag_info)))
2765                     return AVERROR(ENOMEM);
2766                 track->frag_info_capacity = new_capacity;
2767             }
2768             info = &track->frag_info[track->nb_frag_info - 1];
2769             info->offset   = avio_tell(s->pb);
2770             info->time     = mov->tracks[i].frag_start;
2771             info->duration = duration;
2772             mov_write_tfrf_tags(s->pb, mov, track);
2773
2774             mov_write_moof_tag(s->pb, mov, moof_tracks);
2775             info->tfrf_offset = track->tfrf_offset;
2776             mov->fragments++;
2777
2778             avio_wb32(s->pb, mdat_size + 8);
2779             ffio_wfourcc(s->pb, "mdat");
2780         }
2781
2782         if (track->entry)
2783             track->frag_start += duration;
2784         track->entry = 0;
2785         if (!track->mdat_buf)
2786             continue;
2787         buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
2788         track->mdat_buf = NULL;
2789
2790         avio_write(s->pb, buf, buf_size);
2791         av_free(buf);
2792     }
2793
2794     mov->mdat_size = 0;
2795
2796     avio_flush(s->pb);
2797     return 0;
2798 }
2799
2800 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
2801 {
2802     MOVMuxContext *mov = s->priv_data;
2803     AVIOContext *pb = s->pb;
2804     MOVTrack *trk = &mov->tracks[pkt->stream_index];
2805     AVCodecContext *enc = trk->enc;
2806     unsigned int samples_in_chunk = 0;
2807     int size = pkt->size;
2808     uint8_t *reformatted_data = NULL;
2809
2810     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
2811         int ret;
2812         if (mov->fragments > 0) {
2813             if (!trk->mdat_buf) {
2814                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
2815                     return ret;
2816             }
2817             pb = trk->mdat_buf;
2818         } else {
2819             if (!mov->mdat_buf) {
2820                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
2821                     return ret;
2822             }
2823             pb = mov->mdat_buf;
2824         }
2825     }
2826
2827     if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
2828         /* We must find out how many AMR blocks there are in one packet */
2829         static uint16_t packed_size[16] =
2830             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
2831         int len = 0;
2832
2833         while (len < size && samples_in_chunk < 100) {
2834             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
2835             samples_in_chunk++;
2836         }
2837         if (samples_in_chunk > 1) {
2838             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
2839             return -1;
2840         }
2841     } else if (trk->sample_size)
2842         samples_in_chunk = size / trk->sample_size;
2843     else
2844         samples_in_chunk = 1;
2845
2846     /* copy extradata if it exists */
2847     if (trk->vos_len == 0 && enc->extradata_size > 0) {
2848         trk->vos_len  = enc->extradata_size;
2849         trk->vos_data = av_malloc(trk->vos_len);
2850         memcpy(trk->vos_data, enc->extradata, trk->vos_len);
2851     }
2852
2853     if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {
2854         /* from x264 or from bytestream h264 */
2855         /* nal reformating needed */
2856         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
2857             ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
2858                                        &size);
2859             avio_write(pb, reformatted_data, size);
2860         } else {
2861             size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
2862         }
2863     } else {
2864         avio_write(pb, pkt->data, size);
2865     }
2866
2867     if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
2868          enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
2869         /* copy frame to create needed atoms */
2870         trk->vos_len  = size;
2871         trk->vos_data = av_malloc(size);
2872         if (!trk->vos_data)
2873             return AVERROR(ENOMEM);
2874         memcpy(trk->vos_data, pkt->data, size);
2875     }
2876
2877     if (trk->entry >= trk->cluster_capacity) {
2878         unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
2879         if (av_reallocp_array(&trk->cluster, new_capacity,
2880                               sizeof(*trk->cluster)))
2881             return AVERROR(ENOMEM);
2882         trk->cluster_capacity = new_capacity;
2883     }
2884
2885     trk->cluster[trk->entry].pos              = avio_tell(pb) - size;
2886     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
2887     trk->cluster[trk->entry].size             = size;
2888     trk->cluster[trk->entry].entries          = samples_in_chunk;
2889     trk->cluster[trk->entry].dts              = pkt->dts;
2890     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
2891         /* First packet of a new fragment. We already wrote the duration
2892          * of the last packet of the previous fragment based on track_duration,
2893          * which might not exactly match our dts. Therefore adjust the dts
2894          * of this packet to be what the previous packets duration implies. */
2895         trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
2896     }
2897     if (trk->start_dts == AV_NOPTS_VALUE)
2898         trk->start_dts = pkt->dts;
2899     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
2900
2901     if (pkt->pts == AV_NOPTS_VALUE) {
2902         av_log(s, AV_LOG_WARNING, "pts has no value\n");
2903         pkt->pts = pkt->dts;
2904     }
2905     if (pkt->dts != pkt->pts)
2906         trk->flags |= MOV_TRACK_CTTS;
2907     trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;
2908     trk->cluster[trk->entry].flags = 0;
2909     if (enc->codec_id == AV_CODEC_ID_VC1) {
2910         mov_parse_vc1_frame(pkt, trk, mov->fragments);
2911     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
2912         if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
2913             trk->entry > 0) { // force sync sample for the first key frame
2914             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
2915             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
2916                 trk->flags |= MOV_TRACK_STPS;
2917         } else {
2918             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
2919         }
2920         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
2921             trk->has_keyframes++;
2922     }
2923     trk->entry++;
2924     trk->sample_count += samples_in_chunk;
2925     mov->mdat_size    += size;
2926
2927     avio_flush(pb);
2928
2929     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
2930         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
2931                                  reformatted_data, size);
2932     av_free(reformatted_data);
2933     return 0;
2934 }
2935
2936 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
2937 {
2938     if (!pkt) {
2939         mov_flush_fragment(s);
2940         return 1;
2941     } else {
2942         MOVMuxContext *mov = s->priv_data;
2943         MOVTrack *trk = &mov->tracks[pkt->stream_index];
2944         AVCodecContext *enc = trk->enc;
2945         int64_t frag_duration = 0;
2946         int size = pkt->size;
2947
2948         if (!pkt->size)
2949             return 0;             /* Discard 0 sized packets */
2950
2951         if (trk->entry)
2952             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
2953                                          s->streams[pkt->stream_index]->time_base,
2954                                          AV_TIME_BASE_Q);
2955         if ((mov->max_fragment_duration &&
2956              frag_duration >= mov->max_fragment_duration) ||
2957              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
2958              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
2959               enc->codec_type == AVMEDIA_TYPE_VIDEO &&
2960               trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
2961             if (frag_duration >= mov->min_fragment_duration)
2962                 mov_flush_fragment(s);
2963         }
2964
2965         return ff_mov_write_packet(s, pkt);
2966     }
2967 }
2968
2969 // QuickTime chapters involve an additional text track with the chapter names
2970 // as samples, and a tref pointing from the other tracks to the chapter one.
2971 static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
2972 {
2973     MOVMuxContext *mov = s->priv_data;
2974     MOVTrack *track = &mov->tracks[tracknum];
2975     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
2976     int i, len;
2977
2978     track->mode = mov->mode;
2979     track->tag = MKTAG('t','e','x','t');
2980     track->timescale = MOV_TIMESCALE;
2981     track->enc = avcodec_alloc_context3(NULL);
2982     track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
2983
2984     for (i = 0; i < s->nb_chapters; i++) {
2985         AVChapter *c = s->chapters[i];
2986         AVDictionaryEntry *t;
2987
2988         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
2989         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
2990         pkt.duration = end - pkt.dts;
2991
2992         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2993             len      = strlen(t->value);
2994             pkt.size = len + 2;
2995             pkt.data = av_malloc(pkt.size);
2996             AV_WB16(pkt.data, len);
2997             memcpy(pkt.data + 2, t->value, len);
2998             ff_mov_write_packet(s, &pkt);
2999             av_freep(&pkt.data);
3000         }
3001     }
3002 }
3003
3004 static int mov_write_header(AVFormatContext *s)
3005 {
3006     AVIOContext *pb = s->pb;
3007     MOVMuxContext *mov = s->priv_data;
3008     AVDictionaryEntry *t;
3009     int i, hint_track = 0;
3010
3011     /* Set the FRAGMENT flag if any of the fragmentation methods are
3012      * enabled. */
3013     if (mov->max_fragment_duration || mov->max_fragment_size ||
3014         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
3015                       FF_MOV_FLAG_FRAG_KEYFRAME |
3016                       FF_MOV_FLAG_FRAG_CUSTOM))
3017         mov->flags |= FF_MOV_FLAG_FRAGMENT;
3018
3019     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
3020      * is enabled, we don't support non-seekable output at all. */
3021     if (!s->pb->seekable &&
3022         ((!(mov->flags & FF_MOV_FLAG_FRAGMENT) &&
3023           !(s->oformat && !strcmp(s->oformat->name, "ismv")))
3024          || mov->ism_lookahead)) {
3025         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
3026         return -1;
3027     }
3028
3029     /* Default mode == MP4 */
3030     mov->mode = MODE_MP4;
3031
3032     if (s->oformat != NULL) {
3033         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
3034         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
3035         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
3036         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
3037         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
3038         else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
3039
3040         mov_write_ftyp_tag(pb,s);
3041         if (mov->mode == MODE_PSP) {
3042             if (s->nb_streams != 2) {
3043                 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3044                 return -1;
3045             }
3046             mov_write_uuidprof_tag(pb, s);
3047         }
3048     }
3049
3050     mov->nb_streams = s->nb_streams;
3051     if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
3052         mov->chapter_track = mov->nb_streams++;
3053
3054     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
3055         /* Add hint tracks for each audio and video stream */
3056         hint_track = mov->nb_streams;
3057         for (i = 0; i < s->nb_streams; i++) {
3058             AVStream *st = s->streams[i];
3059             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3060                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3061                 mov->nb_streams++;
3062             }
3063         }
3064     }
3065
3066     mov->tracks = av_mallocz(mov->nb_streams * sizeof(*mov->tracks));
3067     if (!mov->tracks)
3068         return AVERROR(ENOMEM);
3069
3070     for (i = 0; i < s->nb_streams; i++) {
3071         AVStream *st= s->streams[i];
3072         MOVTrack *track= &mov->tracks[i];
3073         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3074
3075         track->enc = st->codec;
3076         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
3077         if (track->language < 0)
3078             track->language = 0;
3079         track->mode = mov->mode;
3080         track->tag  = mov_find_codec_tag(s, track);
3081         if (!track->tag) {
3082             av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
3083                    "codec not currently supported in container\n", i);
3084             goto error;
3085         }
3086         /* If hinting of this track is enabled by a later hint track,
3087          * this is updated. */
3088         track->hint_track = -1;
3089         track->start_dts  = AV_NOPTS_VALUE;
3090         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3091             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
3092                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
3093                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
3094                 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
3095                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
3096                     goto error;
3097                 }
3098                 track->height = track->tag >> 24 == 'n' ? 486 : 576;
3099             }
3100             track->timescale = st->codec->time_base.den;
3101             if (track->mode == MODE_MOV && track->timescale > 100000)
3102                 av_log(s, AV_LOG_WARNING,
3103                        "WARNING codec timebase is very high. If duration is too long,\n"
3104                        "file may not be playable by quicktime. Specify a shorter timebase\n"
3105                        "or choose different container.\n");
3106         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3107             track->timescale = st->codec->sample_rate;
3108             /* set sample_size for PCM and ADPCM */
3109             if (av_get_bits_per_sample(st->codec->codec_id) ||
3110                 st->codec->codec_id == AV_CODEC_ID_ILBC) {
3111                 if (!st->codec->block_align) {
3112                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set\n", i);
3113                     goto error;
3114                 }
3115                 track->sample_size = st->codec->block_align;
3116             }
3117             /* set audio_vbr for compressed audio */
3118             if (av_get_bits_per_sample(st->codec->codec_id) < 8) {
3119                 track->audio_vbr = 1;
3120             }
3121             if (track->mode != MODE_MOV &&
3122                 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
3123                 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
3124                        i, track->enc->sample_rate);
3125                 goto error;
3126             }
3127         } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3128             track->timescale = st->codec->time_base.den;
3129         }
3130         if (!track->height)
3131             track->height = st->codec->height;
3132         /* The ism specific timescale isn't mandatory, but is assumed by
3133          * some tools, such as mp4split. */
3134         if (mov->mode == MODE_ISM)
3135             track->timescale = 10000000;
3136
3137         avpriv_set_pts_info(st, 64, 1, track->timescale);
3138
3139         /* copy extradata if it exists */
3140         if (st->codec->extradata_size) {
3141             track->vos_len  = st->codec->extradata_size;
3142             track->vos_data = av_malloc(track->vos_len);
3143             memcpy(track->vos_data, st->codec->extradata, track->vos_len);
3144         }
3145     }
3146
3147     if (mov->mode == MODE_ISM) {
3148         /* If no fragmentation options have been set, set a default. */
3149         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
3150                             FF_MOV_FLAG_FRAG_CUSTOM)) &&
3151             !mov->max_fragment_duration && !mov->max_fragment_size)
3152             mov->max_fragment_duration = 5000000;
3153         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
3154                       FF_MOV_FLAG_FRAGMENT;
3155     }
3156
3157     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3158         mov_write_mdat_tag(pb, mov);
3159
3160     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
3161         mov->time = ff_iso8601_to_unix_time(t->value);
3162     if (mov->time)
3163         mov->time += 0x7C25B080; // 1970 based -> 1904 based
3164
3165     if (mov->chapter_track)
3166         mov_create_chapter_track(s, mov->chapter_track);
3167
3168     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
3169         /* Initialize the hint tracks for each audio and video stream */
3170         for (i = 0; i < s->nb_streams; i++) {
3171             AVStream *st = s->streams[i];
3172             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3173                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3174                 ff_mov_init_hinting(s, hint_track, i);
3175                 hint_track++;
3176             }
3177         }
3178     }
3179
3180     avio_flush(pb);
3181
3182     if (mov->flags & FF_MOV_FLAG_ISML)
3183         mov_write_isml_manifest(pb, mov);
3184
3185     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3186         mov_write_moov_tag(pb, mov, s);
3187         mov->fragments++;
3188     }
3189
3190     return 0;
3191  error:
3192     av_freep(&mov->tracks);
3193     return -1;
3194 }
3195
3196 static int mov_write_trailer(AVFormatContext *s)
3197 {
3198     MOVMuxContext *mov = s->priv_data;
3199     AVIOContext *pb = s->pb;
3200     int res = 0;
3201     int i;
3202
3203     int64_t moov_pos = avio_tell(pb);
3204
3205     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
3206         /* Write size of mdat tag */
3207         if (mov->mdat_size + 8 <= UINT32_MAX) {
3208             avio_seek(pb, mov->mdat_pos, SEEK_SET);
3209             avio_wb32(pb, mov->mdat_size + 8);
3210         } else {
3211             /* overwrite 'wide' placeholder atom */
3212             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
3213             /* special value: real atom size will be 64 bit value after
3214              * tag field */
3215             avio_wb32(pb, 1);
3216             ffio_wfourcc(pb, "mdat");
3217             avio_wb64(pb, mov->mdat_size + 16);
3218         }
3219         avio_seek(pb, moov_pos, SEEK_SET);
3220
3221         mov_write_moov_tag(pb, mov, s);
3222     } else {
3223         mov_flush_fragment(s);
3224         mov_write_mfra_tag(pb, mov);
3225     }
3226
3227     if (mov->chapter_track)
3228         av_freep(&mov->tracks[mov->chapter_track].enc);
3229
3230     for (i = 0; i < mov->nb_streams; i++) {
3231         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
3232             ff_mov_close_hinting(&mov->tracks[i]);
3233         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
3234             mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
3235             int64_t off = avio_tell(pb);
3236             uint8_t buf[7];
3237             if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
3238                 avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
3239                 avio_write(pb, buf, 7);
3240                 avio_seek(pb, off, SEEK_SET);
3241             }
3242         }
3243         av_freep(&mov->tracks[i].cluster);
3244         av_freep(&mov->tracks[i].frag_info);
3245
3246         if (mov->tracks[i].vos_len)
3247             av_free(mov->tracks[i].vos_data);
3248     }
3249
3250     av_freep(&mov->tracks);
3251
3252     return res;
3253 }
3254
3255 #if CONFIG_MOV_MUXER
3256 MOV_CLASS(mov)
3257 AVOutputFormat ff_mov_muxer = {
3258     .name              = "mov",
3259     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3260     .extensions        = "mov",
3261     .priv_data_size    = sizeof(MOVMuxContext),
3262     .audio_codec       = AV_CODEC_ID_AAC,
3263     .video_codec       = CONFIG_LIBX264_ENCODER ?
3264                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
3265     .write_header      = mov_write_header,
3266     .write_packet      = mov_write_packet,
3267     .write_trailer     = mov_write_trailer,
3268     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
3269     .codec_tag         = (const AVCodecTag* const []){
3270         ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
3271     },
3272     .priv_class        = &mov_muxer_class,
3273 };
3274 #endif
3275 #if CONFIG_TGP_MUXER
3276 MOV_CLASS(tgp)
3277 AVOutputFormat ff_tgp_muxer = {
3278     .name              = "3gp",
3279     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
3280     .extensions        = "3gp",
3281     .priv_data_size    = sizeof(MOVMuxContext),
3282     .audio_codec       = AV_CODEC_ID_AMR_NB,
3283     .video_codec       = AV_CODEC_ID_H263,
3284     .write_header      = mov_write_header,
3285     .write_packet      = mov_write_packet,
3286     .write_trailer     = mov_write_trailer,
3287     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
3288     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
3289     .priv_class        = &tgp_muxer_class,
3290 };
3291 #endif
3292 #if CONFIG_MP4_MUXER
3293 MOV_CLASS(mp4)
3294 AVOutputFormat ff_mp4_muxer = {
3295     .name              = "mp4",
3296     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
3297     .mime_type         = "application/mp4",
3298     .extensions        = "mp4",
3299     .priv_data_size    = sizeof(MOVMuxContext),
3300     .audio_codec       = AV_CODEC_ID_AAC,
3301     .video_codec       = CONFIG_LIBX264_ENCODER ?
3302                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
3303     .write_header      = mov_write_header,
3304     .write_packet      = mov_write_packet,
3305     .write_trailer     = mov_write_trailer,
3306     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
3307     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
3308     .priv_class        = &mp4_muxer_class,
3309 };
3310 #endif
3311 #if CONFIG_PSP_MUXER
3312 MOV_CLASS(psp)
3313 AVOutputFormat ff_psp_muxer = {
3314     .name              = "psp",
3315     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
3316     .extensions        = "mp4,psp",
3317     .priv_data_size    = sizeof(MOVMuxContext),
3318     .audio_codec       = AV_CODEC_ID_AAC,
3319     .video_codec       = CONFIG_LIBX264_ENCODER ?
3320                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
3321     .write_header      = mov_write_header,
3322     .write_packet      = mov_write_packet,
3323     .write_trailer     = mov_write_trailer,
3324     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
3325     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
3326     .priv_class        = &psp_muxer_class,
3327 };
3328 #endif
3329 #if CONFIG_TG2_MUXER
3330 MOV_CLASS(tg2)
3331 AVOutputFormat ff_tg2_muxer = {
3332     .name              = "3g2",
3333     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
3334     .extensions        = "3g2",
3335     .priv_data_size    = sizeof(MOVMuxContext),
3336     .audio_codec       = AV_CODEC_ID_AMR_NB,
3337     .video_codec       = AV_CODEC_ID_H263,
3338     .write_header      = mov_write_header,
3339     .write_packet      = mov_write_packet,
3340     .write_trailer     = mov_write_trailer,
3341     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
3342     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
3343     .priv_class        = &tg2_muxer_class,
3344 };
3345 #endif
3346 #if CONFIG_IPOD_MUXER
3347 MOV_CLASS(ipod)
3348 AVOutputFormat ff_ipod_muxer = {
3349     .name              = "ipod",
3350     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
3351     .mime_type         = "application/mp4",
3352     .extensions        = "m4v,m4a",
3353     .priv_data_size    = sizeof(MOVMuxContext),
3354     .audio_codec       = AV_CODEC_ID_AAC,
3355     .video_codec       = AV_CODEC_ID_H264,
3356     .write_header      = mov_write_header,
3357     .write_packet      = mov_write_packet,
3358     .write_trailer     = mov_write_trailer,
3359     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
3360     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
3361     .priv_class        = &ipod_muxer_class,
3362 };
3363 #endif
3364 #if CONFIG_ISMV_MUXER
3365 MOV_CLASS(ismv)
3366 AVOutputFormat ff_ismv_muxer = {
3367     .name              = "ismv",
3368     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
3369     .mime_type         = "application/mp4",
3370     .extensions        = "ismv,isma",
3371     .priv_data_size    = sizeof(MOVMuxContext),
3372     .audio_codec       = AV_CODEC_ID_AAC,
3373     .video_codec       = AV_CODEC_ID_H264,
3374     .write_header      = mov_write_header,
3375     .write_packet      = mov_write_packet,
3376     .write_trailer     = mov_write_trailer,
3377     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
3378     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
3379     .priv_class        = &ismv_muxer_class,
3380 };
3381 #endif