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