]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
oggdec: simplify start time calculation code.
[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','2'),  0 },
863     { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
864     { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
865     { PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
866     { PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
867     { PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
868     { PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
869     { PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
870     { PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
871     { PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
872     { PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
873     { PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
874     { PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
875     { PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
876     { PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
877 };
878
879 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
880 {
881     int tag = track->enc->codec_tag;
882     int i;
883
884     for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
885         if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag && track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
886             tag = mov_pix_fmt_tags[i].tag;
887             track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
888             break;
889         }
890     }
891
892     return tag;
893 }
894
895 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
896 {
897     int tag = track->enc->codec_tag;
898
899     if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
900                  (track->enc->codec_id == CODEC_ID_DVVIDEO ||
901                   track->enc->codec_id == CODEC_ID_RAWVIDEO ||
902                   track->enc->codec_id == CODEC_ID_H263 ||
903                   av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
904         if (track->enc->codec_id == CODEC_ID_DVVIDEO)
905             tag = mov_get_dv_codec_tag(s, track);
906         else if (track->enc->codec_id == CODEC_ID_RAWVIDEO)
907             tag = mov_get_rawvideo_codec_tag(s, track);
908         else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
909             tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
910             if (!tag) { // if no mac fcc found, try with Microsoft tags
911                 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
912                 if (tag)
913                     av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
914                            "the file may be unplayable!\n");
915             }
916         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
917             tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
918             if (!tag) { // if no mac fcc found, try with Microsoft tags
919                 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
920                 if (ms_tag) {
921                     tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
922                     av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
923                            "the file may be unplayable!\n");
924                 }
925             }
926         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
927             tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
928     }
929
930     return tag;
931 }
932
933 static const AVCodecTag codec_3gp_tags[] = {
934     { CODEC_ID_H263,   MKTAG('s','2','6','3') },
935     { CODEC_ID_H264,   MKTAG('a','v','c','1') },
936     { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
937     { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
938     { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
939     { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
940     { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
941     { CODEC_ID_NONE, 0 },
942 };
943
944 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
945 {
946     int tag;
947
948     if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
949         tag = mp4_get_codec_tag(s, track);
950     else if (track->mode == MODE_ISM) {
951         tag = mp4_get_codec_tag(s, track);
952         if (!tag && track->enc->codec_id == CODEC_ID_WMAPRO)
953             tag = MKTAG('w', 'm', 'a', ' ');
954     } else if (track->mode == MODE_IPOD)
955         tag = ipod_get_codec_tag(s, track);
956     else if (track->mode & MODE_3GP)
957         tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
958     else
959         tag = mov_get_codec_tag(s, track);
960
961     return tag;
962 }
963
964 /** Write uuid atom.
965  * Needed to make file play in iPods running newest firmware
966  * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
967  */
968 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
969 {
970     avio_wb32(pb, 28);
971     ffio_wfourcc(pb, "uuid");
972     avio_wb32(pb, 0x6b6840f2);
973     avio_wb32(pb, 0x5f244fc5);
974     avio_wb32(pb, 0xba39a51b);
975     avio_wb32(pb, 0xcf0323f3);
976     avio_wb32(pb, 0x0);
977     return 28;
978 }
979
980 static const uint16_t fiel_data[] = {
981     0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
982 };
983
984 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
985 {
986     unsigned mov_field_order = 0;
987     if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
988         mov_field_order = fiel_data[track->enc->field_order];
989     else
990         return 0;
991     avio_wb32(pb, 10);
992     ffio_wfourcc(pb, "fiel");
993     avio_wb16(pb, mov_field_order);
994     return 10;
995 }
996
997 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
998 {
999     int64_t pos = avio_tell(pb);
1000     avio_wb32(pb, 0);    /* size */
1001     avio_wl32(pb, track->tag); // store it byteswapped
1002     avio_wb32(pb, 0);    /* Reserved */
1003     avio_wb16(pb, 0);    /* Reserved */
1004     avio_wb16(pb, 1);    /* Data-reference index */
1005
1006     if (track->enc->extradata_size)
1007         avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1008
1009     return update_size(pb, pos);
1010 }
1011
1012 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1013 {
1014     AVRational sar;
1015     av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
1016               track->enc->sample_aspect_ratio.den, INT_MAX);
1017
1018     avio_wb32(pb, 16);
1019     ffio_wfourcc(pb, "pasp");
1020     avio_wb32(pb, sar.num);
1021     avio_wb32(pb, sar.den);
1022     return 16;
1023 }
1024
1025 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1026 {
1027     int64_t pos = avio_tell(pb);
1028     char compressor_name[32] = { 0 };
1029
1030     avio_wb32(pb, 0); /* size */
1031     avio_wl32(pb, track->tag); // store it byteswapped
1032     avio_wb32(pb, 0); /* Reserved */
1033     avio_wb16(pb, 0); /* Reserved */
1034     avio_wb16(pb, 1); /* Data-reference index */
1035
1036     avio_wb16(pb, 0); /* Codec stream version */
1037     avio_wb16(pb, 0); /* Codec stream revision (=0) */
1038     if (track->mode == MODE_MOV) {
1039         ffio_wfourcc(pb, "FFMP"); /* Vendor */
1040         if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
1041             avio_wb32(pb, 0); /* Temporal Quality */
1042             avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1043         } else {
1044             avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1045             avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1046         }
1047     } else {
1048         avio_wb32(pb, 0); /* Reserved */
1049         avio_wb32(pb, 0); /* Reserved */
1050         avio_wb32(pb, 0); /* Reserved */
1051     }
1052     avio_wb16(pb, track->enc->width); /* Video width */
1053     avio_wb16(pb, track->height); /* Video height */
1054     avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1055     avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1056     avio_wb32(pb, 0); /* Data size (= 0) */
1057     avio_wb16(pb, 1); /* Frame count (= 1) */
1058
1059     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1060     if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
1061         av_strlcpy(compressor_name,track->enc->codec->name,32);
1062     avio_w8(pb, strlen(compressor_name));
1063     avio_write(pb, compressor_name, 31);
1064
1065     if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1066         avio_wb16(pb, track->enc->bits_per_coded_sample);
1067     else
1068         avio_wb16(pb, 0x18); /* Reserved */
1069     avio_wb16(pb, 0xffff); /* Reserved */
1070     if(track->tag == MKTAG('m','p','4','v'))
1071         mov_write_esds_tag(pb, track);
1072     else if(track->enc->codec_id == CODEC_ID_H263)
1073         mov_write_d263_tag(pb);
1074     else if(track->enc->codec_id == CODEC_ID_SVQ3)
1075         mov_write_svq3_tag(pb);
1076     else if(track->enc->codec_id == CODEC_ID_AVUI) {
1077         mov_write_extradata_tag(pb, track);
1078         avio_wb32(pb, 0);
1079     } else if(track->enc->codec_id == CODEC_ID_DNXHD)
1080         mov_write_avid_tag(pb, track);
1081     else if(track->enc->codec_id == CODEC_ID_H264) {
1082         mov_write_avcc_tag(pb, track);
1083         if(track->mode == MODE_IPOD)
1084             mov_write_uuid_tag_ipod(pb);
1085     } else if (track->enc->field_order != AV_FIELD_UNKNOWN)
1086         mov_write_fiel_tag(pb, track);
1087     else if (track->enc->codec_id == CODEC_ID_VC1 && track->vos_len > 0)
1088         mov_write_dvc1_tag(pb, track);
1089     else if (track->vos_len > 0)
1090         mov_write_glbl_tag(pb, track);
1091
1092     if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1093         track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1094         mov_write_pasp_tag(pb, track);
1095     }
1096
1097     return update_size(pb, pos);
1098 }
1099
1100 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1101 {
1102     int64_t pos = avio_tell(pb);
1103     int frame_duration = track->enc->time_base.num;
1104     int nb_frames = (track->timescale + frame_duration/2) / frame_duration;
1105
1106     avio_wb32(pb, 0); /* size */
1107     ffio_wfourcc(pb, "tmcd");               /* Data format */
1108     avio_wb32(pb, 0);                       /* Reserved */
1109     avio_wb32(pb, 1);                       /* Data reference index */
1110     avio_wb32(pb, 0);                       /* Flags */
1111     avio_wb32(pb, track->timecode_flags);   /* Flags (timecode) */
1112     avio_wb32(pb, track->timescale);        /* Timescale */
1113     avio_wb32(pb, frame_duration);          /* Frame duration */
1114     avio_w8(pb, nb_frames);                 /* Number of frames */
1115     avio_wb24(pb, 0);                       /* Reserved */
1116     /* TODO: source reference string */
1117     return update_size(pb, pos);
1118 }
1119
1120 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1121 {
1122     int64_t pos = avio_tell(pb);
1123     avio_wb32(pb, 0); /* size */
1124     ffio_wfourcc(pb, "rtp ");
1125     avio_wb32(pb, 0); /* Reserved */
1126     avio_wb16(pb, 0); /* Reserved */
1127     avio_wb16(pb, 1); /* Data-reference index */
1128
1129     avio_wb16(pb, 1); /* Hint track version */
1130     avio_wb16(pb, 1); /* Highest compatible version */
1131     avio_wb32(pb, track->max_packet_size); /* Max packet size */
1132
1133     avio_wb32(pb, 12); /* size */
1134     ffio_wfourcc(pb, "tims");
1135     avio_wb32(pb, track->timescale);
1136
1137     return update_size(pb, pos);
1138 }
1139
1140 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
1141 {
1142     int64_t pos = avio_tell(pb);
1143     avio_wb32(pb, 0); /* size */
1144     ffio_wfourcc(pb, "stsd");
1145     avio_wb32(pb, 0); /* version & flags */
1146     avio_wb32(pb, 1); /* entry count */
1147     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1148         mov_write_video_tag(pb, track);
1149     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1150         mov_write_audio_tag(pb, track);
1151     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1152         mov_write_subtitle_tag(pb, track);
1153     else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1154         mov_write_rtp_tag(pb, track);
1155     else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1156         mov_write_tmcd_tag(pb, track);
1157     return update_size(pb, pos);
1158 }
1159
1160 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1161 {
1162     MOVStts *ctts_entries;
1163     uint32_t entries = 0;
1164     uint32_t atom_size;
1165     int i;
1166
1167     ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
1168     ctts_entries[0].count = 1;
1169     ctts_entries[0].duration = track->cluster[0].cts;
1170     for (i=1; i<track->entry; i++) {
1171         if (track->cluster[i].cts == ctts_entries[entries].duration) {
1172             ctts_entries[entries].count++; /* compress */
1173         } else {
1174             entries++;
1175             ctts_entries[entries].duration = track->cluster[i].cts;
1176             ctts_entries[entries].count = 1;
1177         }
1178     }
1179     entries++; /* last one */
1180     atom_size = 16 + (entries * 8);
1181     avio_wb32(pb, atom_size); /* size */
1182     ffio_wfourcc(pb, "ctts");
1183     avio_wb32(pb, 0); /* version & flags */
1184     avio_wb32(pb, entries); /* entry count */
1185     for (i=0; i<entries; i++) {
1186         avio_wb32(pb, ctts_entries[i].count);
1187         avio_wb32(pb, ctts_entries[i].duration);
1188     }
1189     av_free(ctts_entries);
1190     return atom_size;
1191 }
1192
1193 /* Time to sample atom */
1194 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1195 {
1196     MOVStts *stts_entries;
1197     uint32_t entries = -1;
1198     uint32_t atom_size;
1199     int i;
1200
1201     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1202         stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1203         stts_entries[0].count = track->sample_count;
1204         stts_entries[0].duration = 1;
1205         entries = 1;
1206     } else {
1207         stts_entries = track->entry ?
1208                        av_malloc(track->entry * sizeof(*stts_entries)) : /* worst case */
1209                        NULL;
1210         for (i=0; i<track->entry; i++) {
1211             int duration = get_cluster_duration(track, i);
1212             if (i && duration == stts_entries[entries].duration) {
1213                 stts_entries[entries].count++; /* compress */
1214             } else {
1215                 entries++;
1216                 stts_entries[entries].duration = duration;
1217                 stts_entries[entries].count = 1;
1218             }
1219         }
1220         entries++; /* last one */
1221     }
1222     atom_size = 16 + (entries * 8);
1223     avio_wb32(pb, atom_size); /* size */
1224     ffio_wfourcc(pb, "stts");
1225     avio_wb32(pb, 0); /* version & flags */
1226     avio_wb32(pb, entries); /* entry count */
1227     for (i=0; i<entries; i++) {
1228         avio_wb32(pb, stts_entries[i].count);
1229         avio_wb32(pb, stts_entries[i].duration);
1230     }
1231     av_free(stts_entries);
1232     return atom_size;
1233 }
1234
1235 static int mov_write_dref_tag(AVIOContext *pb)
1236 {
1237     avio_wb32(pb, 28); /* size */
1238     ffio_wfourcc(pb, "dref");
1239     avio_wb32(pb, 0); /* version & flags */
1240     avio_wb32(pb, 1); /* entry count */
1241
1242     avio_wb32(pb, 0xc); /* size */
1243     //FIXME add the alis and rsrc atom
1244     ffio_wfourcc(pb, "url ");
1245     avio_wb32(pb, 1); /* version & flags */
1246
1247     return 28;
1248 }
1249
1250 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1251 {
1252     int64_t pos = avio_tell(pb);
1253     avio_wb32(pb, 0); /* size */
1254     ffio_wfourcc(pb, "stbl");
1255     mov_write_stsd_tag(pb, track);
1256     mov_write_stts_tag(pb, track);
1257     if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1258          track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1259         track->has_keyframes && track->has_keyframes < track->entry)
1260         mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1261     if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1262         mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1263     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1264         track->flags & MOV_TRACK_CTTS)
1265         mov_write_ctts_tag(pb, track);
1266     mov_write_stsc_tag(pb, track);
1267     mov_write_stsz_tag(pb, track);
1268     mov_write_stco_tag(pb, track);
1269     return update_size(pb, pos);
1270 }
1271
1272 static int mov_write_dinf_tag(AVIOContext *pb)
1273 {
1274     int64_t pos = avio_tell(pb);
1275     avio_wb32(pb, 0); /* size */
1276     ffio_wfourcc(pb, "dinf");
1277     mov_write_dref_tag(pb);
1278     return update_size(pb, pos);
1279 }
1280
1281 static int mov_write_nmhd_tag(AVIOContext *pb)
1282 {
1283     avio_wb32(pb, 12);
1284     ffio_wfourcc(pb, "nmhd");
1285     avio_wb32(pb, 0);
1286     return 12;
1287 }
1288
1289 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
1290 {
1291     int64_t pos = avio_tell(pb);
1292     const char *font = "Lucida Grande";
1293     avio_wb32(pb, 0);                   /* size */
1294     ffio_wfourcc(pb, "tcmi");           /* timecode media information atom */
1295     avio_wb32(pb, 0);                   /* version & flags */
1296     avio_wb16(pb, 0);                   /* text font */
1297     avio_wb16(pb, 0);                   /* text face */
1298     avio_wb16(pb, 12);                  /* text size */
1299     avio_wb16(pb, 0);                   /* (unknown, not in the QT specs...) */
1300     avio_wb16(pb, 0x0000);              /* text color (red) */
1301     avio_wb16(pb, 0x0000);              /* text color (green) */
1302     avio_wb16(pb, 0x0000);              /* text color (blue) */
1303     avio_wb16(pb, 0xffff);              /* background color (red) */
1304     avio_wb16(pb, 0xffff);              /* background color (green) */
1305     avio_wb16(pb, 0xffff);              /* background color (blue) */
1306     avio_w8(pb, strlen(font));          /* font len (part of the pascal string) */
1307     avio_write(pb, font, strlen(font)); /* font name */
1308     return update_size(pb, pos);
1309 }
1310
1311 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
1312 {
1313     int64_t pos = avio_tell(pb);
1314     avio_wb32(pb, 0);      /* size */
1315     ffio_wfourcc(pb, "gmhd");
1316     avio_wb32(pb, 0x18);   /* gmin size */
1317     ffio_wfourcc(pb, "gmin");/* generic media info */
1318     avio_wb32(pb, 0);      /* version & flags */
1319     avio_wb16(pb, 0x40);   /* graphics mode = */
1320     avio_wb16(pb, 0x8000); /* opColor (r?) */
1321     avio_wb16(pb, 0x8000); /* opColor (g?) */
1322     avio_wb16(pb, 0x8000); /* opColor (b?) */
1323     avio_wb16(pb, 0);      /* balance */
1324     avio_wb16(pb, 0);      /* reserved */
1325
1326     /*
1327      * This special text atom is required for
1328      * Apple Quicktime chapters. The contents
1329      * don't appear to be documented, so the
1330      * bytes are copied verbatim.
1331      */
1332     avio_wb32(pb, 0x2C);   /* size */
1333     ffio_wfourcc(pb, "text");
1334     avio_wb16(pb, 0x01);
1335     avio_wb32(pb, 0x00);
1336     avio_wb32(pb, 0x00);
1337     avio_wb32(pb, 0x00);
1338     avio_wb32(pb, 0x01);
1339     avio_wb32(pb, 0x00);
1340     avio_wb32(pb, 0x00);
1341     avio_wb32(pb, 0x00);
1342     avio_wb32(pb, 0x00004000);
1343     avio_wb16(pb, 0x0000);
1344
1345     if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1346         int64_t tmcd_pos = avio_tell(pb);
1347         avio_wb32(pb, 0); /* size */
1348         ffio_wfourcc(pb, "tmcd");
1349         mov_write_tcmi_tag(pb, track);
1350         update_size(pb, tmcd_pos);
1351     }
1352     return update_size(pb, pos);
1353 }
1354
1355 static int mov_write_smhd_tag(AVIOContext *pb)
1356 {
1357     avio_wb32(pb, 16); /* size */
1358     ffio_wfourcc(pb, "smhd");
1359     avio_wb32(pb, 0); /* version & flags */
1360     avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1361     avio_wb16(pb, 0); /* reserved */
1362     return 16;
1363 }
1364
1365 static int mov_write_vmhd_tag(AVIOContext *pb)
1366 {
1367     avio_wb32(pb, 0x14); /* size (always 0x14) */
1368     ffio_wfourcc(pb, "vmhd");
1369     avio_wb32(pb, 0x01); /* version & flags */
1370     avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1371     return 0x14;
1372 }
1373
1374 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1375 {
1376     const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1377     int64_t pos = avio_tell(pb);
1378
1379     if (!track) { /* no media --> data handler */
1380         hdlr = "dhlr";
1381         hdlr_type = "url ";
1382         descr = "DataHandler";
1383     } else {
1384         hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1385         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1386             hdlr_type = "vide";
1387             descr = "VideoHandler";
1388         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1389             hdlr_type = "soun";
1390             descr = "SoundHandler";
1391         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1392             if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
1393             else                                      hdlr_type = "text";
1394             descr = "SubtitleHandler";
1395         } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1396             hdlr_type = "tmcd";
1397             descr = "TimeCodeHandler";
1398         } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1399             hdlr_type = "hint";
1400             descr = "HintHandler";
1401         } else {
1402             hdlr = "dhlr";
1403             hdlr_type = "url ";
1404             descr = "DataHandler";
1405         }
1406     }
1407
1408     avio_wb32(pb, 0); /* size */
1409     ffio_wfourcc(pb, "hdlr");
1410     avio_wb32(pb, 0); /* Version & flags */
1411     avio_write(pb, hdlr, 4); /* handler */
1412     ffio_wfourcc(pb, hdlr_type); /* handler type */
1413     avio_wb32(pb ,0); /* reserved */
1414     avio_wb32(pb ,0); /* reserved */
1415     avio_wb32(pb ,0); /* reserved */
1416     if (!track || track->mode == MODE_MOV)
1417         avio_w8(pb, strlen(descr)); /* pascal string */
1418     avio_write(pb, descr, strlen(descr)); /* handler description */
1419     if (track && track->mode != MODE_MOV)
1420         avio_w8(pb, 0); /* c string */
1421     return update_size(pb, pos);
1422 }
1423
1424 static int mov_write_hmhd_tag(AVIOContext *pb)
1425 {
1426     /* This atom must be present, but leaving the values at zero
1427      * seems harmless. */
1428     avio_wb32(pb, 28); /* size */
1429     ffio_wfourcc(pb, "hmhd");
1430     avio_wb32(pb, 0); /* version, flags */
1431     avio_wb16(pb, 0); /* maxPDUsize */
1432     avio_wb16(pb, 0); /* avgPDUsize */
1433     avio_wb32(pb, 0); /* maxbitrate */
1434     avio_wb32(pb, 0); /* avgbitrate */
1435     avio_wb32(pb, 0); /* reserved */
1436     return 28;
1437 }
1438
1439 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1440 {
1441     int64_t pos = avio_tell(pb);
1442     avio_wb32(pb, 0); /* size */
1443     ffio_wfourcc(pb, "minf");
1444     if(track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1445         mov_write_vmhd_tag(pb);
1446     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1447         mov_write_smhd_tag(pb);
1448     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1449         if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb, track);
1450         else                                      mov_write_nmhd_tag(pb);
1451     } else if (track->tag == MKTAG('t','m','c','d')) {
1452         mov_write_gmhd_tag(pb, track);
1453     } else if (track->tag == MKTAG('r','t','p',' ')) {
1454         mov_write_hmhd_tag(pb);
1455     }
1456     if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1457         mov_write_hdlr_tag(pb, NULL);
1458     mov_write_dinf_tag(pb);
1459     mov_write_stbl_tag(pb, track);
1460     return update_size(pb, pos);
1461 }
1462
1463 static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1464 {
1465     int version = track->track_duration < INT32_MAX ? 0 : 1;
1466
1467     if (track->mode == MODE_ISM)
1468         version = 1;
1469
1470     (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1471     ffio_wfourcc(pb, "mdhd");
1472     avio_w8(pb, version);
1473     avio_wb24(pb, 0); /* flags */
1474     if (version == 1) {
1475         avio_wb64(pb, track->time);
1476         avio_wb64(pb, track->time);
1477     } else {
1478         avio_wb32(pb, track->time); /* creation time */
1479         avio_wb32(pb, track->time); /* modification time */
1480     }
1481     avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1482     if (!track->entry)
1483         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1484     else
1485         (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
1486     avio_wb16(pb, track->language); /* language */
1487     avio_wb16(pb, 0); /* reserved (quality) */
1488
1489     if(version!=0 && track->mode == MODE_MOV){
1490         av_log(NULL, AV_LOG_ERROR,
1491             "FATAL error, file duration too long for timebase, this file will not be\n"
1492             "playable with quicktime. Choose a different timebase or a different\n"
1493             "container format\n");
1494     }
1495
1496     return 32;
1497 }
1498
1499 static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1500 {
1501     int64_t pos = avio_tell(pb);
1502     avio_wb32(pb, 0); /* size */
1503     ffio_wfourcc(pb, "mdia");
1504     mov_write_mdhd_tag(pb, track);
1505     mov_write_hdlr_tag(pb, track);
1506     mov_write_minf_tag(pb, track);
1507     return update_size(pb, pos);
1508 }
1509
1510 /* transformation matrix
1511      |a  b  u|
1512      |c  d  v|
1513      |tx ty w| */
1514 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
1515                          int16_t d, int16_t tx, int16_t ty)
1516 {
1517     avio_wb32(pb, a << 16);  /* 16.16 format */
1518     avio_wb32(pb, b << 16);  /* 16.16 format */
1519     avio_wb32(pb, 0);        /* u in 2.30 format */
1520     avio_wb32(pb, c << 16);  /* 16.16 format */
1521     avio_wb32(pb, d << 16);  /* 16.16 format */
1522     avio_wb32(pb, 0);        /* v in 2.30 format */
1523     avio_wb32(pb, tx << 16); /* 16.16 format */
1524     avio_wb32(pb, ty << 16); /* 16.16 format */
1525     avio_wb32(pb, 1 << 30);  /* w in 2.30 format */
1526 }
1527
1528 static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1529 {
1530     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1531                                       track->timescale, AV_ROUND_UP);
1532     int version = duration < INT32_MAX ? 0 : 1;
1533     int rotation = 0;
1534
1535     if (track->mode == MODE_ISM)
1536         version = 1;
1537
1538     (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1539     ffio_wfourcc(pb, "tkhd");
1540     avio_w8(pb, version);
1541     avio_wb24(pb, 0xf); /* flags (track enabled) */
1542     if (version == 1) {
1543         avio_wb64(pb, track->time);
1544         avio_wb64(pb, track->time);
1545     } else {
1546         avio_wb32(pb, track->time); /* creation time */
1547         avio_wb32(pb, track->time); /* modification time */
1548     }
1549     avio_wb32(pb, track->track_id); /* track-id */
1550     avio_wb32(pb, 0); /* reserved */
1551     if (!track->entry)
1552         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1553     else
1554         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1555
1556     avio_wb32(pb, 0); /* reserved */
1557     avio_wb32(pb, 0); /* reserved */
1558     avio_wb16(pb, 0); /* layer */
1559     avio_wb16(pb, st ? st->codec->codec_type : 0); /* alternate group) */
1560     /* Volume, only for audio */
1561     if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1562         avio_wb16(pb, 0x0100);
1563     else
1564         avio_wb16(pb, 0);
1565     avio_wb16(pb, 0); /* reserved */
1566
1567     /* Matrix structure */
1568     if (st && st->metadata) {
1569         AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
1570         rotation = (rot && rot->value) ? atoi(rot->value) : 0;
1571     }
1572     if (rotation == 90) {
1573         write_matrix(pb,  0,  1, -1,  0, track->enc->height, 0);
1574     } else if (rotation == 180) {
1575         write_matrix(pb, -1,  0,  0, -1, track->enc->width, track->enc->height);
1576     } else if (rotation == 270) {
1577         write_matrix(pb,  0, -1,  1,  0, 0, track->enc->width);
1578     } else {
1579         write_matrix(pb,  1,  0,  0,  1, 0, 0);
1580     }
1581     /* Track width and height, for visual only */
1582     if(st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1583               track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1584         if(track->mode == MODE_MOV) {
1585             avio_wb32(pb, track->enc->width << 16);
1586             avio_wb32(pb, track->height << 16);
1587         } else {
1588             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1589             if(!sample_aspect_ratio || track->height != track->enc->height)
1590                 sample_aspect_ratio = 1;
1591             avio_wb32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1592             avio_wb32(pb, track->height*0x10000);
1593         }
1594     }
1595     else {
1596         avio_wb32(pb, 0);
1597         avio_wb32(pb, 0);
1598     }
1599     return 0x5c;
1600 }
1601
1602 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1603 {
1604     int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1605                                track->enc->sample_aspect_ratio.den);
1606
1607     int64_t pos = avio_tell(pb);
1608
1609     avio_wb32(pb, 0); /* size */
1610     ffio_wfourcc(pb, "tapt");
1611
1612     avio_wb32(pb, 20);
1613     ffio_wfourcc(pb, "clef");
1614     avio_wb32(pb, 0);
1615     avio_wb32(pb, width << 16);
1616     avio_wb32(pb, track->enc->height << 16);
1617
1618     avio_wb32(pb, 20);
1619     ffio_wfourcc(pb, "enof");
1620     avio_wb32(pb, 0);
1621     avio_wb32(pb, track->enc->width << 16);
1622     avio_wb32(pb, track->enc->height << 16);
1623
1624     return update_size(pb, pos);
1625 }
1626
1627 // This box seems important for the psp playback ... without it the movie seems to hang
1628 static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1629 {
1630     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1631                                       track->timescale, AV_ROUND_UP);
1632     int version = duration < INT32_MAX ? 0 : 1;
1633     int entry_size, entry_count, size;
1634     int64_t delay, start_ct = track->cluster[0].cts;
1635     delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
1636                            track->timescale, AV_ROUND_DOWN);
1637     version |= delay < INT32_MAX ? 0 : 1;
1638
1639     entry_size = (version == 1) ? 20 : 12;
1640     entry_count = 1 + (delay > 0);
1641     size = 24 + entry_count * entry_size;
1642
1643     /* write the atom data */
1644     avio_wb32(pb, size);
1645     ffio_wfourcc(pb, "edts");
1646     avio_wb32(pb, size - 8);
1647     ffio_wfourcc(pb, "elst");
1648     avio_w8(pb, version);
1649     avio_wb24(pb, 0); /* flags */
1650
1651     avio_wb32(pb, entry_count);
1652     if (delay > 0) { /* add an empty edit to delay presentation */
1653         if (version == 1) {
1654             avio_wb64(pb, delay);
1655             avio_wb64(pb, -1);
1656         } else {
1657             avio_wb32(pb, delay);
1658             avio_wb32(pb, -1);
1659         }
1660         avio_wb32(pb, 0x00010000);
1661     }
1662
1663     /* duration */
1664     if (version == 1) {
1665         avio_wb64(pb, duration);
1666         avio_wb64(pb, start_ct);
1667     } else {
1668         avio_wb32(pb, duration);
1669         avio_wb32(pb, start_ct);
1670     }
1671     avio_wb32(pb, 0x00010000);
1672     return size;
1673 }
1674
1675 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1676 {
1677     avio_wb32(pb, 20);   // size
1678     ffio_wfourcc(pb, "tref");
1679     avio_wb32(pb, 12);   // size (subatom)
1680     avio_wl32(pb, track->tref_tag);
1681     avio_wb32(pb, track->tref_id);
1682     return 20;
1683 }
1684
1685 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1686 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1687 {
1688     avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1689     ffio_wfourcc(pb, "uuid");
1690     ffio_wfourcc(pb, "USMT");
1691     avio_wb32(pb, 0x21d24fce);
1692     avio_wb32(pb, 0xbb88695c);
1693     avio_wb32(pb, 0xfac9c740);
1694     avio_wb32(pb, 0x1c);     // another size here!
1695     ffio_wfourcc(pb, "MTDT");
1696     avio_wb32(pb, 0x00010012);
1697     avio_wb32(pb, 0x0a);
1698     avio_wb32(pb, 0x55c40000);
1699     avio_wb32(pb, 0x1);
1700     avio_wb32(pb, 0x0);
1701     return 0x34;
1702 }
1703
1704 static int mov_write_udta_sdp(AVIOContext *pb, AVFormatContext *ctx, int index)
1705 {
1706     char buf[1000] = "";
1707     int len;
1708
1709     ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0]->codec, NULL, NULL, 0, 0, ctx);
1710     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", index);
1711     len = strlen(buf);
1712
1713     avio_wb32(pb, len + 24);
1714     ffio_wfourcc(pb, "udta");
1715     avio_wb32(pb, len + 16);
1716     ffio_wfourcc(pb, "hnti");
1717     avio_wb32(pb, len + 8);
1718     ffio_wfourcc(pb, "sdp ");
1719     avio_write(pb, buf, len);
1720     return len + 24;
1721 }
1722
1723 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
1724                               MOVTrack *track, AVStream *st)
1725 {
1726     int64_t pos = avio_tell(pb);
1727     avio_wb32(pb, 0); /* size */
1728     ffio_wfourcc(pb, "trak");
1729     mov_write_tkhd_tag(pb, track, st);
1730     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) // EDTS with fragments is tricky as we dont know the duration when its written
1731         mov_write_edts_tag(pb, track);  // PSP Movies and several other cases require edts box
1732     if (track->tref_tag)
1733         mov_write_tref_tag(pb, track);
1734     mov_write_mdia_tag(pb, track);
1735     if (track->mode == MODE_PSP)
1736         mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1737     if (track->tag == MKTAG('r','t','p',' '))
1738         mov_write_udta_sdp(pb, track->rtp_ctx, track->track_id);
1739     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO && track->mode == MODE_MOV) {
1740         double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1741         if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio)
1742             mov_write_tapt_tag(pb, track);
1743     };
1744     return update_size(pb, pos);
1745 }
1746
1747 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1748 {
1749     int i, has_audio = 0, has_video = 0;
1750     int64_t pos = avio_tell(pb);
1751     int audio_profile = mov->iods_audio_profile;
1752     int video_profile = mov->iods_video_profile;
1753     for (i = 0; i < mov->nb_streams; i++) {
1754         if(mov->tracks[i].entry > 0) {
1755             has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
1756             has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
1757         }
1758     }
1759     if (audio_profile < 0)
1760         audio_profile = 0xFF - has_audio;
1761     if (video_profile < 0)
1762         video_profile = 0xFF - has_video;
1763     avio_wb32(pb, 0x0); /* size */
1764     ffio_wfourcc(pb, "iods");
1765     avio_wb32(pb, 0);    /* version & flags */
1766     put_descr(pb, 0x10, 7);
1767     avio_wb16(pb, 0x004f);
1768     avio_w8(pb, 0xff);
1769     avio_w8(pb, 0xff);
1770     avio_w8(pb, audio_profile);
1771     avio_w8(pb, video_profile);
1772     avio_w8(pb, 0xff);
1773     return update_size(pb, pos);
1774 }
1775
1776 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
1777 {
1778     avio_wb32(pb, 0x20); /* size */
1779     ffio_wfourcc(pb, "trex");
1780     avio_wb32(pb, 0);   /* version & flags */
1781     avio_wb32(pb, track->track_id); /* track ID */
1782     avio_wb32(pb, 1);   /* default sample description index */
1783     avio_wb32(pb, 0);   /* default sample duration */
1784     avio_wb32(pb, 0);   /* default sample size */
1785     avio_wb32(pb, 0);   /* default sample flags */
1786     return 0;
1787 }
1788
1789 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
1790 {
1791     int64_t pos = avio_tell(pb);
1792     int i;
1793     avio_wb32(pb, 0x0); /* size */
1794     ffio_wfourcc(pb, "mvex");
1795     for (i = 0; i < mov->nb_streams; i++)
1796         mov_write_trex_tag(pb, &mov->tracks[i]);
1797     return update_size(pb, pos);
1798 }
1799
1800 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
1801 {
1802     int max_track_id = 1, i;
1803     int64_t max_track_len_temp, max_track_len = 0;
1804     int version;
1805
1806     for (i=0; i<mov->nb_streams; i++) {
1807         if(mov->tracks[i].entry > 0) {
1808             max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
1809                                                 MOV_TIMESCALE,
1810                                                 mov->tracks[i].timescale,
1811                                                 AV_ROUND_UP);
1812             if (max_track_len < max_track_len_temp)
1813                 max_track_len = max_track_len_temp;
1814             if (max_track_id < mov->tracks[i].track_id)
1815                 max_track_id = mov->tracks[i].track_id;
1816         }
1817     }
1818
1819     version = max_track_len < UINT32_MAX ? 0 : 1;
1820     (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
1821     ffio_wfourcc(pb, "mvhd");
1822     avio_w8(pb, version);
1823     avio_wb24(pb, 0); /* flags */
1824     if (version == 1) {
1825         avio_wb64(pb, mov->time);
1826         avio_wb64(pb, mov->time);
1827     } else {
1828         avio_wb32(pb, mov->time); /* creation time */
1829         avio_wb32(pb, mov->time); /* modification time */
1830     }
1831     avio_wb32(pb, MOV_TIMESCALE);
1832     (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
1833
1834     avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1835     avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1836     avio_wb16(pb, 0); /* reserved */
1837     avio_wb32(pb, 0); /* reserved */
1838     avio_wb32(pb, 0); /* reserved */
1839
1840     /* Matrix structure */
1841     write_matrix(pb, 1, 0, 0, 1, 0, 0);
1842
1843     avio_wb32(pb, 0); /* reserved (preview time) */
1844     avio_wb32(pb, 0); /* reserved (preview duration) */
1845     avio_wb32(pb, 0); /* reserved (poster time) */
1846     avio_wb32(pb, 0); /* reserved (selection time) */
1847     avio_wb32(pb, 0); /* reserved (selection duration) */
1848     avio_wb32(pb, 0); /* reserved (current time) */
1849     avio_wb32(pb, max_track_id + 1); /* Next track id */
1850     return 0x6c;
1851 }
1852
1853 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
1854                                      AVFormatContext *s)
1855 {
1856     avio_wb32(pb, 33); /* size */
1857     ffio_wfourcc(pb, "hdlr");
1858     avio_wb32(pb, 0);
1859     avio_wb32(pb, 0);
1860     ffio_wfourcc(pb, "mdir");
1861     ffio_wfourcc(pb, "appl");
1862     avio_wb32(pb, 0);
1863     avio_wb32(pb, 0);
1864     avio_w8(pb, 0);
1865     return 33;
1866 }
1867
1868 /* helper function to write a data tag with the specified string as data */
1869 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
1870 {
1871     if(long_style){
1872         int size = 16 + strlen(data);
1873         avio_wb32(pb, size); /* size */
1874         ffio_wfourcc(pb, "data");
1875         avio_wb32(pb, 1);
1876         avio_wb32(pb, 0);
1877         avio_write(pb, data, strlen(data));
1878         return size;
1879     }else{
1880         if (!lang)
1881             lang = ff_mov_iso639_to_lang("und", 1);
1882         avio_wb16(pb, strlen(data)); /* string length */
1883         avio_wb16(pb, lang);
1884         avio_write(pb, data, strlen(data));
1885         return strlen(data) + 4;
1886     }
1887 }
1888
1889 static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style){
1890     int size = 0;
1891     if (value && value[0]) {
1892         int64_t pos = avio_tell(pb);
1893         avio_wb32(pb, 0); /* size */
1894         ffio_wfourcc(pb, name);
1895         mov_write_string_data_tag(pb, value, lang, long_style);
1896         size = update_size(pb, pos);
1897     }
1898     return size;
1899 }
1900
1901 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
1902                                      const char *name, const char *tag,
1903                                      int long_style)
1904 {
1905     int l, lang = 0, len, len2;
1906     AVDictionaryEntry *t, *t2 = NULL;
1907     char tag2[16];
1908
1909     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
1910         return 0;
1911
1912     len = strlen(t->key);
1913     snprintf(tag2, sizeof(tag2), "%s-", tag);
1914     while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
1915         len2 = strlen(t2->key);
1916         if (len2 == len+4 && !strcmp(t->value, t2->value)
1917             && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 1)) >= 0) {
1918             lang = l;
1919             break;
1920         }
1921     }
1922     return mov_write_string_tag(pb, name, t->value, lang, long_style);
1923 }
1924
1925 /* iTunes track number */
1926 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
1927                               AVFormatContext *s)
1928 {
1929     AVDictionaryEntry *t = av_dict_get(s->metadata, "track", NULL, 0);
1930     int size = 0, track = t ? atoi(t->value) : 0;
1931     if (track) {
1932         avio_wb32(pb, 32); /* size */
1933         ffio_wfourcc(pb, "trkn");
1934             avio_wb32(pb, 24); /* size */
1935             ffio_wfourcc(pb, "data");
1936             avio_wb32(pb, 0);        // 8 bytes empty
1937             avio_wb32(pb, 0);
1938             avio_wb16(pb, 0);        // empty
1939             avio_wb16(pb, track);    // track number
1940             avio_wb16(pb, 0);        // total track number
1941             avio_wb16(pb, 0);        // empty
1942         size = 32;
1943     }
1944     return size;
1945 }
1946
1947 /* iTunes meta data list */
1948 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
1949                               AVFormatContext *s)
1950 {
1951     int64_t pos = avio_tell(pb);
1952     avio_wb32(pb, 0); /* size */
1953     ffio_wfourcc(pb, "ilst");
1954     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1955     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
1956     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
1957     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1958     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1959     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
1960     mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1961     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1962     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1963     mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1964     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
1965     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
1966     mov_write_string_metadata(s, pb, "desc",    "description",1);
1967     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
1968     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
1969     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
1970     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
1971     mov_write_trkn_tag(pb, mov, s);
1972     return update_size(pb, pos);
1973 }
1974
1975 /* iTunes meta data tag */
1976 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
1977                               AVFormatContext *s)
1978 {
1979     int size = 0;
1980     int64_t pos = avio_tell(pb);
1981     avio_wb32(pb, 0); /* size */
1982     ffio_wfourcc(pb, "meta");
1983     avio_wb32(pb, 0);
1984     mov_write_itunes_hdlr_tag(pb, mov, s);
1985     mov_write_ilst_tag(pb, mov, s);
1986     size = update_size(pb, pos);
1987     return size;
1988 }
1989
1990 static int utf8len(const uint8_t *b)
1991 {
1992     int len=0;
1993     int val;
1994     while(*b){
1995         GET_UTF8(val, *b++, return -1;)
1996         len++;
1997     }
1998     return len;
1999 }
2000
2001 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2002 {
2003     int val;
2004     while(*b){
2005         GET_UTF8(val, *b++, return -1;)
2006         avio_wb16(pb, val);
2007     }
2008     avio_wb16(pb, 0x00);
2009     return 0;
2010 }
2011
2012 static uint16_t language_code(const char *str)
2013 {
2014     return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
2015 }
2016
2017 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2018                                   const char *tag, const char *str)
2019 {
2020     int64_t pos = avio_tell(pb);
2021     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2022     if (!t || !utf8len(t->value))
2023         return 0;
2024     avio_wb32(pb, 0);   /* size */
2025     ffio_wfourcc(pb, tag); /* type */
2026     avio_wb32(pb, 0);   /* version + flags */
2027     if (!strcmp(tag, "yrrc"))
2028         avio_wb16(pb, atoi(t->value));
2029     else {
2030         avio_wb16(pb, language_code("eng")); /* language */
2031         avio_write(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
2032         if (!strcmp(tag, "albm") &&
2033             (t = av_dict_get(s->metadata, "track", NULL, 0)))
2034             avio_w8(pb, atoi(t->value));
2035     }
2036     return update_size(pb, pos);
2037 }
2038
2039 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2040 {
2041     int64_t pos = avio_tell(pb);
2042     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2043
2044     avio_wb32(pb, 0);            // size
2045     ffio_wfourcc(pb, "chpl");
2046     avio_wb32(pb, 0x01000000);   // version + flags
2047     avio_wb32(pb, 0);            // unknown
2048     avio_w8(pb, nb_chapters);
2049
2050     for (i = 0; i < nb_chapters; i++) {
2051         AVChapter *c = s->chapters[i];
2052         AVDictionaryEntry *t;
2053         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2054
2055         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2056             int len = FFMIN(strlen(t->value), 255);
2057             avio_w8(pb, len);
2058             avio_write(pb, t->value, len);
2059         } else
2060             avio_w8(pb, 0);
2061     }
2062     return update_size(pb, pos);
2063 }
2064
2065 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2066                               AVFormatContext *s)
2067 {
2068     AVIOContext *pb_buf;
2069     int i, ret, size;
2070     uint8_t *buf;
2071
2072     for (i = 0; i < s->nb_streams; i++)
2073         if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
2074             return 0;
2075         }
2076
2077     ret = avio_open_dyn_buf(&pb_buf);
2078     if(ret < 0)
2079         return ret;
2080
2081     if (mov->mode & MODE_3GP) {
2082         mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2083         mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2084         mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2085         mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2086         mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2087         mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2088         mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2089         mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2090     } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2091         mov_write_string_metadata(s, pb_buf, "\251ART", "artist"     , 0);
2092         mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
2093         mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
2094         mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
2095         mov_write_string_metadata(s, pb_buf, "\251day", "date"       , 0);
2096         mov_write_string_metadata(s, pb_buf, "\251swr", "encoder"    , 0);
2097         // currently ignored by mov.c
2098         mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
2099         // add support for libquicktime, this atom is also actually read by mov.c
2100         mov_write_string_metadata(s, pb_buf, "\251cmt", "comment"    , 0);
2101         mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
2102         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
2103     } else {
2104         /* iTunes meta data */
2105         mov_write_meta_tag(pb_buf, mov, s);
2106     }
2107
2108     if (s->nb_chapters)
2109         mov_write_chpl_tag(pb_buf, s);
2110
2111     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2112         avio_wb32(pb, size+8);
2113         ffio_wfourcc(pb, "udta");
2114         avio_write(pb, buf, size);
2115     }
2116     av_free(buf);
2117
2118     return 0;
2119 }
2120
2121 static void mov_write_psp_udta_tag(AVIOContext *pb,
2122                                   const char *str, const char *lang, int type)
2123 {
2124     int len = utf8len(str)+1;
2125     if(len<=0)
2126         return;
2127     avio_wb16(pb, len*2+10);            /* size */
2128     avio_wb32(pb, type);                /* type */
2129     avio_wb16(pb, language_code(lang)); /* language */
2130     avio_wb16(pb, 0x01);                /* ? */
2131     ascii_to_wc(pb, str);
2132 }
2133
2134 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2135 {
2136     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2137     int64_t pos, pos2;
2138
2139     if (title) {
2140         pos = avio_tell(pb);
2141         avio_wb32(pb, 0); /* size placeholder*/
2142         ffio_wfourcc(pb, "uuid");
2143         ffio_wfourcc(pb, "USMT");
2144         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2145         avio_wb32(pb, 0xbb88695c);
2146         avio_wb32(pb, 0xfac9c740);
2147
2148         pos2 = avio_tell(pb);
2149         avio_wb32(pb, 0); /* size placeholder*/
2150         ffio_wfourcc(pb, "MTDT");
2151         avio_wb16(pb, 4);
2152
2153         // ?
2154         avio_wb16(pb, 0x0C);                 /* size */
2155         avio_wb32(pb, 0x0B);                 /* type */
2156         avio_wb16(pb, language_code("und")); /* language */
2157         avio_wb16(pb, 0x0);                  /* ? */
2158         avio_wb16(pb, 0x021C);               /* data */
2159
2160         mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
2161         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
2162 //        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);
2163         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2164
2165         update_size(pb, pos2);
2166         return update_size(pb, pos);
2167     }
2168
2169     return 0;
2170 }
2171
2172 static void build_chunks(MOVTrack *trk)
2173 {
2174     int i;
2175     MOVIentry *chunk= &trk->cluster[0];
2176     uint64_t chunkSize = chunk->size;
2177     chunk->chunkNum= 1;
2178     if (trk->chunkCount)
2179         return;
2180     trk->chunkCount= 1;
2181     for(i=1; i<trk->entry; i++){
2182         if(chunk->pos + chunkSize == trk->cluster[i].pos &&
2183             chunkSize + trk->cluster[i].size < (1<<20)){
2184             chunkSize             += trk->cluster[i].size;
2185             chunk->samples_in_chunk += trk->cluster[i].entries;
2186         }else{
2187             trk->cluster[i].chunkNum = chunk->chunkNum+1;
2188             chunk=&trk->cluster[i];
2189             chunkSize = chunk->size;
2190             trk->chunkCount++;
2191         }
2192     }
2193 }
2194
2195 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2196                               AVFormatContext *s)
2197 {
2198     int i;
2199     int64_t pos = avio_tell(pb);
2200     avio_wb32(pb, 0); /* size placeholder*/
2201     ffio_wfourcc(pb, "moov");
2202
2203     for (i=0; i<mov->nb_streams; i++) {
2204         if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2205             continue;
2206
2207         mov->tracks[i].time = mov->time;
2208         mov->tracks[i].track_id = i+1;
2209
2210         if (mov->tracks[i].entry)
2211             build_chunks(&mov->tracks[i]);
2212     }
2213
2214     if (mov->chapter_track)
2215         for (i=0; i<s->nb_streams; i++) {
2216             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2217             mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
2218         }
2219     for (i = 0; i < mov->nb_streams; i++) {
2220         if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
2221             mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
2222             mov->tracks[i].tref_id =
2223                 mov->tracks[mov->tracks[i].src_track].track_id;
2224         }
2225     }
2226     for (i = 0; i < mov->nb_streams; i++) {
2227         if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
2228             int src_trk = mov->tracks[i].src_track;
2229             mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
2230             mov->tracks[src_trk].tref_id  = mov->tracks[i].track_id;
2231             mov->tracks[i].track_duration = mov->tracks[src_trk].track_duration;
2232         }
2233     }
2234
2235     mov_write_mvhd_tag(pb, mov);
2236     if (mov->mode != MODE_MOV && !mov->iods_skip)
2237         mov_write_iods_tag(pb, mov);
2238     for (i=0; i<mov->nb_streams; i++) {
2239         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2240             mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2241         }
2242     }
2243     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2244         mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2245
2246     if (mov->mode == MODE_PSP)
2247         mov_write_uuidusmt_tag(pb, s);
2248     else
2249         mov_write_udta_tag(pb, mov, s);
2250
2251     return update_size(pb, pos);
2252 }
2253
2254 static void param_write_int(AVIOContext *pb, const char *name, int value)
2255 {
2256     avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2257 }
2258
2259 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2260 {
2261     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2262 }
2263
2264 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2265 {
2266     char buf[150];
2267     len = FFMIN(sizeof(buf)/2 - 1, len);
2268     ff_data_to_hex(buf, value, len, 0);
2269     buf[2*len] = '\0';
2270     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2271 }
2272
2273 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2274 {
2275     int64_t pos = avio_tell(pb);
2276     int i;
2277     const uint8_t uuid[] = {
2278         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2279         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2280     };
2281
2282     avio_wb32(pb, 0);
2283     ffio_wfourcc(pb, "uuid");
2284     avio_write(pb, uuid, sizeof(uuid));
2285     avio_wb32(pb, 0);
2286
2287     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2288     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2289     avio_printf(pb, "<head>\n");
2290     avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2291                     LIBAVFORMAT_IDENT);
2292     avio_printf(pb, "</head>\n");
2293     avio_printf(pb, "<body>\n");
2294     avio_printf(pb, "<switch>\n");
2295     for (i = 0; i < mov->nb_streams; i++) {
2296         MOVTrack *track = &mov->tracks[i];
2297         const char *type;
2298         /* track->track_id is initialized in write_moov, and thus isn't known
2299          * here yet */
2300         int track_id = i + 1;
2301
2302         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2303             type = "video";
2304         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2305             type = "audio";
2306         } else {
2307             continue;
2308         }
2309         avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
2310                                                        track->enc->bit_rate);
2311         param_write_int(pb, "systemBitrate", track->enc->bit_rate);
2312         param_write_int(pb, "trackID", track_id);
2313         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2314             if (track->enc->codec_id == CODEC_ID_H264) {
2315                 uint8_t *ptr;
2316                 int size = track->enc->extradata_size;
2317                 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
2318                                                    &size)) {
2319                     param_write_hex(pb, "CodecPrivateData",
2320                                     ptr ? ptr : track->enc->extradata,
2321                                     size);
2322                     av_free(ptr);
2323                 }
2324                 param_write_string(pb, "FourCC", "H264");
2325             } else if (track->enc->codec_id == CODEC_ID_VC1) {
2326                 param_write_string(pb, "FourCC", "WVC1");
2327                 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2328                                 track->enc->extradata_size);
2329             }
2330             param_write_int(pb, "MaxWidth", track->enc->width);
2331             param_write_int(pb, "MaxHeight", track->enc->height);
2332             param_write_int(pb, "DisplayWidth", track->enc->width);
2333             param_write_int(pb, "DisplayHeight", track->enc->height);
2334         } else {
2335             if (track->enc->codec_id == CODEC_ID_AAC) {
2336                 param_write_string(pb, "FourCC", "AACL");
2337             } else if (track->enc->codec_id == CODEC_ID_WMAPRO) {
2338                 param_write_string(pb, "FourCC", "WMAP");
2339             }
2340             param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2341                             track->enc->extradata_size);
2342             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
2343                                                 track->enc->codec_id));
2344             param_write_int(pb, "Channels", track->enc->channels);
2345             param_write_int(pb, "SamplingRate", track->enc->sample_rate);
2346             param_write_int(pb, "BitsPerSample", 16);
2347             param_write_int(pb, "PacketSize", track->enc->block_align ?
2348                                               track->enc->block_align : 4);
2349         }
2350         avio_printf(pb, "</%s>\n", type);
2351     }
2352     avio_printf(pb, "</switch>\n");
2353     avio_printf(pb, "</body>\n");
2354     avio_printf(pb, "</smil>\n");
2355
2356     return update_size(pb, pos);
2357 }
2358
2359 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2360 {
2361     avio_wb32(pb, 16);
2362     ffio_wfourcc(pb, "mfhd");
2363     avio_wb32(pb, 0);
2364     avio_wb32(pb, mov->fragments);
2365     return 0;
2366 }
2367
2368 static int mov_write_tfhd_tag(AVIOContext *pb, MOVTrack *track,
2369                               int64_t moof_offset)
2370 {
2371     int64_t pos = avio_tell(pb);
2372     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2373                      MOV_TFHD_BASE_DATA_OFFSET;
2374     if (!track->entry) {
2375         flags |= MOV_TFHD_DURATION_IS_EMPTY;
2376     } else {
2377         flags |= MOV_TFHD_DEFAULT_FLAGS;
2378     }
2379
2380     /* Don't set a default sample size, the silverlight player refuses
2381      * to play files with that set. Don't set a default sample duration,
2382      * WMP freaks out if it is set. */
2383     if (track->mode == MODE_ISM)
2384         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION);
2385
2386     avio_wb32(pb, 0); /* size placeholder */
2387     ffio_wfourcc(pb, "tfhd");
2388     avio_w8(pb, 0); /* version */
2389     avio_wb24(pb, flags);
2390
2391     avio_wb32(pb, track->track_id); /* track-id */
2392     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
2393         avio_wb64(pb, moof_offset);
2394     if (flags & MOV_TFHD_DEFAULT_DURATION) {
2395         track->default_duration = get_cluster_duration(track, 0);
2396         avio_wb32(pb, track->default_duration);
2397     }
2398     if (flags & MOV_TFHD_DEFAULT_SIZE) {
2399         track->default_size = track->entry ? track->cluster[0].size : 1;
2400         avio_wb32(pb, track->default_size);
2401     } else
2402         track->default_size = -1;
2403
2404     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
2405         track->default_sample_flags =
2406             track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
2407             (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2408             MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
2409         avio_wb32(pb, track->default_sample_flags);
2410     }
2411
2412     return update_size(pb, pos);
2413 }
2414
2415 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2416 {
2417     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2418            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2419 }
2420
2421 static int mov_write_trun_tag(AVIOContext *pb, MOVTrack *track)
2422 {
2423     int64_t pos = avio_tell(pb);
2424     uint32_t flags = MOV_TRUN_DATA_OFFSET;
2425     int i;
2426
2427     for (i = 0; i < track->entry; i++) {
2428         if (get_cluster_duration(track, i) != track->default_duration)
2429             flags |= MOV_TRUN_SAMPLE_DURATION;
2430         if (track->cluster[i].size != track->default_size)
2431             flags |= MOV_TRUN_SAMPLE_SIZE;
2432         if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
2433             flags |= MOV_TRUN_SAMPLE_FLAGS;
2434     }
2435     if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
2436         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
2437     if (track->flags & MOV_TRACK_CTTS)
2438         flags |= MOV_TRUN_SAMPLE_CTS;
2439
2440     avio_wb32(pb, 0); /* size placeholder */
2441     ffio_wfourcc(pb, "trun");
2442     avio_w8(pb, 0); /* version */
2443     avio_wb24(pb, flags);
2444
2445     avio_wb32(pb, track->entry); /* sample count */
2446     track->moof_size_offset = avio_tell(pb);
2447     avio_wb32(pb, 0); /* data offset */
2448     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
2449         avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
2450
2451     for (i = 0; i < track->entry; i++) {
2452         if (flags & MOV_TRUN_SAMPLE_DURATION)
2453             avio_wb32(pb, get_cluster_duration(track, i));
2454         if (flags & MOV_TRUN_SAMPLE_SIZE)
2455             avio_wb32(pb, track->cluster[i].size);
2456         if (flags & MOV_TRUN_SAMPLE_FLAGS)
2457             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
2458         if (flags & MOV_TRUN_SAMPLE_CTS)
2459             avio_wb32(pb, track->cluster[i].cts);
2460     }
2461
2462     return update_size(pb, pos);
2463 }
2464
2465 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2466 {
2467     int64_t pos = avio_tell(pb);
2468     const uint8_t uuid[] = {
2469         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2470         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2471     };
2472
2473     avio_wb32(pb, 0); /* size placeholder */
2474     ffio_wfourcc(pb, "uuid");
2475     avio_write(pb, uuid, sizeof(uuid));
2476     avio_w8(pb, 1);
2477     avio_wb24(pb, 0);
2478     avio_wb64(pb, track->frag_start);
2479     avio_wb64(pb, track->start_dts + track->track_duration -
2480                   track->cluster[0].dts);
2481
2482     return update_size(pb, pos);
2483 }
2484
2485 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2486                               MOVTrack *track, int entry)
2487 {
2488     int n = track->nb_frag_info - 1 - entry, i;
2489     int size = 8 + 16 + 4 + 1 + 16*n;
2490     const uint8_t uuid[] = {
2491         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2492         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2493     };
2494
2495     if (entry < 0)
2496         return 0;
2497
2498     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2499     avio_wb32(pb, size);
2500     ffio_wfourcc(pb, "uuid");
2501     avio_write(pb, uuid, sizeof(uuid));
2502     avio_w8(pb, 1);
2503     avio_wb24(pb, 0);
2504     avio_w8(pb, n);
2505     for (i = 0; i < n; i++) {
2506         int index = entry + 1 + i;
2507         avio_wb64(pb, track->frag_info[index].time);
2508         avio_wb64(pb, track->frag_info[index].duration);
2509     }
2510     if (n < mov->ism_lookahead) {
2511         int free_size = 16*(mov->ism_lookahead - n);
2512         avio_wb32(pb, free_size);
2513         ffio_wfourcc(pb, "free");
2514         for (i = 0; i < free_size - 8; i++)
2515             avio_w8(pb, 0);
2516     }
2517
2518     return 0;
2519 }
2520
2521 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2522                                MOVTrack *track)
2523 {
2524     int64_t pos = avio_tell(pb);
2525     int i;
2526     for (i = 0; i < mov->ism_lookahead; i++) {
2527         /* Update the tfrf tag for the last ism_lookahead fragments,
2528          * nb_frag_info - 1 is the next fragment to be written. */
2529         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2530     }
2531     avio_seek(pb, pos, SEEK_SET);
2532     return 0;
2533 }
2534
2535 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
2536                               MOVTrack *track, int64_t moof_offset)
2537 {
2538     int64_t pos = avio_tell(pb);
2539     avio_wb32(pb, 0); /* size placeholder */
2540     ffio_wfourcc(pb, "traf");
2541
2542     mov_write_tfhd_tag(pb, track, moof_offset);
2543     mov_write_trun_tag(pb, track);
2544     if (mov->mode == MODE_ISM) {
2545         mov_write_tfxd_tag(pb, track);
2546
2547         if (mov->ism_lookahead) {
2548             int i, size = 16 + 4 + 1 + 16*mov->ism_lookahead;
2549
2550             track->tfrf_offset = avio_tell(pb);
2551             avio_wb32(pb, 8 + size);
2552             ffio_wfourcc(pb, "free");
2553             for (i = 0; i < size; i++)
2554                 avio_w8(pb, 0);
2555         }
2556     }
2557
2558     return update_size(pb, pos);
2559 }
2560
2561 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
2562 {
2563     int64_t pos = avio_tell(pb), end;
2564     int i, moof_size;
2565
2566     avio_wb32(pb, 0); /* size placeholder */
2567     ffio_wfourcc(pb, "moof");
2568
2569     mov_write_mfhd_tag(pb, mov);
2570     for (i = 0; i < mov->nb_streams; i++) {
2571         MOVTrack *track = &mov->tracks[i];
2572         if (tracks >= 0 && i != tracks)
2573             continue;
2574         if (!track->entry)
2575             continue;
2576         mov_write_traf_tag(pb, mov, track, pos);
2577     }
2578
2579     end = avio_tell(pb);
2580     moof_size = end - pos;
2581     for (i = 0; i < mov->nb_streams; i++) {
2582         MOVTrack *track = &mov->tracks[i];
2583         if (tracks >= 0 && i != tracks)
2584             continue;
2585         if (!track->entry)
2586             continue;
2587         avio_seek(pb, mov->tracks[i].moof_size_offset, SEEK_SET);
2588         avio_wb32(pb, moof_size + 8 + mov->tracks[i].data_offset);
2589     }
2590     avio_seek(pb, end, SEEK_SET);
2591
2592     return update_size(pb, pos);
2593 }
2594
2595 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
2596 {
2597     int64_t pos = avio_tell(pb);
2598     int i;
2599
2600     avio_wb32(pb, 0); /* size placeholder */
2601     ffio_wfourcc(pb, "tfra");
2602     avio_w8(pb, 1); /* version */
2603     avio_wb24(pb, 0);
2604
2605     avio_wb32(pb, track->track_id);
2606     avio_wb32(pb, 0); /* length of traf/trun/sample num */
2607     avio_wb32(pb, track->nb_frag_info);
2608     for (i = 0; i < track->nb_frag_info; i++) {
2609         avio_wb64(pb, track->frag_info[i].time);
2610         avio_wb64(pb, track->frag_info[i].offset);
2611         avio_w8(pb, 1); /* traf number */
2612         avio_w8(pb, 1); /* trun number */
2613         avio_w8(pb, 1); /* sample number */
2614     }
2615
2616     return update_size(pb, pos);
2617 }
2618
2619 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
2620 {
2621     int64_t pos = avio_tell(pb);
2622     int i;
2623
2624     avio_wb32(pb, 0); /* size placeholder */
2625     ffio_wfourcc(pb, "mfra");
2626     /* An empty mfra atom is enough to indicate to the publishing point that
2627      * the stream has ended. */
2628     if (mov->flags & FF_MOV_FLAG_ISML)
2629         return update_size(pb, pos);
2630
2631     for (i = 0; i < mov->nb_streams; i++) {
2632         MOVTrack *track = &mov->tracks[i];
2633         if (track->nb_frag_info)
2634             mov_write_tfra_tag(pb, track);
2635     }
2636
2637     avio_wb32(pb, 16);
2638     ffio_wfourcc(pb, "mfro");
2639     avio_wb32(pb, 0); /* version + flags */
2640     avio_wb32(pb, avio_tell(pb) + 4 - pos);
2641
2642     return update_size(pb, pos);
2643 }
2644
2645 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
2646 {
2647     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
2648     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
2649
2650     mov->mdat_pos = avio_tell(pb);
2651     avio_wb32(pb, 0); /* size placeholder*/
2652     ffio_wfourcc(pb, "mdat");
2653     return 0;
2654 }
2655
2656 /* TODO: This needs to be more general */
2657 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
2658 {
2659     MOVMuxContext *mov = s->priv_data;
2660     int64_t pos = avio_tell(pb);
2661     int has_h264 = 0, has_video = 0;
2662     int minor = 0x200;
2663     int i;
2664
2665     for (i = 0; i < s->nb_streams; i++) {
2666         AVStream *st = s->streams[i];
2667         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2668             has_video = 1;
2669         if (st->codec->codec_id == CODEC_ID_H264)
2670             has_h264 = 1;
2671     }
2672
2673     avio_wb32(pb, 0); /* size */
2674     ffio_wfourcc(pb, "ftyp");
2675
2676     if (mov->mode == MODE_3GP) {
2677         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
2678         minor =     has_h264 ?   0x100 :   0x200;
2679     } else if (mov->mode & MODE_3G2) {
2680         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
2681         minor =     has_h264 ? 0x20000 : 0x10000;
2682     }else if (mov->mode == MODE_PSP)
2683         ffio_wfourcc(pb, "MSNV");
2684     else if (mov->mode == MODE_MP4)
2685         ffio_wfourcc(pb, "isom");
2686     else if (mov->mode == MODE_IPOD)
2687         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
2688     else if (mov->mode == MODE_ISM)
2689         ffio_wfourcc(pb, "isml");
2690     else
2691         ffio_wfourcc(pb, "qt  ");
2692
2693     avio_wb32(pb, minor);
2694
2695     if(mov->mode == MODE_MOV)
2696         ffio_wfourcc(pb, "qt  ");
2697     else if (mov->mode == MODE_ISM) {
2698         ffio_wfourcc(pb, "piff");
2699         ffio_wfourcc(pb, "iso2");
2700     } else {
2701         ffio_wfourcc(pb, "isom");
2702         ffio_wfourcc(pb, "iso2");
2703         if(has_h264)
2704             ffio_wfourcc(pb, "avc1");
2705     }
2706
2707     if (mov->mode == MODE_3GP)
2708         ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
2709     else if (mov->mode & MODE_3G2)
2710         ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
2711     else if (mov->mode == MODE_PSP)
2712         ffio_wfourcc(pb, "MSNV");
2713     else if (mov->mode == MODE_MP4)
2714         ffio_wfourcc(pb, "mp41");
2715     return update_size(pb, pos);
2716 }
2717
2718 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
2719 {
2720     AVCodecContext *video_codec = s->streams[0]->codec;
2721     AVCodecContext *audio_codec = s->streams[1]->codec;
2722     int audio_rate = audio_codec->sample_rate;
2723     int frame_rate = ((video_codec->time_base.den) * (0x10000))/ (video_codec->time_base.num);
2724     int audio_kbitrate = audio_codec->bit_rate / 1000;
2725     int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
2726
2727     avio_wb32(pb, 0x94); /* size */
2728     ffio_wfourcc(pb, "uuid");
2729     ffio_wfourcc(pb, "PROF");
2730
2731     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2732     avio_wb32(pb, 0xbb88695c);
2733     avio_wb32(pb, 0xfac9c740);
2734
2735     avio_wb32(pb, 0x0);  /* ? */
2736     avio_wb32(pb, 0x3);  /* 3 sections ? */
2737
2738     avio_wb32(pb, 0x14); /* size */
2739     ffio_wfourcc(pb, "FPRF");
2740     avio_wb32(pb, 0x0);  /* ? */
2741     avio_wb32(pb, 0x0);  /* ? */
2742     avio_wb32(pb, 0x0);  /* ? */
2743
2744     avio_wb32(pb, 0x2c);  /* size */
2745     ffio_wfourcc(pb, "APRF");/* audio */
2746     avio_wb32(pb, 0x0);
2747     avio_wb32(pb, 0x2);   /* TrackID */
2748     ffio_wfourcc(pb, "mp4a");
2749     avio_wb32(pb, 0x20f);
2750     avio_wb32(pb, 0x0);
2751     avio_wb32(pb, audio_kbitrate);
2752     avio_wb32(pb, audio_kbitrate);
2753     avio_wb32(pb, audio_rate);
2754     avio_wb32(pb, audio_codec->channels);
2755
2756     avio_wb32(pb, 0x34);  /* size */
2757     ffio_wfourcc(pb, "VPRF");   /* video */
2758     avio_wb32(pb, 0x0);
2759     avio_wb32(pb, 0x1);    /* TrackID */
2760     if (video_codec->codec_id == CODEC_ID_H264) {
2761         ffio_wfourcc(pb, "avc1");
2762         avio_wb16(pb, 0x014D);
2763         avio_wb16(pb, 0x0015);
2764     } else {
2765         ffio_wfourcc(pb, "mp4v");
2766         avio_wb16(pb, 0x0000);
2767         avio_wb16(pb, 0x0103);
2768     }
2769     avio_wb32(pb, 0x0);
2770     avio_wb32(pb, video_kbitrate);
2771     avio_wb32(pb, video_kbitrate);
2772     avio_wb32(pb, frame_rate);
2773     avio_wb32(pb, frame_rate);
2774     avio_wb16(pb, video_codec->width);
2775     avio_wb16(pb, video_codec->height);
2776     avio_wb32(pb, 0x010001); /* ? */
2777 }
2778
2779 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
2780 {
2781     uint32_t c = -1;
2782     int i, closed_gop = 0;
2783
2784     for (i = 0; i < pkt->size - 4; i++) {
2785         c = (c<<8) + pkt->data[i];
2786         if (c == 0x1b8) { // gop
2787             closed_gop = pkt->data[i+4]>>6 & 0x01;
2788         } else if (c == 0x100) { // pic
2789             int temp_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
2790             if (!temp_ref || closed_gop) // I picture is not reordered
2791                 *flags = MOV_SYNC_SAMPLE;
2792             else
2793                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
2794             break;
2795         }
2796     }
2797     return 0;
2798 }
2799
2800 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
2801 {
2802     const uint8_t *start, *next, *end = pkt->data + pkt->size;
2803     int seq = 0, entry = 0;
2804     int key = pkt->flags & AV_PKT_FLAG_KEY;
2805     start = find_next_marker(pkt->data, end);
2806     for (next = start; next < end; start = next) {
2807         next = find_next_marker(start + 4, end);
2808         switch (AV_RB32(start)) {
2809         case VC1_CODE_SEQHDR:
2810             seq = 1;
2811             break;
2812         case VC1_CODE_ENTRYPOINT:
2813             entry = 1;
2814             break;
2815         case VC1_CODE_SLICE:
2816             trk->vc1_info.slices = 1;
2817             break;
2818         }
2819     }
2820     if (!trk->entry && !fragment) {
2821         /* First packet in first fragment */
2822         trk->vc1_info.first_packet_seq   = seq;
2823         trk->vc1_info.first_packet_entry = entry;
2824     } else if ((seq && !trk->vc1_info.packet_seq) ||
2825                (entry && !trk->vc1_info.packet_entry)) {
2826         int i;
2827         for (i = 0; i < trk->entry; i++)
2828             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
2829         trk->has_keyframes = 0;
2830         if (seq)
2831             trk->vc1_info.packet_seq = 1;
2832         if (entry)
2833             trk->vc1_info.packet_entry = 1;
2834         if (!fragment) {
2835             /* First fragment */
2836             if ((!seq   || trk->vc1_info.first_packet_seq) &&
2837                 (!entry || trk->vc1_info.first_packet_entry)) {
2838                 /* First packet had the same headers as this one, readd the
2839                  * sync sample flag. */
2840                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
2841                 trk->has_keyframes = 1;
2842             }
2843         }
2844     }
2845     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
2846         key = seq && entry;
2847     else if (trk->vc1_info.packet_seq)
2848         key = seq;
2849     else if (trk->vc1_info.packet_entry)
2850         key = entry;
2851     if (key) {
2852         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
2853         trk->has_keyframes++;
2854     }
2855 }
2856
2857 static int mov_flush_fragment(AVFormatContext *s)
2858 {
2859     MOVMuxContext *mov = s->priv_data;
2860     int i, first_track = -1;
2861     int64_t mdat_size = 0;
2862
2863     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
2864         return 0;
2865
2866     if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
2867         int64_t pos = avio_tell(s->pb);
2868         int ret;
2869         AVIOContext *moov_buf;
2870         uint8_t *buf;
2871         int buf_size;
2872
2873         for (i = 0; i < mov->nb_streams; i++)
2874             if (!mov->tracks[i].entry)
2875                 break;
2876         /* Don't write the initial moov unless all tracks have data */
2877         if (i < mov->nb_streams)
2878             return 0;
2879
2880         if ((ret = avio_open_dyn_buf(&moov_buf)) < 0)
2881             return ret;
2882         mov_write_moov_tag(moov_buf, mov, s);
2883         buf_size = avio_close_dyn_buf(moov_buf, &buf);
2884         av_free(buf);
2885         for (i = 0; i < mov->nb_streams; i++)
2886             mov->tracks[i].data_offset = pos + buf_size + 8;
2887
2888         mov_write_moov_tag(s->pb, mov, s);
2889
2890         buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
2891         mov->mdat_buf = NULL;
2892         avio_wb32(s->pb, buf_size + 8);
2893         ffio_wfourcc(s->pb, "mdat");
2894         avio_write(s->pb, buf, buf_size);
2895         av_free(buf);
2896
2897         mov->fragments++;
2898         mov->mdat_size = 0;
2899         for (i = 0; i < mov->nb_streams; i++) {
2900             if (mov->tracks[i].entry)
2901                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
2902                                              mov->tracks[i].track_duration -
2903                                              mov->tracks[i].cluster[0].dts;
2904             mov->tracks[i].entry = 0;
2905         }
2906         avio_flush(s->pb);
2907         return 0;
2908     }
2909
2910     for (i = 0; i < mov->nb_streams; i++) {
2911         MOVTrack *track = &mov->tracks[i];
2912         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
2913             track->data_offset = 0;
2914         else
2915             track->data_offset = mdat_size;
2916         if (!track->mdat_buf)
2917             continue;
2918         mdat_size += avio_tell(track->mdat_buf);
2919         if (first_track < 0)
2920             first_track = i;
2921     }
2922
2923     if (!mdat_size)
2924         return 0;
2925
2926     for (i = 0; i < mov->nb_streams; i++) {
2927         MOVTrack *track = &mov->tracks[i];
2928         int buf_size, write_moof = 1, moof_tracks = -1;
2929         uint8_t *buf;
2930         int64_t duration = 0;
2931
2932         if (track->entry)
2933             duration = track->start_dts + track->track_duration -
2934                        track->cluster[0].dts;
2935         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
2936             if (!track->mdat_buf)
2937                 continue;
2938             mdat_size = avio_tell(track->mdat_buf);
2939             moof_tracks = i;
2940         } else {
2941             write_moof = i == first_track;
2942         }
2943
2944         if (write_moof) {
2945             MOVFragmentInfo *info;
2946             avio_flush(s->pb);
2947             track->nb_frag_info++;
2948             track->frag_info = av_realloc(track->frag_info,
2949                                           sizeof(*track->frag_info) *
2950                                           track->nb_frag_info);
2951             info = &track->frag_info[track->nb_frag_info - 1];
2952             info->offset   = avio_tell(s->pb);
2953             info->time     = mov->tracks[i].frag_start;
2954             info->duration = duration;
2955             mov_write_tfrf_tags(s->pb, mov, track);
2956
2957             mov_write_moof_tag(s->pb, mov, moof_tracks);
2958             info->tfrf_offset = track->tfrf_offset;
2959             mov->fragments++;
2960
2961             avio_wb32(s->pb, mdat_size + 8);
2962             ffio_wfourcc(s->pb, "mdat");
2963         }
2964
2965         if (track->entry)
2966             track->frag_start += duration;
2967         track->entry = 0;
2968         if (!track->mdat_buf)
2969             continue;
2970         buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
2971         track->mdat_buf = NULL;
2972
2973         avio_write(s->pb, buf, buf_size);
2974         av_free(buf);
2975     }
2976
2977     mov->mdat_size = 0;
2978
2979     avio_flush(s->pb);
2980     return 0;
2981 }
2982
2983 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
2984 {
2985     MOVMuxContext *mov = s->priv_data;
2986     AVIOContext *pb = s->pb;
2987     MOVTrack *trk = &mov->tracks[pkt->stream_index];
2988     AVCodecContext *enc = trk->enc;
2989     unsigned int samples_in_chunk = 0;
2990     int size= pkt->size;
2991     uint8_t *reformatted_data = NULL;
2992
2993     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
2994         int ret;
2995         if (mov->fragments > 0) {
2996             if (!trk->mdat_buf) {
2997                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
2998                     return ret;
2999             }
3000             pb = trk->mdat_buf;
3001         } else {
3002             if (!mov->mdat_buf) {
3003                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
3004                     return ret;
3005             }
3006             pb = mov->mdat_buf;
3007         }
3008     }
3009
3010     if (enc->codec_id == CODEC_ID_AMR_NB) {
3011         /* We must find out how many AMR blocks there are in one packet */
3012         static uint16_t packed_size[16] =
3013             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
3014         int len = 0;
3015
3016         while (len < size && samples_in_chunk < 100) {
3017             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
3018             samples_in_chunk++;
3019         }
3020         if (samples_in_chunk > 1) {
3021             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
3022             return -1;
3023         }
3024     } else if (enc->codec_id == CODEC_ID_ADPCM_MS ||
3025                enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
3026         samples_in_chunk = enc->frame_size;
3027     } else if (trk->sample_size)
3028         samples_in_chunk = size / trk->sample_size;
3029     else
3030         samples_in_chunk = 1;
3031
3032     /* copy extradata if it exists */
3033     if (trk->vos_len == 0 && enc->extradata_size > 0) {
3034         trk->vos_len = enc->extradata_size;
3035         trk->vos_data = av_malloc(trk->vos_len);
3036         memcpy(trk->vos_data, enc->extradata, trk->vos_len);
3037     }
3038
3039     if (enc->codec_id == CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {
3040         /* from x264 or from bytestream h264 */
3041         /* nal reformating needed */
3042         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3043             ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
3044                                        &size);
3045             avio_write(pb, reformatted_data, size);
3046         } else {
3047             size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
3048         }
3049     } else if (enc->codec_id == CODEC_ID_AAC && pkt->size > 2 &&
3050                (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
3051         av_log(s, AV_LOG_ERROR, "malformated aac bitstream, use -absf aac_adtstoasc\n");
3052         return -1;
3053     } else {
3054         avio_write(pb, pkt->data, size);
3055     }
3056
3057     if ((enc->codec_id == CODEC_ID_DNXHD ||
3058          enc->codec_id == CODEC_ID_AC3) && !trk->vos_len) {
3059         /* copy frame to create needed atoms */
3060         trk->vos_len = size;
3061         trk->vos_data = av_malloc(size);
3062         if (!trk->vos_data)
3063             return AVERROR(ENOMEM);
3064         memcpy(trk->vos_data, pkt->data, size);
3065     }
3066
3067     if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
3068         trk->cluster = av_realloc_f(trk->cluster, sizeof(*trk->cluster), (trk->entry + MOV_INDEX_CLUSTER_SIZE));
3069         if (!trk->cluster)
3070             return -1;
3071     }
3072
3073     trk->cluster[trk->entry].pos = avio_tell(pb) - size;
3074     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
3075     trk->cluster[trk->entry].chunkNum = 0;
3076     trk->cluster[trk->entry].size = size;
3077     trk->cluster[trk->entry].entries = samples_in_chunk;
3078     trk->cluster[trk->entry].dts = pkt->dts;
3079     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
3080         /* First packet of a new fragment. We already wrote the duration
3081          * of the last packet of the previous fragment based on track_duration,
3082          * which might not exactly match our dts. Therefore adjust the dts
3083          * of this packet to be what the previous packets duration implies. */
3084         trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
3085     }
3086     if (trk->start_dts == AV_NOPTS_VALUE)
3087         trk->start_dts = pkt->dts;
3088     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
3089     trk->last_sample_is_subtitle_end = 0;
3090
3091     if (pkt->pts == AV_NOPTS_VALUE) {
3092         av_log(s, AV_LOG_WARNING, "pts has no value\n");
3093         pkt->pts = pkt->dts;
3094     }
3095     if (pkt->dts != pkt->pts)
3096         trk->flags |= MOV_TRACK_CTTS;
3097     trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
3098     trk->cluster[trk->entry].flags = 0;
3099     if (enc->codec_id == CODEC_ID_VC1) {
3100         mov_parse_vc1_frame(pkt, trk, mov->fragments);
3101     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
3102         if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO &&
3103             trk->entry > 0) { // force sync sample for the first key frame
3104             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
3105             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
3106                 trk->flags |= MOV_TRACK_STPS;
3107         } else {
3108             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
3109         }
3110         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
3111             trk->has_keyframes++;
3112     }
3113     trk->entry++;
3114     trk->sample_count += samples_in_chunk;
3115     mov->mdat_size += size;
3116
3117     avio_flush(pb);
3118
3119     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
3120         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
3121                                  reformatted_data, size);
3122     av_free(reformatted_data);
3123     return 0;
3124 }
3125
3126 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
3127 {
3128         MOVMuxContext *mov = s->priv_data;
3129         MOVTrack *trk = &mov->tracks[pkt->stream_index];
3130         AVCodecContext *enc = trk->enc;
3131         int64_t frag_duration = 0;
3132         int size = pkt->size;
3133
3134         if (!pkt->size) return 0; /* Discard 0 sized packets */
3135
3136         if (trk->entry && pkt->stream_index < s->nb_streams)
3137             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
3138                                          s->streams[pkt->stream_index]->time_base,
3139                                          AV_TIME_BASE_Q);
3140         if ((mov->max_fragment_duration &&
3141              frag_duration >= mov->max_fragment_duration) ||
3142              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
3143              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
3144               enc->codec_type == AVMEDIA_TYPE_VIDEO &&
3145               trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
3146             if (frag_duration >= mov->min_fragment_duration)
3147                 mov_flush_fragment(s);
3148         }
3149
3150         return ff_mov_write_packet(s, pkt);
3151 }
3152
3153 static int mov_write_subtitle_end_packet(AVFormatContext *s,
3154                                          int stream_index,
3155                                          int64_t dts) {
3156     AVPacket end;
3157     short data = 0;
3158     int ret;
3159
3160     av_init_packet(&end);
3161     end.size = sizeof (short);
3162     end.data = (char *)&data;
3163     end.pts = dts;
3164     end.dts = dts;
3165     end.duration = 0;
3166     end.stream_index = stream_index;
3167
3168     ret = mov_write_single_packet(s, &end);
3169     av_free_packet(&end);
3170
3171     return ret;
3172 }
3173
3174 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3175 {
3176     if (!pkt) {
3177         mov_flush_fragment(s);
3178         return 1;
3179     } else {
3180         int i;
3181         MOVMuxContext *mov = s->priv_data;
3182
3183         if (!pkt->size) return 0; /* Discard 0 sized packets */
3184
3185         /*
3186          * Subtitles require special handling.
3187          *
3188          * 1) For full complaince, every track must have a sample at
3189          * dts == 0, which is rarely true for subtitles. So, as soon
3190          * as we see any packet with dts > 0, write an empty subtitle
3191          * at dts == 0 for any subtitle track with no samples in it.
3192          *
3193          * 2) For each subtitle track, check if the current packet's
3194          * dts is past the duration of the last subtitle sample. If
3195          * so, we now need to write an end sample for that subtitle.
3196          *
3197          * This must be done conditionally to allow for subtitles that
3198          * immediately replace each other, in which case an end sample
3199          * is not needed, and is, in fact, actively harmful.
3200          *
3201          * 3) See mov_write_trailer for how the final end sample is
3202          * handled.
3203          */
3204         for (i = 0; i < mov->nb_streams; i++) {
3205             MOVTrack *trk = &mov->tracks[i];
3206             int ret;
3207
3208             if (trk->enc->codec_id == CODEC_ID_MOV_TEXT &&
3209                 trk->track_duration < pkt->dts &&
3210                 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
3211                 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
3212                 if (ret < 0) return ret;
3213                 trk->last_sample_is_subtitle_end = 1;
3214             }
3215         }
3216
3217         return mov_write_single_packet(s, pkt);
3218     }
3219 }
3220
3221 // QuickTime chapters involve an additional text track with the chapter names
3222 // as samples, and a tref pointing from the other tracks to the chapter one.
3223 static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
3224 {
3225     AVIOContext *pb;
3226
3227     MOVMuxContext *mov = s->priv_data;
3228     MOVTrack *track = &mov->tracks[tracknum];
3229     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
3230     int i, len;
3231
3232     track->mode = mov->mode;
3233     track->tag = MKTAG('t','e','x','t');
3234     track->timescale = MOV_TIMESCALE;
3235     track->enc = avcodec_alloc_context3(NULL);
3236     track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3237
3238     if (avio_open_dyn_buf(&pb) >= 0) {
3239         int size;
3240         uint8_t *buf;
3241
3242         /* Stub header (usually for Quicktime chapter track) */
3243         // TextSampleEntry
3244         avio_wb32(pb, 0x01); // displayFlags
3245         avio_w8(pb, 0x00);   // horizontal justification
3246         avio_w8(pb, 0x00);   // vertical justification
3247         avio_w8(pb, 0x00);   // bgColourRed
3248         avio_w8(pb, 0x00);   // bgColourGreen
3249         avio_w8(pb, 0x00);   // bgColourBlue
3250         avio_w8(pb, 0x00);   // bgColourAlpha
3251         // BoxRecord
3252         avio_wb16(pb, 0x00); // defTextBoxTop
3253         avio_wb16(pb, 0x00); // defTextBoxLeft
3254         avio_wb16(pb, 0x00); // defTextBoxBottom
3255         avio_wb16(pb, 0x00); // defTextBoxRight
3256         // StyleRecord
3257         avio_wb16(pb, 0x00); // startChar
3258         avio_wb16(pb, 0x00); // endChar
3259         avio_wb16(pb, 0x01); // fontID
3260         avio_w8(pb, 0x00);   // fontStyleFlags
3261         avio_w8(pb, 0x00);   // fontSize
3262         avio_w8(pb, 0x00);   // fgColourRed
3263         avio_w8(pb, 0x00);   // fgColourGreen
3264         avio_w8(pb, 0x00);   // fgColourBlue
3265         avio_w8(pb, 0x00);   // fgColourAlpha
3266         // FontTableBox
3267         avio_wb32(pb, 0x0D); // box size
3268         ffio_wfourcc(pb, "ftab"); // box atom name
3269         avio_wb16(pb, 0x01); // entry count
3270         // FontRecord
3271         avio_wb16(pb, 0x01); // font ID
3272         avio_w8(pb, 0x00);   // font name length
3273
3274         if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
3275             track->enc->extradata = buf;
3276             track->enc->extradata_size = size;
3277         } else {
3278             av_free(&buf);
3279         }
3280     }
3281
3282     for (i = 0; i < s->nb_chapters; i++) {
3283         AVChapter *c = s->chapters[i];
3284         AVDictionaryEntry *t;
3285
3286         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
3287         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
3288         pkt.duration = end - pkt.dts;
3289
3290         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3291             len = strlen(t->value);
3292             pkt.size = len+2;
3293             pkt.data = av_malloc(pkt.size);
3294             AV_WB16(pkt.data, len);
3295             memcpy(pkt.data+2, t->value, len);
3296             ff_mov_write_packet(s, &pkt);
3297             av_freep(&pkt.data);
3298         }
3299     }
3300 }
3301
3302 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
3303 {
3304     MOVMuxContext *mov  = s->priv_data;
3305     MOVTrack *track     = &mov->tracks[index];
3306     AVStream *src_st    = s->streams[src_index];
3307     AVTimecode tc;
3308     AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
3309     AVRational rate = {src_st->codec->time_base.den, src_st->codec->time_base.num};
3310
3311     /* compute the frame number */
3312     int ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
3313     if (ret < 0)
3314         return ret;
3315
3316     /* tmcd track based on video stream */
3317     track->mode      = mov->mode;
3318     track->tag       = MKTAG('t','m','c','d');
3319     track->src_track = src_index;
3320     track->timescale = src_st->codec->time_base.den;
3321     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
3322         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
3323
3324     /* encode context: tmcd data stream */
3325     track->enc = avcodec_alloc_context3(NULL);
3326     track->enc->codec_type = AVMEDIA_TYPE_DATA;
3327     track->enc->codec_tag  = track->tag;
3328     track->enc->time_base  = src_st->codec->time_base;
3329
3330     /* the tmcd track just contains one packet with the frame number */
3331     pkt.data = av_malloc(pkt.size);
3332     AV_WB32(pkt.data, tc.start);
3333     ret = ff_mov_write_packet(s, &pkt);
3334     av_free(pkt.data);
3335     return ret;
3336 }
3337
3338 static int mov_write_header(AVFormatContext *s)
3339 {
3340     AVIOContext *pb = s->pb;
3341     MOVMuxContext *mov = s->priv_data;
3342     AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
3343     int i, hint_track = 0, tmcd_track = 0;
3344
3345     /* Set the FRAGMENT flag if any of the fragmentation methods are
3346      * enabled. */
3347     if (mov->max_fragment_duration || mov->max_fragment_size ||
3348         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
3349                       FF_MOV_FLAG_FRAG_KEYFRAME |
3350                       FF_MOV_FLAG_FRAG_CUSTOM))
3351         mov->flags |= FF_MOV_FLAG_FRAGMENT;
3352
3353     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
3354      * is enabled, we don't support non-seekable output at all. */
3355     if (!s->pb->seekable &&
3356         ((!(mov->flags & FF_MOV_FLAG_FRAGMENT) &&
3357           !(s->oformat && !strcmp(s->oformat->name, "ismv")))
3358          || mov->ism_lookahead)) {
3359         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
3360         return -1;
3361     }
3362
3363     /* Default mode == MP4 */
3364     mov->mode = MODE_MP4;
3365
3366     if (s->oformat != NULL) {
3367         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
3368         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
3369         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
3370         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
3371         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
3372         else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
3373
3374         mov_write_ftyp_tag(pb,s);
3375         if (mov->mode == MODE_PSP) {
3376             if (s->nb_streams != 2) {
3377                 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3378                 return -1;
3379             }
3380             mov_write_uuidprof_tag(pb,s);
3381         }
3382     }
3383
3384     mov->nb_streams = s->nb_streams;
3385     if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
3386         mov->chapter_track = mov->nb_streams++;
3387
3388     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
3389         /* Add hint tracks for each audio and video stream */
3390         hint_track = mov->nb_streams;
3391         for (i = 0; i < s->nb_streams; i++) {
3392             AVStream *st = s->streams[i];
3393             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3394                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3395                 mov->nb_streams++;
3396             }
3397         }
3398     }
3399
3400     if (mov->mode == MODE_MOV) {
3401         tmcd_track = mov->nb_streams;
3402
3403         /* +1 tmcd track for each video stream with a timecode */
3404         for (i = 0; i < s->nb_streams; i++) {
3405             AVStream *st = s->streams[i];
3406             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3407                 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
3408                 mov->nb_meta_tmcd++;
3409         }
3410
3411         /* check if there is already a tmcd track to remux */
3412         if (mov->nb_meta_tmcd) {
3413             for (i = 0; i < s->nb_streams; i++) {
3414                 AVStream *st = s->streams[i];
3415                 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
3416                     av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
3417                            "so timecode metadata are now ignored\n");
3418                     mov->nb_meta_tmcd = 0;
3419                 }
3420             }
3421         }
3422
3423         mov->nb_streams += mov->nb_meta_tmcd;
3424     }
3425
3426     mov->tracks = av_mallocz(mov->nb_streams*sizeof(*mov->tracks));
3427     if (!mov->tracks)
3428         return AVERROR(ENOMEM);
3429
3430     for(i=0; i<s->nb_streams; i++){
3431         AVStream *st= s->streams[i];
3432         MOVTrack *track= &mov->tracks[i];
3433         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3434
3435         track->enc = st->codec;
3436         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
3437         if (track->language < 0)
3438             track->language = 0;
3439         track->mode = mov->mode;
3440         track->tag = mov_find_codec_tag(s, track);
3441         if (!track->tag) {
3442             av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
3443                    "codec not currently supported in container\n", i);
3444             goto error;
3445         }
3446         /* If hinting of this track is enabled by a later hint track,
3447          * this is updated. */
3448         track->hint_track = -1;
3449         track->start_dts = AV_NOPTS_VALUE;
3450         if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
3451             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
3452                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
3453                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
3454                 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
3455                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
3456                     goto error;
3457                 }
3458                 track->height = track->tag>>24 == 'n' ? 486 : 576;
3459             }
3460             track->timescale = st->codec->time_base.den;
3461             if (track->mode == MODE_MOV && track->timescale > 100000)
3462                 av_log(s, AV_LOG_WARNING,
3463                        "WARNING codec timebase is very high. If duration is too long,\n"
3464                        "file may not be playable by quicktime. Specify a shorter timebase\n"
3465                        "or choose different container.\n");
3466         }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO){
3467             track->timescale = st->codec->sample_rate;
3468             if(!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
3469                 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
3470                 track->audio_vbr = 1;
3471             }else if(st->codec->codec_id == CODEC_ID_ADPCM_MS ||
3472                      st->codec->codec_id == CODEC_ID_ADPCM_IMA_WAV ||
3473                      st->codec->codec_id == CODEC_ID_ILBC){
3474                 if (!st->codec->block_align) {
3475                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
3476                     goto error;
3477                 }
3478                 track->sample_size = st->codec->block_align;
3479             }else if(st->codec->frame_size > 1){ /* assume compressed audio */
3480                 track->audio_vbr = 1;
3481             }else{
3482                 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
3483             }
3484             if (track->mode != MODE_MOV &&
3485                 track->enc->codec_id == CODEC_ID_MP3 && track->timescale < 16000) {
3486                 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
3487                        i, track->enc->sample_rate);
3488                 goto error;
3489             }
3490         }else if(st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE){
3491             track->timescale = st->codec->time_base.den;
3492         }else{
3493             track->timescale = MOV_TIMESCALE;
3494         }
3495         if (!track->height)
3496             track->height = st->codec->height;
3497         /* The ism specific timescale isn't mandatory, but is assumed by
3498          * some tools, such as mp4split. */
3499         if (mov->mode == MODE_ISM)
3500             track->timescale = 10000000;
3501
3502         avpriv_set_pts_info(st, 64, 1, track->timescale);
3503
3504         /* copy extradata if it exists */
3505         if (st->codec->extradata_size) {
3506             track->vos_len  = st->codec->extradata_size;
3507             track->vos_data = av_malloc(track->vos_len);
3508             memcpy(track->vos_data, st->codec->extradata, track->vos_len);
3509         }
3510     }
3511
3512     if (mov->mode == MODE_ISM) {
3513         /* If no fragmentation options have been set, set a default. */
3514         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
3515                             FF_MOV_FLAG_FRAG_CUSTOM)) &&
3516             !mov->max_fragment_duration && !mov->max_fragment_size)
3517             mov->max_fragment_duration = 5000000;
3518         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
3519                       FF_MOV_FLAG_FRAGMENT;
3520     }
3521
3522     if(mov->reserved_moov_size){
3523         mov->reserved_moov_pos= avio_tell(pb);
3524         avio_skip(pb, mov->reserved_moov_size);
3525     }
3526
3527     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3528         mov_write_mdat_tag(pb, mov);
3529
3530     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
3531         mov->time = ff_iso8601_to_unix_time(t->value);
3532     if (mov->time)
3533         mov->time += 0x7C25B080; // 1970 based -> 1904 based
3534
3535     if (mov->chapter_track)
3536         mov_create_chapter_track(s, mov->chapter_track);
3537
3538     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
3539         /* Initialize the hint tracks for each audio and video stream */
3540         for (i = 0; i < s->nb_streams; i++) {
3541             AVStream *st = s->streams[i];
3542             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3543                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3544                 ff_mov_init_hinting(s, hint_track, i);
3545                 hint_track++;
3546             }
3547         }
3548     }
3549
3550     if (mov->nb_meta_tmcd) {
3551         /* Initialize the tmcd tracks */
3552         for (i = 0; i < s->nb_streams; i++) {
3553             AVStream *st = s->streams[i];
3554             t = global_tcr;
3555
3556             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3557                 if (!t)
3558                     t = av_dict_get(st->metadata, "timecode", NULL, 0);
3559                 if (!t)
3560                     continue;
3561                 if (mov_create_timecode_track(s, tmcd_track, i, t->value) < 0)
3562                     goto error;
3563                 tmcd_track++;
3564             }
3565         }
3566     }
3567
3568     avio_flush(pb);
3569
3570     if (mov->flags & FF_MOV_FLAG_ISML)
3571         mov_write_isml_manifest(pb, mov);
3572
3573     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3574         mov_write_moov_tag(pb, mov, s);
3575         mov->fragments++;
3576     }
3577
3578     return 0;
3579  error:
3580     av_freep(&mov->tracks);
3581     return -1;
3582 }
3583
3584 static int mov_write_trailer(AVFormatContext *s)
3585 {
3586     MOVMuxContext *mov = s->priv_data;
3587     AVIOContext *pb = s->pb;
3588     int64_t moov_pos;
3589     int res = 0;
3590     int i;
3591
3592     /*
3593      * Before actually writing the trailer, make sure that there are no
3594      * dangling subtitles, that need a terminating sample.
3595      */
3596     for (i = 0; i < mov->nb_streams; i++) {
3597         MOVTrack *trk = &mov->tracks[i];
3598         if (trk->enc->codec_id == CODEC_ID_MOV_TEXT &&
3599             !trk->last_sample_is_subtitle_end) {
3600             mov_write_subtitle_end_packet(s, i, trk->track_duration);
3601             trk->last_sample_is_subtitle_end = 1;
3602         }
3603     }
3604
3605     moov_pos = avio_tell(pb);
3606
3607     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
3608         /* Write size of mdat tag */
3609         if (mov->mdat_size + 8 <= UINT32_MAX) {
3610             avio_seek(pb, mov->mdat_pos, SEEK_SET);
3611             avio_wb32(pb, mov->mdat_size + 8);
3612         } else {
3613             /* overwrite 'wide' placeholder atom */
3614             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
3615             /* special value: real atom size will be 64 bit value after
3616              * tag field */
3617             avio_wb32(pb, 1);
3618             ffio_wfourcc(pb, "mdat");
3619             avio_wb64(pb, mov->mdat_size + 16);
3620         }
3621         avio_seek(pb, mov->reserved_moov_size ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
3622
3623         mov_write_moov_tag(pb, mov, s);
3624         if(mov->reserved_moov_size){
3625             int64_t size=  mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
3626             if(size < 8){
3627                 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
3628                 return -1;
3629             }
3630             avio_wb32(pb, size);
3631             ffio_wfourcc(pb, "free");
3632             for(i=0; i<size; i++)
3633                 avio_w8(pb, 0);
3634             avio_seek(pb, moov_pos, SEEK_SET);
3635         }
3636     } else {
3637         mov_flush_fragment(s);
3638         mov_write_mfra_tag(pb, mov);
3639     }
3640
3641     if (mov->chapter_track)
3642         av_freep(&mov->tracks[mov->chapter_track].enc);
3643
3644     for (i=0; i<mov->nb_streams; i++) {
3645         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
3646             ff_mov_close_hinting(&mov->tracks[i]);
3647         else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
3648             av_freep(&mov->tracks[i].enc);
3649         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
3650             mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
3651             int64_t off = avio_tell(pb);
3652             uint8_t buf[7];
3653             if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
3654                 avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
3655                 avio_write(pb, buf, 7);
3656                 avio_seek(pb, off, SEEK_SET);
3657             }
3658         }
3659         av_freep(&mov->tracks[i].cluster);
3660         av_freep(&mov->tracks[i].frag_info);
3661
3662         if (mov->tracks[i].vos_len)
3663             av_free(mov->tracks[i].vos_data);
3664
3665     }
3666
3667     avio_flush(pb);
3668
3669     av_freep(&mov->tracks);
3670
3671     return res;
3672 }
3673
3674 #if CONFIG_MOV_MUXER
3675 MOV_CLASS(mov)
3676 AVOutputFormat ff_mov_muxer = {
3677     .name              = "mov",
3678     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3679     .extensions        = "mov",
3680     .priv_data_size    = sizeof(MOVMuxContext),
3681     .audio_codec       = CODEC_ID_AAC,
3682     .video_codec       = CONFIG_LIBX264_ENCODER ?
3683                          CODEC_ID_H264 : CODEC_ID_MPEG4,
3684     .write_header      = mov_write_header,
3685     .write_packet      = mov_write_packet,
3686     .write_trailer     = mov_write_trailer,
3687     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
3688     .codec_tag         = (const AVCodecTag* const []){
3689         ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
3690     },
3691     .priv_class        = &mov_muxer_class,
3692 };
3693 #endif
3694 #if CONFIG_TGP_MUXER
3695 MOV_CLASS(tgp)
3696 AVOutputFormat ff_tgp_muxer = {
3697     .name              = "3gp",
3698     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
3699     .extensions        = "3gp",
3700     .priv_data_size    = sizeof(MOVMuxContext),
3701     .audio_codec       = CODEC_ID_AMR_NB,
3702     .video_codec       = CODEC_ID_H263,
3703     .write_header      = mov_write_header,
3704     .write_packet      = mov_write_packet,
3705     .write_trailer     = mov_write_trailer,
3706     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
3707     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
3708     .priv_class        = &tgp_muxer_class,
3709 };
3710 #endif
3711 #if CONFIG_MP4_MUXER
3712 MOV_CLASS(mp4)
3713 AVOutputFormat ff_mp4_muxer = {
3714     .name              = "mp4",
3715     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
3716     .mime_type         = "application/mp4",
3717     .extensions        = "mp4",
3718     .priv_data_size    = sizeof(MOVMuxContext),
3719     .audio_codec       = CODEC_ID_AAC,
3720     .video_codec       = CONFIG_LIBX264_ENCODER ?
3721                          CODEC_ID_H264 : CODEC_ID_MPEG4,
3722     .write_header      = mov_write_header,
3723     .write_packet      = mov_write_packet,
3724     .write_trailer     = mov_write_trailer,
3725     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
3726     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
3727     .priv_class        = &mp4_muxer_class,
3728 };
3729 #endif
3730 #if CONFIG_PSP_MUXER
3731 MOV_CLASS(psp)
3732 AVOutputFormat ff_psp_muxer = {
3733     .name              = "psp",
3734     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
3735     .extensions        = "mp4,psp",
3736     .priv_data_size    = sizeof(MOVMuxContext),
3737     .audio_codec       = CODEC_ID_AAC,
3738     .video_codec       = CONFIG_LIBX264_ENCODER ?
3739                          CODEC_ID_H264 : CODEC_ID_MPEG4,
3740     .write_header      = mov_write_header,
3741     .write_packet      = mov_write_packet,
3742     .write_trailer     = mov_write_trailer,
3743     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
3744     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
3745     .priv_class        = &psp_muxer_class,
3746 };
3747 #endif
3748 #if CONFIG_TG2_MUXER
3749 MOV_CLASS(tg2)
3750 AVOutputFormat ff_tg2_muxer = {
3751     .name              = "3g2",
3752     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
3753     .extensions        = "3g2",
3754     .priv_data_size    = sizeof(MOVMuxContext),
3755     .audio_codec       = CODEC_ID_AMR_NB,
3756     .video_codec       = CODEC_ID_H263,
3757     .write_header      = mov_write_header,
3758     .write_packet      = mov_write_packet,
3759     .write_trailer     = mov_write_trailer,
3760     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
3761     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
3762     .priv_class        = &tg2_muxer_class,
3763 };
3764 #endif
3765 #if CONFIG_IPOD_MUXER
3766 MOV_CLASS(ipod)
3767 AVOutputFormat ff_ipod_muxer = {
3768     .name              = "ipod",
3769     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
3770     .mime_type         = "application/mp4",
3771     .extensions        = "m4v,m4a",
3772     .priv_data_size    = sizeof(MOVMuxContext),
3773     .audio_codec       = CODEC_ID_AAC,
3774     .video_codec       = CODEC_ID_H264,
3775     .write_header      = mov_write_header,
3776     .write_packet      = mov_write_packet,
3777     .write_trailer     = mov_write_trailer,
3778     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
3779     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
3780     .priv_class        = &ipod_muxer_class,
3781 };
3782 #endif
3783 #if CONFIG_ISMV_MUXER
3784 MOV_CLASS(ismv)
3785 AVOutputFormat ff_ismv_muxer = {
3786     .name              = "ismv",
3787     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
3788     .mime_type         = "application/mp4",
3789     .extensions        = "ismv,isma",
3790     .priv_data_size    = sizeof(MOVMuxContext),
3791     .audio_codec       = CODEC_ID_AAC,
3792     .video_codec       = CODEC_ID_H264,
3793     .write_header      = mov_write_header,
3794     .write_packet      = mov_write_packet,
3795     .write_trailer     = mov_write_trailer,
3796     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
3797     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
3798     .priv_class        = &ismv_muxer_class,
3799 };
3800 #endif