]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
pthread: do not touch has_b_frames
[ffmpeg] / libavformat / movenc.c
1 /*
2  * MOV, 3GP, MP4 muxer
3  * Copyright (c) 2003 Thomas Raivio
4  * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6  *
7  * This file is part of Libav.
8  *
9  * Libav is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * Libav is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with Libav; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include "movenc.h"
25 #include "avformat.h"
26 #include "avio_internal.h"
27 #include "riff.h"
28 #include "avio.h"
29 #include "isom.h"
30 #include "avc.h"
31 #include "libavcodec/get_bits.h"
32 #include "libavcodec/put_bits.h"
33 #include "internal.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/intfloat_readwrite.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/dict.h"
39 #include "rtpenc.h"
40
41 #undef NDEBUG
42 #include <assert.h>
43
44 static const AVOption options[] = {
45     { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.dbl = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
46     { "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" },
47     FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
48     { NULL },
49 };
50
51 #define MOV_CLASS(flavor)\
52 static const AVClass flavor ## _muxer_class = {\
53     .class_name = #flavor " muxer",\
54     .item_name  = av_default_item_name,\
55     .option     = options,\
56     .version    = LIBAVUTIL_VERSION_INT,\
57 };
58
59 //FIXME support 64 bit variant with wide placeholders
60 static int64_t updateSize(AVIOContext *pb, int64_t pos)
61 {
62     int64_t curpos = avio_tell(pb);
63     avio_seek(pb, pos, SEEK_SET);
64     avio_wb32(pb, curpos - pos); /* rewrite size */
65     avio_seek(pb, curpos, SEEK_SET);
66
67     return curpos - pos;
68 }
69
70 /* Chunk offset atom */
71 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
72 {
73     int i;
74     int mode64 = 0; //   use 32 bit size variant if possible
75     int64_t pos = avio_tell(pb);
76     avio_wb32(pb, 0); /* size */
77     if (pos > UINT32_MAX) {
78         mode64 = 1;
79         ffio_wfourcc(pb, "co64");
80     } else
81         ffio_wfourcc(pb, "stco");
82     avio_wb32(pb, 0); /* version & flags */
83     avio_wb32(pb, track->entry); /* entry count */
84     for (i=0; i<track->entry; i++) {
85         if(mode64 == 1)
86             avio_wb64(pb, track->cluster[i].pos);
87         else
88             avio_wb32(pb, track->cluster[i].pos);
89     }
90     return updateSize(pb, pos);
91 }
92
93 /* Sample size atom */
94 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
95 {
96     int equalChunks = 1;
97     int i, j, entries = 0, tst = -1, oldtst = -1;
98
99     int64_t pos = avio_tell(pb);
100     avio_wb32(pb, 0); /* size */
101     ffio_wfourcc(pb, "stsz");
102     avio_wb32(pb, 0); /* version & flags */
103
104     for (i=0; i<track->entry; i++) {
105         tst = track->cluster[i].size/track->cluster[i].entries;
106         if(oldtst != -1 && tst != oldtst) {
107             equalChunks = 0;
108         }
109         oldtst = tst;
110         entries += track->cluster[i].entries;
111     }
112     if (equalChunks) {
113         int sSize = track->cluster[0].size/track->cluster[0].entries;
114         sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
115         avio_wb32(pb, sSize); // sample size
116         avio_wb32(pb, entries); // sample count
117     }
118     else {
119         avio_wb32(pb, 0); // sample size
120         avio_wb32(pb, entries); // sample count
121         for (i=0; i<track->entry; i++) {
122             for (j=0; j<track->cluster[i].entries; j++) {
123                 avio_wb32(pb, track->cluster[i].size /
124                          track->cluster[i].entries);
125             }
126         }
127     }
128     return updateSize(pb, pos);
129 }
130
131 /* Sample to chunk atom */
132 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
133 {
134     int index = 0, oldval = -1, i;
135     int64_t entryPos, curpos;
136
137     int64_t pos = avio_tell(pb);
138     avio_wb32(pb, 0); /* size */
139     ffio_wfourcc(pb, "stsc");
140     avio_wb32(pb, 0); // version & flags
141     entryPos = avio_tell(pb);
142     avio_wb32(pb, track->entry); // entry count
143     for (i=0; i<track->entry; i++) {
144         if(oldval != track->cluster[i].samplesInChunk)
145         {
146             avio_wb32(pb, i+1); // first chunk
147             avio_wb32(pb, track->cluster[i].samplesInChunk); // samples per chunk
148             avio_wb32(pb, 0x1); // sample description index
149             oldval = track->cluster[i].samplesInChunk;
150             index++;
151         }
152     }
153     curpos = avio_tell(pb);
154     avio_seek(pb, entryPos, SEEK_SET);
155     avio_wb32(pb, index); // rewrite size
156     avio_seek(pb, curpos, SEEK_SET);
157
158     return updateSize(pb, pos);
159 }
160
161 /* Sync sample atom */
162 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
163 {
164     int64_t curpos, entryPos;
165     int i, index = 0;
166     int64_t pos = avio_tell(pb);
167     avio_wb32(pb, 0); // size
168     ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
169     avio_wb32(pb, 0); // version & flags
170     entryPos = avio_tell(pb);
171     avio_wb32(pb, track->entry); // entry count
172     for (i=0; i<track->entry; i++) {
173         if (track->cluster[i].flags & flag) {
174             avio_wb32(pb, i+1);
175             index++;
176         }
177     }
178     curpos = avio_tell(pb);
179     avio_seek(pb, entryPos, SEEK_SET);
180     avio_wb32(pb, index); // rewrite size
181     avio_seek(pb, curpos, SEEK_SET);
182     return updateSize(pb, pos);
183 }
184
185 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
186 {
187     avio_wb32(pb, 0x11); /* size */
188     if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
189     else                         ffio_wfourcc(pb, "damr");
190     ffio_wfourcc(pb, "FFMP");
191     avio_w8(pb, 0); /* decoder version */
192
193     avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
194     avio_w8(pb, 0x00); /* Mode change period (no restriction) */
195     avio_w8(pb, 0x01); /* Frames per sample */
196     return 0x11;
197 }
198
199 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
200 {
201     GetBitContext gbc;
202     PutBitContext pbc;
203     uint8_t buf[3];
204     int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
205
206     if (track->vosLen < 7)
207         return -1;
208
209     avio_wb32(pb, 11);
210     ffio_wfourcc(pb, "dac3");
211
212     init_get_bits(&gbc, track->vosData+4, (track->vosLen-4) * 8);
213     fscod      = get_bits(&gbc, 2);
214     frmsizecod = get_bits(&gbc, 6);
215     bsid       = get_bits(&gbc, 5);
216     bsmod      = get_bits(&gbc, 3);
217     acmod      = get_bits(&gbc, 3);
218     if (acmod == 2) {
219         skip_bits(&gbc, 2); // dsurmod
220     } else {
221         if ((acmod & 1) && acmod != 1)
222             skip_bits(&gbc, 2); // cmixlev
223         if (acmod & 4)
224             skip_bits(&gbc, 2); // surmixlev
225     }
226     lfeon = get_bits1(&gbc);
227
228     init_put_bits(&pbc, buf, sizeof(buf));
229     put_bits(&pbc, 2, fscod);
230     put_bits(&pbc, 5, bsid);
231     put_bits(&pbc, 3, bsmod);
232     put_bits(&pbc, 3, acmod);
233     put_bits(&pbc, 1, lfeon);
234     put_bits(&pbc, 5, frmsizecod>>1); // bit_rate_code
235     put_bits(&pbc, 5, 0); // reserved
236
237     flush_put_bits(&pbc);
238     avio_write(pb, buf, sizeof(buf));
239
240     return 11;
241 }
242
243 /**
244  * This function writes extradata "as is".
245  * Extradata must be formated like a valid atom (with size and tag)
246  */
247 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
248 {
249     avio_write(pb, track->enc->extradata, track->enc->extradata_size);
250     return track->enc->extradata_size;
251 }
252
253 static int mov_write_enda_tag(AVIOContext *pb)
254 {
255     avio_wb32(pb, 10);
256     ffio_wfourcc(pb, "enda");
257     avio_wb16(pb, 1); /* little endian */
258     return 10;
259 }
260
261 static void putDescr(AVIOContext *pb, int tag, unsigned int size)
262 {
263     int i = 3;
264     avio_w8(pb, tag);
265     for(; i>0; i--)
266         avio_w8(pb, (size>>(7*i)) | 0x80);
267     avio_w8(pb, size & 0x7F);
268 }
269
270 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
271 {
272     int64_t pos = avio_tell(pb);
273     int decoderSpecificInfoLen = track->vosLen ? 5+track->vosLen : 0;
274
275     avio_wb32(pb, 0); // size
276     ffio_wfourcc(pb, "esds");
277     avio_wb32(pb, 0); // Version
278
279     // ES descriptor
280     putDescr(pb, 0x03, 3 + 5+13 + decoderSpecificInfoLen + 5+1);
281     avio_wb16(pb, track->trackID);
282     avio_w8(pb, 0x00); // flags (= no flags)
283
284     // DecoderConfig descriptor
285     putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
286
287     // Object type indication
288     if ((track->enc->codec_id == CODEC_ID_MP2 ||
289          track->enc->codec_id == CODEC_ID_MP3) &&
290         track->enc->sample_rate > 24000)
291         avio_w8(pb, 0x6B); // 11172-3
292     else
293         avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
294
295     // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
296     // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
297     if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
298         avio_w8(pb, 0x15); // flags (= Audiostream)
299     else
300         avio_w8(pb, 0x11); // flags (= Visualstream)
301
302     avio_w8(pb,  track->enc->rc_buffer_size>>(3+16));      // Buffersize DB (24 bits)
303     avio_wb16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
304
305     avio_wb32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
306     if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
307         avio_wb32(pb, 0); // vbr
308     else
309         avio_wb32(pb, track->enc->rc_max_rate); // avg bitrate
310
311     if (track->vosLen) {
312         // DecoderSpecific info descriptor
313         putDescr(pb, 0x05, track->vosLen);
314         avio_write(pb, track->vosData, track->vosLen);
315     }
316
317     // SL descriptor
318     putDescr(pb, 0x06, 1);
319     avio_w8(pb, 0x02);
320     return updateSize(pb, pos);
321 }
322
323 static int mov_pcm_le_gt16(enum CodecID codec_id)
324 {
325     return codec_id == CODEC_ID_PCM_S24LE ||
326            codec_id == CODEC_ID_PCM_S32LE ||
327            codec_id == CODEC_ID_PCM_F32LE ||
328            codec_id == CODEC_ID_PCM_F64LE;
329 }
330
331 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
332 {
333     int64_t pos = avio_tell(pb);
334     avio_wb32(pb, 0);
335     avio_wl32(pb, track->tag); // store it byteswapped
336     track->enc->codec_tag = av_bswap16(track->tag >> 16);
337     ff_put_wav_header(pb, track->enc);
338     return updateSize(pb, pos);
339 }
340
341 static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
342 {
343     int64_t pos = avio_tell(pb);
344
345     avio_wb32(pb, 0);     /* size */
346     ffio_wfourcc(pb, "wave");
347
348     avio_wb32(pb, 12);    /* size */
349     ffio_wfourcc(pb, "frma");
350     avio_wl32(pb, track->tag);
351
352     if (track->enc->codec_id == CODEC_ID_AAC) {
353         /* useless atom needed by mplayer, ipod, not needed by quicktime */
354         avio_wb32(pb, 12); /* size */
355         ffio_wfourcc(pb, "mp4a");
356         avio_wb32(pb, 0);
357         mov_write_esds_tag(pb, track);
358     } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
359         mov_write_enda_tag(pb);
360     } else if (track->enc->codec_id == CODEC_ID_AMR_NB) {
361         mov_write_amr_tag(pb, track);
362     } else if (track->enc->codec_id == CODEC_ID_AC3) {
363         mov_write_ac3_tag(pb, track);
364     } else if (track->enc->codec_id == CODEC_ID_ALAC) {
365         mov_write_extradata_tag(pb, track);
366     } else if (track->enc->codec_id == CODEC_ID_ADPCM_MS ||
367                track->enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
368         mov_write_ms_tag(pb, track);
369     }
370
371     avio_wb32(pb, 8);     /* size */
372     avio_wb32(pb, 0);     /* null tag */
373
374     return updateSize(pb, pos);
375 }
376
377 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
378 {
379     avio_wb32(pb, track->vosLen+8);
380     ffio_wfourcc(pb, "glbl");
381     avio_write(pb, track->vosData, track->vosLen);
382     return 8+track->vosLen;
383 }
384
385 /**
386  * Compute flags for 'lpcm' tag.
387  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
388  */
389 static int mov_get_lpcm_flags(enum CodecID codec_id)
390 {
391     switch (codec_id) {
392     case CODEC_ID_PCM_F32BE:
393     case CODEC_ID_PCM_F64BE:
394         return 11;
395     case CODEC_ID_PCM_F32LE:
396     case CODEC_ID_PCM_F64LE:
397         return 9;
398     case CODEC_ID_PCM_U8:
399         return 10;
400     case CODEC_ID_PCM_S16BE:
401     case CODEC_ID_PCM_S24BE:
402     case CODEC_ID_PCM_S32BE:
403         return 14;
404     case CODEC_ID_PCM_S8:
405     case CODEC_ID_PCM_S16LE:
406     case CODEC_ID_PCM_S24LE:
407     case CODEC_ID_PCM_S32LE:
408         return 12;
409     default:
410         return 0;
411     }
412 }
413
414 static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
415 {
416     int64_t pos = avio_tell(pb);
417     int version = 0;
418     uint32_t tag = track->tag;
419
420     if (track->mode == MODE_MOV) {
421         if (track->timescale > UINT16_MAX) {
422             if (mov_get_lpcm_flags(track->enc->codec_id))
423                 tag = AV_RL32("lpcm");
424             version = 2;
425         } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
426                    track->enc->codec_id == CODEC_ID_ADPCM_MS ||
427                    track->enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
428             version = 1;
429         }
430     }
431
432     avio_wb32(pb, 0); /* size */
433     avio_wl32(pb, tag); // store it byteswapped
434     avio_wb32(pb, 0); /* Reserved */
435     avio_wb16(pb, 0); /* Reserved */
436     avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */
437
438     /* SoundDescription */
439     avio_wb16(pb, version); /* Version */
440     avio_wb16(pb, 0); /* Revision level */
441     avio_wb32(pb, 0); /* Reserved */
442
443     if (version == 2) {
444         avio_wb16(pb, 3);
445         avio_wb16(pb, 16);
446         avio_wb16(pb, 0xfffe);
447         avio_wb16(pb, 0);
448         avio_wb32(pb, 0x00010000);
449         avio_wb32(pb, 72);
450         avio_wb64(pb, av_dbl2int(track->timescale));
451         avio_wb32(pb, track->enc->channels);
452         avio_wb32(pb, 0x7F000000);
453         avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
454         avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
455         avio_wb32(pb, track->sampleSize);
456         avio_wb32(pb, track->enc->frame_size);
457     } else {
458         if (track->mode == MODE_MOV) {
459             avio_wb16(pb, track->enc->channels);
460             if (track->enc->codec_id == CODEC_ID_PCM_U8 ||
461                 track->enc->codec_id == CODEC_ID_PCM_S8)
462                 avio_wb16(pb, 8); /* bits per sample */
463             else
464                 avio_wb16(pb, 16);
465             avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
466         } else { /* reserved for mp4/3gp */
467             avio_wb16(pb, 2);
468             avio_wb16(pb, 16);
469             avio_wb16(pb, 0);
470         }
471
472         avio_wb16(pb, 0); /* packet size (= 0) */
473         avio_wb16(pb, track->timescale); /* Time scale */
474         avio_wb16(pb, 0); /* Reserved */
475     }
476
477     if(version == 1) { /* SoundDescription V1 extended info */
478         avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
479         avio_wb32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
480         avio_wb32(pb, track->sampleSize); /* Bytes per frame */
481         avio_wb32(pb, 2); /* Bytes per sample */
482     }
483
484     if(track->mode == MODE_MOV &&
485        (track->enc->codec_id == CODEC_ID_AAC ||
486         track->enc->codec_id == CODEC_ID_AC3 ||
487         track->enc->codec_id == CODEC_ID_AMR_NB ||
488         track->enc->codec_id == CODEC_ID_ALAC ||
489         track->enc->codec_id == CODEC_ID_ADPCM_MS ||
490         track->enc->codec_id == CODEC_ID_ADPCM_IMA_WAV ||
491         mov_pcm_le_gt16(track->enc->codec_id)))
492         mov_write_wave_tag(pb, track);
493     else if(track->tag == MKTAG('m','p','4','a'))
494         mov_write_esds_tag(pb, track);
495     else if(track->enc->codec_id == CODEC_ID_AMR_NB)
496         mov_write_amr_tag(pb, track);
497     else if(track->enc->codec_id == CODEC_ID_AC3)
498         mov_write_ac3_tag(pb, track);
499     else if(track->enc->codec_id == CODEC_ID_ALAC)
500         mov_write_extradata_tag(pb, track);
501     else if(track->vosLen > 0)
502         mov_write_glbl_tag(pb, track);
503
504     return updateSize(pb, pos);
505 }
506
507 static int mov_write_d263_tag(AVIOContext *pb)
508 {
509     avio_wb32(pb, 0xf); /* size */
510     ffio_wfourcc(pb, "d263");
511     ffio_wfourcc(pb, "FFMP");
512     avio_w8(pb, 0); /* decoder version */
513     /* FIXME use AVCodecContext level/profile, when encoder will set values */
514     avio_w8(pb, 0xa); /* level */
515     avio_w8(pb, 0); /* profile */
516     return 0xf;
517 }
518
519 /* TODO: No idea about these values */
520 static int mov_write_svq3_tag(AVIOContext *pb)
521 {
522     avio_wb32(pb, 0x15);
523     ffio_wfourcc(pb, "SMI ");
524     ffio_wfourcc(pb, "SEQH");
525     avio_wb32(pb, 0x5);
526     avio_wb32(pb, 0xe2c0211d);
527     avio_wb32(pb, 0xc0000000);
528     avio_w8(pb, 0);
529     return 0x15;
530 }
531
532 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
533 {
534     int64_t pos = avio_tell(pb);
535
536     avio_wb32(pb, 0);
537     ffio_wfourcc(pb, "avcC");
538     ff_isom_write_avcc(pb, track->vosData, track->vosLen);
539     return updateSize(pb, pos);
540 }
541
542 /* also used by all avid codecs (dv, imx, meridien) and their variants */
543 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
544 {
545     int i;
546     avio_wb32(pb, 24); /* size */
547     ffio_wfourcc(pb, "ACLR");
548     ffio_wfourcc(pb, "ACLR");
549     ffio_wfourcc(pb, "0001");
550     avio_wb32(pb, 2); /* yuv range: full 1 / normal 2 */
551     avio_wb32(pb, 0); /* unknown */
552
553     avio_wb32(pb, 24); /* size */
554     ffio_wfourcc(pb, "APRG");
555     ffio_wfourcc(pb, "APRG");
556     ffio_wfourcc(pb, "0001");
557     avio_wb32(pb, 1); /* unknown */
558     avio_wb32(pb, 0); /* unknown */
559
560     avio_wb32(pb, 120); /* size */
561     ffio_wfourcc(pb, "ARES");
562     ffio_wfourcc(pb, "ARES");
563     ffio_wfourcc(pb, "0001");
564     avio_wb32(pb, AV_RB32(track->vosData + 0x28)); /* dnxhd cid, some id ? */
565     avio_wb32(pb, track->enc->width);
566     /* values below are based on samples created with quicktime and avid codecs */
567     if (track->vosData[5] & 2) { // interlaced
568         avio_wb32(pb, track->enc->height/2);
569         avio_wb32(pb, 2); /* unknown */
570         avio_wb32(pb, 0); /* unknown */
571         avio_wb32(pb, 4); /* unknown */
572     } else {
573         avio_wb32(pb, track->enc->height);
574         avio_wb32(pb, 1); /* unknown */
575         avio_wb32(pb, 0); /* unknown */
576         if (track->enc->height == 1080)
577             avio_wb32(pb, 5); /* unknown */
578         else
579             avio_wb32(pb, 6); /* unknown */
580     }
581     /* padding */
582     for (i = 0; i < 10; i++)
583         avio_wb64(pb, 0);
584
585     /* extra padding for stsd needed */
586     avio_wb32(pb, 0);
587     return 0;
588 }
589
590 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
591 {
592     int tag = track->enc->codec_tag;
593
594     if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
595         return 0;
596
597     if      (track->enc->codec_id == CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
598     else if (track->enc->codec_id == CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
599     else if (track->enc->codec_id == CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
600     else if (track->enc->codec_id == CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
601     else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
602     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
603
604     return tag;
605 }
606
607 static const AVCodecTag codec_ipod_tags[] = {
608     { CODEC_ID_H264,   MKTAG('a','v','c','1') },
609     { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
610     { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
611     { CODEC_ID_ALAC,   MKTAG('a','l','a','c') },
612     { CODEC_ID_AC3,    MKTAG('a','c','-','3') },
613     { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
614     { CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
615     { CODEC_ID_NONE, 0 },
616 };
617
618 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
619 {
620     int tag = track->enc->codec_tag;
621
622     // keep original tag for subs, ipod supports both formats
623     if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
624         (tag == MKTAG('t','x','3','g') ||
625          tag == MKTAG('t','e','x','t'))))
626         tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
627
628     if (!av_match_ext(s->filename, "m4a") && !av_match_ext(s->filename, "m4v"))
629         av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
630                "Quicktime/Ipod might not play the file\n");
631
632     return tag;
633 }
634
635 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
636 {
637     int tag;
638
639     if (track->enc->width == 720) /* SD */
640         if (track->enc->height == 480) /* NTSC */
641             if  (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
642             else                                         tag = MKTAG('d','v','c',' ');
643         else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
644         else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
645         else                                             tag = MKTAG('d','v','p','p');
646     else if (track->enc->height == 720) /* HD 720 line */
647         if  (track->enc->time_base.den == 50)            tag = MKTAG('d','v','h','q');
648         else                                             tag = MKTAG('d','v','h','p');
649     else if (track->enc->height == 1080) /* HD 1080 line */
650         if  (track->enc->time_base.den == 25)            tag = MKTAG('d','v','h','5');
651         else                                             tag = MKTAG('d','v','h','6');
652     else {
653         av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
654         return 0;
655     }
656
657     return tag;
658 }
659
660 static const struct {
661     enum PixelFormat pix_fmt;
662     uint32_t tag;
663     unsigned bps;
664 } mov_pix_fmt_tags[] = {
665     { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
666     { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
667     { PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
668     { PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
669     { PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
670     { PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
671     { PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
672     { PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
673     { PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
674     { PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
675     { PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
676     { PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
677     { PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
678     { PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
679 };
680
681 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
682 {
683     int tag = track->enc->codec_tag;
684     int i;
685
686     for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
687         if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
688             tag = mov_pix_fmt_tags[i].tag;
689             track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
690             break;
691         }
692     }
693
694     return tag;
695 }
696
697 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
698 {
699     int tag = track->enc->codec_tag;
700
701     if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
702                  (track->enc->codec_id == CODEC_ID_DVVIDEO ||
703                   track->enc->codec_id == CODEC_ID_RAWVIDEO ||
704                   track->enc->codec_id == CODEC_ID_H263 ||
705                   av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
706         if (track->enc->codec_id == CODEC_ID_DVVIDEO)
707             tag = mov_get_dv_codec_tag(s, track);
708         else if (track->enc->codec_id == CODEC_ID_RAWVIDEO)
709             tag = mov_get_rawvideo_codec_tag(s, track);
710         else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
711             tag = ff_codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
712             if (!tag) { // if no mac fcc found, try with Microsoft tags
713                 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
714                 if (tag)
715                     av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
716                            "the file may be unplayable!\n");
717             }
718         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
719             tag = ff_codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
720             if (!tag) { // if no mac fcc found, try with Microsoft tags
721                 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
722                 if (ms_tag) {
723                     tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
724                     av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
725                            "the file may be unplayable!\n");
726                 }
727             }
728         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
729             tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
730     }
731
732     return tag;
733 }
734
735 static const AVCodecTag codec_3gp_tags[] = {
736     { CODEC_ID_H263,   MKTAG('s','2','6','3') },
737     { CODEC_ID_H264,   MKTAG('a','v','c','1') },
738     { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
739     { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
740     { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
741     { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
742     { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
743     { CODEC_ID_NONE, 0 },
744 };
745
746 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
747 {
748     int tag = track->enc->codec_tag;
749
750     if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
751         tag = mp4_get_codec_tag(s, track);
752     else if (track->mode == MODE_IPOD)
753         tag = ipod_get_codec_tag(s, track);
754     else if (track->mode & MODE_3GP)
755         tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
756     else
757         tag = mov_get_codec_tag(s, track);
758
759     return tag;
760 }
761
762 /** Write uuid atom.
763  * Needed to make file play in iPods running newest firmware
764  * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
765  */
766 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
767 {
768     avio_wb32(pb, 28);
769     ffio_wfourcc(pb, "uuid");
770     avio_wb32(pb, 0x6b6840f2);
771     avio_wb32(pb, 0x5f244fc5);
772     avio_wb32(pb, 0xba39a51b);
773     avio_wb32(pb, 0xcf0323f3);
774     avio_wb32(pb, 0x0);
775     return 28;
776 }
777
778 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
779 {
780     int64_t pos = avio_tell(pb);
781     avio_wb32(pb, 0);    /* size */
782     avio_wl32(pb, track->tag); // store it byteswapped
783     avio_wb32(pb, 0);    /* Reserved */
784     avio_wb16(pb, 0);    /* Reserved */
785     avio_wb16(pb, 1);    /* Data-reference index */
786
787     if (track->enc->extradata_size)
788         avio_write(pb, track->enc->extradata, track->enc->extradata_size);
789
790     return updateSize(pb, pos);
791 }
792
793 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
794 {
795     AVRational sar;
796     av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
797               track->enc->sample_aspect_ratio.den, INT_MAX);
798
799     avio_wb32(pb, 16);
800     ffio_wfourcc(pb, "pasp");
801     avio_wb32(pb, sar.num);
802     avio_wb32(pb, sar.den);
803     return 16;
804 }
805
806 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
807 {
808     int64_t pos = avio_tell(pb);
809     char compressor_name[32];
810
811     avio_wb32(pb, 0); /* size */
812     avio_wl32(pb, track->tag); // store it byteswapped
813     avio_wb32(pb, 0); /* Reserved */
814     avio_wb16(pb, 0); /* Reserved */
815     avio_wb16(pb, 1); /* Data-reference index */
816
817     avio_wb16(pb, 0); /* Codec stream version */
818     avio_wb16(pb, 0); /* Codec stream revision (=0) */
819     if (track->mode == MODE_MOV) {
820         ffio_wfourcc(pb, "FFMP"); /* Vendor */
821         if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
822             avio_wb32(pb, 0); /* Temporal Quality */
823             avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
824         } else {
825             avio_wb32(pb, 0x200); /* Temporal Quality = normal */
826             avio_wb32(pb, 0x200); /* Spatial Quality = normal */
827         }
828     } else {
829         avio_wb32(pb, 0); /* Reserved */
830         avio_wb32(pb, 0); /* Reserved */
831         avio_wb32(pb, 0); /* Reserved */
832     }
833     avio_wb16(pb, track->enc->width); /* Video width */
834     avio_wb16(pb, track->height); /* Video height */
835     avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
836     avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
837     avio_wb32(pb, 0); /* Data size (= 0) */
838     avio_wb16(pb, 1); /* Frame count (= 1) */
839
840     memset(compressor_name,0,32);
841     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
842     if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
843         av_strlcpy(compressor_name,track->enc->codec->name,32);
844     avio_w8(pb, strlen(compressor_name));
845     avio_write(pb, compressor_name, 31);
846
847     if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
848         avio_wb16(pb, track->enc->bits_per_coded_sample);
849     else
850         avio_wb16(pb, 0x18); /* Reserved */
851     avio_wb16(pb, 0xffff); /* Reserved */
852     if(track->tag == MKTAG('m','p','4','v'))
853         mov_write_esds_tag(pb, track);
854     else if(track->enc->codec_id == CODEC_ID_H263)
855         mov_write_d263_tag(pb);
856     else if(track->enc->codec_id == CODEC_ID_SVQ3)
857         mov_write_svq3_tag(pb);
858     else if(track->enc->codec_id == CODEC_ID_DNXHD)
859         mov_write_avid_tag(pb, track);
860     else if(track->enc->codec_id == CODEC_ID_H264) {
861         mov_write_avcc_tag(pb, track);
862         if(track->mode == MODE_IPOD)
863             mov_write_uuid_tag_ipod(pb);
864     } else if(track->vosLen > 0)
865         mov_write_glbl_tag(pb, track);
866
867     if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
868         track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
869         mov_write_pasp_tag(pb, track);
870     }
871
872     return updateSize(pb, pos);
873 }
874
875 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
876 {
877     int64_t pos = avio_tell(pb);
878     avio_wb32(pb, 0); /* size */
879     ffio_wfourcc(pb, "rtp ");
880     avio_wb32(pb, 0); /* Reserved */
881     avio_wb16(pb, 0); /* Reserved */
882     avio_wb16(pb, 1); /* Data-reference index */
883
884     avio_wb16(pb, 1); /* Hint track version */
885     avio_wb16(pb, 1); /* Highest compatible version */
886     avio_wb32(pb, track->max_packet_size); /* Max packet size */
887
888     avio_wb32(pb, 12); /* size */
889     ffio_wfourcc(pb, "tims");
890     avio_wb32(pb, track->timescale);
891
892     return updateSize(pb, pos);
893 }
894
895 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
896 {
897     int64_t pos = avio_tell(pb);
898     avio_wb32(pb, 0); /* size */
899     ffio_wfourcc(pb, "stsd");
900     avio_wb32(pb, 0); /* version & flags */
901     avio_wb32(pb, 1); /* entry count */
902     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
903         mov_write_video_tag(pb, track);
904     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
905         mov_write_audio_tag(pb, track);
906     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
907         mov_write_subtitle_tag(pb, track);
908     else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
909         mov_write_rtp_tag(pb, track);
910     return updateSize(pb, pos);
911 }
912
913 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
914 {
915     MOVStts *ctts_entries;
916     uint32_t entries = 0;
917     uint32_t atom_size;
918     int i;
919
920     ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
921     ctts_entries[0].count = 1;
922     ctts_entries[0].duration = track->cluster[0].cts;
923     for (i=1; i<track->entry; i++) {
924         if (track->cluster[i].cts == ctts_entries[entries].duration) {
925             ctts_entries[entries].count++; /* compress */
926         } else {
927             entries++;
928             ctts_entries[entries].duration = track->cluster[i].cts;
929             ctts_entries[entries].count = 1;
930         }
931     }
932     entries++; /* last one */
933     atom_size = 16 + (entries * 8);
934     avio_wb32(pb, atom_size); /* size */
935     ffio_wfourcc(pb, "ctts");
936     avio_wb32(pb, 0); /* version & flags */
937     avio_wb32(pb, entries); /* entry count */
938     for (i=0; i<entries; i++) {
939         avio_wb32(pb, ctts_entries[i].count);
940         avio_wb32(pb, ctts_entries[i].duration);
941     }
942     av_free(ctts_entries);
943     return atom_size;
944 }
945
946 /* Time to sample atom */
947 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
948 {
949     MOVStts *stts_entries;
950     uint32_t entries = -1;
951     uint32_t atom_size;
952     int i;
953
954     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
955         stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
956         stts_entries[0].count = track->sampleCount;
957         stts_entries[0].duration = 1;
958         entries = 1;
959     } else {
960         stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
961         for (i=0; i<track->entry; i++) {
962             int64_t duration = i + 1 == track->entry ?
963                 track->trackDuration - track->cluster[i].dts + track->cluster[0].dts : /* readjusting */
964                 track->cluster[i+1].dts - track->cluster[i].dts;
965             if (i && duration == stts_entries[entries].duration) {
966                 stts_entries[entries].count++; /* compress */
967             } else {
968                 entries++;
969                 stts_entries[entries].duration = duration;
970                 stts_entries[entries].count = 1;
971             }
972         }
973         entries++; /* last one */
974     }
975     atom_size = 16 + (entries * 8);
976     avio_wb32(pb, atom_size); /* size */
977     ffio_wfourcc(pb, "stts");
978     avio_wb32(pb, 0); /* version & flags */
979     avio_wb32(pb, entries); /* entry count */
980     for (i=0; i<entries; i++) {
981         avio_wb32(pb, stts_entries[i].count);
982         avio_wb32(pb, stts_entries[i].duration);
983     }
984     av_free(stts_entries);
985     return atom_size;
986 }
987
988 static int mov_write_dref_tag(AVIOContext *pb)
989 {
990     avio_wb32(pb, 28); /* size */
991     ffio_wfourcc(pb, "dref");
992     avio_wb32(pb, 0); /* version & flags */
993     avio_wb32(pb, 1); /* entry count */
994
995     avio_wb32(pb, 0xc); /* size */
996     ffio_wfourcc(pb, "url ");
997     avio_wb32(pb, 1); /* version & flags */
998
999     return 28;
1000 }
1001
1002 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1003 {
1004     int64_t pos = avio_tell(pb);
1005     avio_wb32(pb, 0); /* size */
1006     ffio_wfourcc(pb, "stbl");
1007     mov_write_stsd_tag(pb, track);
1008     mov_write_stts_tag(pb, track);
1009     if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1010          track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1011         track->hasKeyframes && track->hasKeyframes < track->entry)
1012         mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1013     if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1014         mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1015     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1016         track->flags & MOV_TRACK_CTTS)
1017         mov_write_ctts_tag(pb, track);
1018     mov_write_stsc_tag(pb, track);
1019     mov_write_stsz_tag(pb, track);
1020     mov_write_stco_tag(pb, track);
1021     return updateSize(pb, pos);
1022 }
1023
1024 static int mov_write_dinf_tag(AVIOContext *pb)
1025 {
1026     int64_t pos = avio_tell(pb);
1027     avio_wb32(pb, 0); /* size */
1028     ffio_wfourcc(pb, "dinf");
1029     mov_write_dref_tag(pb);
1030     return updateSize(pb, pos);
1031 }
1032
1033 static int mov_write_nmhd_tag(AVIOContext *pb)
1034 {
1035     avio_wb32(pb, 12);
1036     ffio_wfourcc(pb, "nmhd");
1037     avio_wb32(pb, 0);
1038     return 12;
1039 }
1040
1041 static int mov_write_gmhd_tag(AVIOContext *pb)
1042 {
1043     avio_wb32(pb, 0x20);   /* size */
1044     ffio_wfourcc(pb, "gmhd");
1045     avio_wb32(pb, 0x18);   /* gmin size */
1046     ffio_wfourcc(pb, "gmin");/* generic media info */
1047     avio_wb32(pb, 0);      /* version & flags */
1048     avio_wb16(pb, 0x40);   /* graphics mode = */
1049     avio_wb16(pb, 0x8000); /* opColor (r?) */
1050     avio_wb16(pb, 0x8000); /* opColor (g?) */
1051     avio_wb16(pb, 0x8000); /* opColor (b?) */
1052     avio_wb16(pb, 0);      /* balance */
1053     avio_wb16(pb, 0);      /* reserved */
1054     return 0x20;
1055 }
1056
1057 static int mov_write_smhd_tag(AVIOContext *pb)
1058 {
1059     avio_wb32(pb, 16); /* size */
1060     ffio_wfourcc(pb, "smhd");
1061     avio_wb32(pb, 0); /* version & flags */
1062     avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1063     avio_wb16(pb, 0); /* reserved */
1064     return 16;
1065 }
1066
1067 static int mov_write_vmhd_tag(AVIOContext *pb)
1068 {
1069     avio_wb32(pb, 0x14); /* size (always 0x14) */
1070     ffio_wfourcc(pb, "vmhd");
1071     avio_wb32(pb, 0x01); /* version & flags */
1072     avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1073     return 0x14;
1074 }
1075
1076 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1077 {
1078     const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1079     int64_t pos = avio_tell(pb);
1080
1081     if (!track) { /* no media --> data handler */
1082         hdlr = "dhlr";
1083         hdlr_type = "url ";
1084         descr = "DataHandler";
1085     } else {
1086         hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1087         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1088             hdlr_type = "vide";
1089             descr = "VideoHandler";
1090         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1091             hdlr_type = "soun";
1092             descr = "SoundHandler";
1093         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1094             if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
1095             else                                      hdlr_type = "text";
1096             descr = "SubtitleHandler";
1097         } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1098             hdlr_type = "hint";
1099             descr = "HintHandler";
1100         }
1101     }
1102
1103     avio_wb32(pb, 0); /* size */
1104     ffio_wfourcc(pb, "hdlr");
1105     avio_wb32(pb, 0); /* Version & flags */
1106     avio_write(pb, hdlr, 4); /* handler */
1107     ffio_wfourcc(pb, hdlr_type); /* handler type */
1108     avio_wb32(pb ,0); /* reserved */
1109     avio_wb32(pb ,0); /* reserved */
1110     avio_wb32(pb ,0); /* reserved */
1111     if (!track || track->mode == MODE_MOV)
1112         avio_w8(pb, strlen(descr)); /* pascal string */
1113     avio_write(pb, descr, strlen(descr)); /* handler description */
1114     if (track && track->mode != MODE_MOV)
1115         avio_w8(pb, 0); /* c string */
1116     return updateSize(pb, pos);
1117 }
1118
1119 static int mov_write_hmhd_tag(AVIOContext *pb)
1120 {
1121     /* This atom must be present, but leaving the values at zero
1122      * seems harmless. */
1123     avio_wb32(pb, 28); /* size */
1124     ffio_wfourcc(pb, "hmhd");
1125     avio_wb32(pb, 0); /* version, flags */
1126     avio_wb16(pb, 0); /* maxPDUsize */
1127     avio_wb16(pb, 0); /* avgPDUsize */
1128     avio_wb32(pb, 0); /* maxbitrate */
1129     avio_wb32(pb, 0); /* avgbitrate */
1130     avio_wb32(pb, 0); /* reserved */
1131     return 28;
1132 }
1133
1134 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1135 {
1136     int64_t pos = avio_tell(pb);
1137     avio_wb32(pb, 0); /* size */
1138     ffio_wfourcc(pb, "minf");
1139     if(track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1140         mov_write_vmhd_tag(pb);
1141     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1142         mov_write_smhd_tag(pb);
1143     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1144         if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb);
1145         else                                      mov_write_nmhd_tag(pb);
1146     } else if (track->tag == MKTAG('r','t','p',' ')) {
1147         mov_write_hmhd_tag(pb);
1148     }
1149     if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1150         mov_write_hdlr_tag(pb, NULL);
1151     mov_write_dinf_tag(pb);
1152     mov_write_stbl_tag(pb, track);
1153     return updateSize(pb, pos);
1154 }
1155
1156 static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1157 {
1158     int version = track->trackDuration < INT32_MAX ? 0 : 1;
1159
1160     (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1161     ffio_wfourcc(pb, "mdhd");
1162     avio_w8(pb, version);
1163     avio_wb24(pb, 0); /* flags */
1164     if (version == 1) {
1165         avio_wb64(pb, track->time);
1166         avio_wb64(pb, track->time);
1167     } else {
1168         avio_wb32(pb, track->time); /* creation time */
1169         avio_wb32(pb, track->time); /* modification time */
1170     }
1171     avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1172     (version == 1) ? avio_wb64(pb, track->trackDuration) : avio_wb32(pb, track->trackDuration); /* duration */
1173     avio_wb16(pb, track->language); /* language */
1174     avio_wb16(pb, 0); /* reserved (quality) */
1175
1176     if(version!=0 && track->mode == MODE_MOV){
1177         av_log(NULL, AV_LOG_ERROR,
1178             "FATAL error, file duration too long for timebase, this file will not be\n"
1179             "playable with quicktime. Choose a different timebase or a different\n"
1180             "container format\n");
1181     }
1182
1183     return 32;
1184 }
1185
1186 static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1187 {
1188     int64_t pos = avio_tell(pb);
1189     avio_wb32(pb, 0); /* size */
1190     ffio_wfourcc(pb, "mdia");
1191     mov_write_mdhd_tag(pb, track);
1192     mov_write_hdlr_tag(pb, track);
1193     mov_write_minf_tag(pb, track);
1194     return updateSize(pb, pos);
1195 }
1196
1197 static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1198 {
1199     int64_t duration = av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1200                                       track->timescale, AV_ROUND_UP);
1201     int version = duration < INT32_MAX ? 0 : 1;
1202
1203     (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1204     ffio_wfourcc(pb, "tkhd");
1205     avio_w8(pb, version);
1206     avio_wb24(pb, 0xf); /* flags (track enabled) */
1207     if (version == 1) {
1208         avio_wb64(pb, track->time);
1209         avio_wb64(pb, track->time);
1210     } else {
1211         avio_wb32(pb, track->time); /* creation time */
1212         avio_wb32(pb, track->time); /* modification time */
1213     }
1214     avio_wb32(pb, track->trackID); /* track-id */
1215     avio_wb32(pb, 0); /* reserved */
1216     (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1217
1218     avio_wb32(pb, 0); /* reserved */
1219     avio_wb32(pb, 0); /* reserved */
1220     avio_wb16(pb, 0); /* layer */
1221     avio_wb16(pb, st ? st->codec->codec_type : 0); /* alternate group) */
1222     /* Volume, only for audio */
1223     if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1224         avio_wb16(pb, 0x0100);
1225     else
1226         avio_wb16(pb, 0);
1227     avio_wb16(pb, 0); /* reserved */
1228
1229     /* Matrix structure */
1230     avio_wb32(pb, 0x00010000); /* reserved */
1231     avio_wb32(pb, 0x0); /* reserved */
1232     avio_wb32(pb, 0x0); /* reserved */
1233     avio_wb32(pb, 0x0); /* reserved */
1234     avio_wb32(pb, 0x00010000); /* reserved */
1235     avio_wb32(pb, 0x0); /* reserved */
1236     avio_wb32(pb, 0x0); /* reserved */
1237     avio_wb32(pb, 0x0); /* reserved */
1238     avio_wb32(pb, 0x40000000); /* reserved */
1239
1240     /* Track width and height, for visual only */
1241     if(st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1242               track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1243         if(track->mode == MODE_MOV) {
1244             avio_wb32(pb, track->enc->width << 16);
1245             avio_wb32(pb, track->height << 16);
1246         } else {
1247             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1248             if(!sample_aspect_ratio || track->height != track->enc->height)
1249                 sample_aspect_ratio = 1;
1250             avio_wb32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1251             avio_wb32(pb, track->height*0x10000);
1252         }
1253     }
1254     else {
1255         avio_wb32(pb, 0);
1256         avio_wb32(pb, 0);
1257     }
1258     return 0x5c;
1259 }
1260
1261 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1262 {
1263     int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1264                                track->enc->sample_aspect_ratio.den);
1265
1266     int64_t pos = avio_tell(pb);
1267
1268     avio_wb32(pb, 0); /* size */
1269     ffio_wfourcc(pb, "tapt");
1270
1271     avio_wb32(pb, 20);
1272     ffio_wfourcc(pb, "clef");
1273     avio_wb32(pb, 0);
1274     avio_wb32(pb, width << 16);
1275     avio_wb32(pb, track->enc->height << 16);
1276
1277     avio_wb32(pb, 20);
1278     ffio_wfourcc(pb, "enof");
1279     avio_wb32(pb, 0);
1280     avio_wb32(pb, track->enc->width << 16);
1281     avio_wb32(pb, track->enc->height << 16);
1282
1283     return updateSize(pb, pos);
1284 };
1285
1286 // This box seems important for the psp playback ... without it the movie seems to hang
1287 static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1288 {
1289     int64_t duration = av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1290                                       track->timescale, AV_ROUND_UP);
1291     int version = duration < INT32_MAX ? 0 : 1;
1292     int entry_size, entry_count, size;
1293     int64_t delay, start_ct = track->cluster[0].cts;
1294     delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
1295                            track->timescale, AV_ROUND_DOWN);
1296     version |= delay < INT32_MAX ? 0 : 1;
1297
1298     entry_size = (version == 1) ? 20 : 12;
1299     entry_count = 1 + (delay > 0);
1300     size = 24 + entry_count * entry_size;
1301
1302     /* write the atom data */
1303     avio_wb32(pb, size);
1304     ffio_wfourcc(pb, "edts");
1305     avio_wb32(pb, size - 8);
1306     ffio_wfourcc(pb, "elst");
1307     avio_w8(pb, version);
1308     avio_wb24(pb, 0); /* flags */
1309
1310     avio_wb32(pb, entry_count);
1311     if (delay > 0) { /* add an empty edit to delay presentation */
1312         if (version == 1) {
1313             avio_wb64(pb, delay);
1314             avio_wb64(pb, -1);
1315         } else {
1316             avio_wb32(pb, delay);
1317             avio_wb32(pb, -1);
1318         }
1319         avio_wb32(pb, 0x00010000);
1320     }
1321
1322     /* duration */
1323     if (version == 1) {
1324         avio_wb64(pb, duration);
1325         avio_wb64(pb, start_ct);
1326     } else {
1327         avio_wb32(pb, duration);
1328         avio_wb32(pb, start_ct);
1329     }
1330     avio_wb32(pb, 0x00010000);
1331     return size;
1332 }
1333
1334 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1335 {
1336     avio_wb32(pb, 20);   // size
1337     ffio_wfourcc(pb, "tref");
1338     avio_wb32(pb, 12);   // size (subatom)
1339     avio_wl32(pb, track->tref_tag);
1340     avio_wb32(pb, track->tref_id);
1341     return 20;
1342 }
1343
1344 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1345 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1346 {
1347     avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1348     ffio_wfourcc(pb, "uuid");
1349     ffio_wfourcc(pb, "USMT");
1350     avio_wb32(pb, 0x21d24fce);
1351     avio_wb32(pb, 0xbb88695c);
1352     avio_wb32(pb, 0xfac9c740);
1353     avio_wb32(pb, 0x1c);     // another size here!
1354     ffio_wfourcc(pb, "MTDT");
1355     avio_wb32(pb, 0x00010012);
1356     avio_wb32(pb, 0x0a);
1357     avio_wb32(pb, 0x55c40000);
1358     avio_wb32(pb, 0x1);
1359     avio_wb32(pb, 0x0);
1360     return 0x34;
1361 }
1362
1363 static int mov_write_udta_sdp(AVIOContext *pb, AVFormatContext *ctx, int index)
1364 {
1365     char buf[1000] = "";
1366     int len;
1367
1368     ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0]->codec, NULL, NULL, 0, 0, ctx);
1369     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", index);
1370     len = strlen(buf);
1371
1372     avio_wb32(pb, len + 24);
1373     ffio_wfourcc(pb, "udta");
1374     avio_wb32(pb, len + 16);
1375     ffio_wfourcc(pb, "hnti");
1376     avio_wb32(pb, len + 8);
1377     ffio_wfourcc(pb, "sdp ");
1378     avio_write(pb, buf, len);
1379     return len + 24;
1380 }
1381
1382 static int mov_write_trak_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1383 {
1384     int64_t pos = avio_tell(pb);
1385     avio_wb32(pb, 0); /* size */
1386     ffio_wfourcc(pb, "trak");
1387     mov_write_tkhd_tag(pb, track, st);
1388     if (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS || track->cluster[0].dts)
1389         mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1390     if (track->tref_tag)
1391         mov_write_tref_tag(pb, track);
1392     mov_write_mdia_tag(pb, track);
1393     if (track->mode == MODE_PSP)
1394         mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1395     if (track->tag == MKTAG('r','t','p',' '))
1396         mov_write_udta_sdp(pb, track->rtp_ctx, track->trackID);
1397     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO && track->mode == MODE_MOV) {
1398         double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1399         if (0.0 != sample_aspect_ratio && 1.0 != sample_aspect_ratio)
1400             mov_write_tapt_tag(pb, track);
1401     };
1402     return updateSize(pb, pos);
1403 }
1404
1405 #if 0
1406 /* TODO: Not sorted out, but not necessary either */
1407 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1408 {
1409     avio_wb32(pb, 0x15); /* size */
1410     ffio_wfourcc(pb, "iods");
1411     avio_wb32(pb, 0);    /* version & flags */
1412     avio_wb16(pb, 0x1007);
1413     avio_w8(pb, 0);
1414     avio_wb16(pb, 0x4fff);
1415     avio_wb16(pb, 0xfffe);
1416     avio_wb16(pb, 0x01ff);
1417     return 0x15;
1418 }
1419 #endif
1420
1421 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
1422 {
1423     int maxTrackID = 1, i;
1424     int64_t maxTrackLenTemp, maxTrackLen = 0;
1425     int version;
1426
1427     for (i=0; i<mov->nb_streams; i++) {
1428         if(mov->tracks[i].entry > 0) {
1429             maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration,
1430                                              MOV_TIMESCALE,
1431                                              mov->tracks[i].timescale,
1432                                              AV_ROUND_UP);
1433             if(maxTrackLen < maxTrackLenTemp)
1434                 maxTrackLen = maxTrackLenTemp;
1435             if(maxTrackID < mov->tracks[i].trackID)
1436                 maxTrackID = mov->tracks[i].trackID;
1437         }
1438     }
1439
1440     version = maxTrackLen < UINT32_MAX ? 0 : 1;
1441     (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
1442     ffio_wfourcc(pb, "mvhd");
1443     avio_w8(pb, version);
1444     avio_wb24(pb, 0); /* flags */
1445     if (version == 1) {
1446         avio_wb64(pb, mov->time);
1447         avio_wb64(pb, mov->time);
1448     } else {
1449         avio_wb32(pb, mov->time); /* creation time */
1450         avio_wb32(pb, mov->time); /* modification time */
1451     }
1452     avio_wb32(pb, MOV_TIMESCALE);
1453     (version == 1) ? avio_wb64(pb, maxTrackLen) : avio_wb32(pb, maxTrackLen); /* duration of longest track */
1454
1455     avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1456     avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1457     avio_wb16(pb, 0); /* reserved */
1458     avio_wb32(pb, 0); /* reserved */
1459     avio_wb32(pb, 0); /* reserved */
1460
1461     /* Matrix structure */
1462     avio_wb32(pb, 0x00010000); /* reserved */
1463     avio_wb32(pb, 0x0); /* reserved */
1464     avio_wb32(pb, 0x0); /* reserved */
1465     avio_wb32(pb, 0x0); /* reserved */
1466     avio_wb32(pb, 0x00010000); /* reserved */
1467     avio_wb32(pb, 0x0); /* reserved */
1468     avio_wb32(pb, 0x0); /* reserved */
1469     avio_wb32(pb, 0x0); /* reserved */
1470     avio_wb32(pb, 0x40000000); /* reserved */
1471
1472     avio_wb32(pb, 0); /* reserved (preview time) */
1473     avio_wb32(pb, 0); /* reserved (preview duration) */
1474     avio_wb32(pb, 0); /* reserved (poster time) */
1475     avio_wb32(pb, 0); /* reserved (selection time) */
1476     avio_wb32(pb, 0); /* reserved (selection duration) */
1477     avio_wb32(pb, 0); /* reserved (current time) */
1478     avio_wb32(pb, maxTrackID+1); /* Next track id */
1479     return 0x6c;
1480 }
1481
1482 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
1483                                      AVFormatContext *s)
1484 {
1485     avio_wb32(pb, 33); /* size */
1486     ffio_wfourcc(pb, "hdlr");
1487     avio_wb32(pb, 0);
1488     avio_wb32(pb, 0);
1489     ffio_wfourcc(pb, "mdir");
1490     ffio_wfourcc(pb, "appl");
1491     avio_wb32(pb, 0);
1492     avio_wb32(pb, 0);
1493     avio_w8(pb, 0);
1494     return 33;
1495 }
1496
1497 /* helper function to write a data tag with the specified string as data */
1498 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
1499 {
1500     if(long_style){
1501         int size = 16 + strlen(data);
1502         avio_wb32(pb, size); /* size */
1503         ffio_wfourcc(pb, "data");
1504         avio_wb32(pb, 1);
1505         avio_wb32(pb, 0);
1506         avio_write(pb, data, strlen(data));
1507         return size;
1508     }else{
1509         if (!lang)
1510             lang = ff_mov_iso639_to_lang("und", 1);
1511         avio_wb16(pb, strlen(data)); /* string length */
1512         avio_wb16(pb, lang);
1513         avio_write(pb, data, strlen(data));
1514         return strlen(data) + 4;
1515     }
1516 }
1517
1518 static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style){
1519     int size = 0;
1520     if (value && value[0]) {
1521         int64_t pos = avio_tell(pb);
1522         avio_wb32(pb, 0); /* size */
1523         ffio_wfourcc(pb, name);
1524         mov_write_string_data_tag(pb, value, lang, long_style);
1525         size= updateSize(pb, pos);
1526     }
1527     return size;
1528 }
1529
1530 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
1531                                      const char *name, const char *tag,
1532                                      int long_style)
1533 {
1534     int l, lang = 0, len, len2;
1535     AVDictionaryEntry *t, *t2 = NULL;
1536     char tag2[16];
1537
1538     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
1539         return 0;
1540
1541     len = strlen(t->key);
1542     snprintf(tag2, sizeof(tag2), "%s-", tag);
1543     while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
1544         len2 = strlen(t2->key);
1545         if (len2 == len+4 && !strcmp(t->value, t2->value)
1546             && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 1)) >= 0) {
1547             lang = l;
1548             break;
1549         }
1550     }
1551     return mov_write_string_tag(pb, name, t->value, lang, long_style);
1552 }
1553
1554 /* iTunes track number */
1555 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
1556                               AVFormatContext *s)
1557 {
1558     AVDictionaryEntry *t = av_dict_get(s->metadata, "track", NULL, 0);
1559     int size = 0, track = t ? atoi(t->value) : 0;
1560     if (track) {
1561         avio_wb32(pb, 32); /* size */
1562         ffio_wfourcc(pb, "trkn");
1563             avio_wb32(pb, 24); /* size */
1564             ffio_wfourcc(pb, "data");
1565             avio_wb32(pb, 0);        // 8 bytes empty
1566             avio_wb32(pb, 0);
1567             avio_wb16(pb, 0);        // empty
1568             avio_wb16(pb, track);    // track number
1569             avio_wb16(pb, 0);        // total track number
1570             avio_wb16(pb, 0);        // empty
1571         size = 32;
1572     }
1573     return size;
1574 }
1575
1576 /* iTunes meta data list */
1577 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
1578                               AVFormatContext *s)
1579 {
1580     int64_t pos = avio_tell(pb);
1581     avio_wb32(pb, 0); /* size */
1582     ffio_wfourcc(pb, "ilst");
1583     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1584     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
1585     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
1586     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1587     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1588     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
1589     mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1590     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1591     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1592     mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1593     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
1594     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
1595     mov_write_string_metadata(s, pb, "desc",    "description",1);
1596     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
1597     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
1598     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
1599     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
1600     mov_write_trkn_tag(pb, mov, s);
1601     return updateSize(pb, pos);
1602 }
1603
1604 /* iTunes meta data tag */
1605 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
1606                               AVFormatContext *s)
1607 {
1608     int size = 0;
1609     int64_t pos = avio_tell(pb);
1610     avio_wb32(pb, 0); /* size */
1611     ffio_wfourcc(pb, "meta");
1612     avio_wb32(pb, 0);
1613     mov_write_itunes_hdlr_tag(pb, mov, s);
1614     mov_write_ilst_tag(pb, mov, s);
1615     size = updateSize(pb, pos);
1616     return size;
1617 }
1618
1619 static int utf8len(const uint8_t *b)
1620 {
1621     int len=0;
1622     int val;
1623     while(*b){
1624         GET_UTF8(val, *b++, return -1;)
1625         len++;
1626     }
1627     return len;
1628 }
1629
1630 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
1631 {
1632     int val;
1633     while(*b){
1634         GET_UTF8(val, *b++, return -1;)
1635         avio_wb16(pb, val);
1636     }
1637     avio_wb16(pb, 0x00);
1638     return 0;
1639 }
1640
1641 static uint16_t language_code(const char *str)
1642 {
1643     return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1644 }
1645
1646 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
1647                                   const char *tag, const char *str)
1648 {
1649     int64_t pos = avio_tell(pb);
1650     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
1651     if (!t || !utf8len(t->value))
1652         return 0;
1653     avio_wb32(pb, 0);   /* size */
1654     ffio_wfourcc(pb, tag); /* type */
1655     avio_wb32(pb, 0);   /* version + flags */
1656     if (!strcmp(tag, "yrrc"))
1657         avio_wb16(pb, atoi(t->value));
1658     else {
1659         avio_wb16(pb, language_code("eng")); /* language */
1660         avio_write(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
1661         if (!strcmp(tag, "albm") &&
1662             (t = av_dict_get(s->metadata, "track", NULL, 0)))
1663             avio_w8(pb, atoi(t->value));
1664     }
1665     return updateSize(pb, pos);
1666 }
1667
1668 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
1669 {
1670     int64_t pos = avio_tell(pb);
1671     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
1672
1673     avio_wb32(pb, 0);            // size
1674     ffio_wfourcc(pb, "chpl");
1675     avio_wb32(pb, 0x01000000);   // version + flags
1676     avio_wb32(pb, 0);            // unknown
1677     avio_w8(pb, nb_chapters);
1678
1679     for (i = 0; i < nb_chapters; i++) {
1680         AVChapter *c = s->chapters[i];
1681         AVDictionaryEntry *t;
1682         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
1683
1684         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1685             int len = FFMIN(strlen(t->value), 255);
1686             avio_w8(pb, len);
1687             avio_write(pb, t->value, len);
1688         } else
1689             avio_w8(pb, 0);
1690     }
1691     return updateSize(pb, pos);
1692 }
1693
1694 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
1695                               AVFormatContext *s)
1696 {
1697     AVIOContext *pb_buf;
1698     int i, ret, size;
1699     uint8_t *buf;
1700
1701     for (i = 0; i < s->nb_streams; i++)
1702         if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1703             return 0;
1704         }
1705
1706     ret = avio_open_dyn_buf(&pb_buf);
1707     if(ret < 0)
1708         return ret;
1709
1710         if (mov->mode & MODE_3GP) {
1711             mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
1712             mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1713             mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1714             mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1715             mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1716             mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1717             mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1718             mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
1719         } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1720             mov_write_string_metadata(s, pb_buf, "\251ART", "artist"     , 0);
1721             mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
1722             mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
1723             mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
1724             mov_write_string_metadata(s, pb_buf, "\251day", "date"       , 0);
1725             mov_write_string_metadata(s, pb_buf, "\251swr", "encoder"    , 0);
1726             mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
1727             mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
1728             mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
1729         } else {
1730             /* iTunes meta data */
1731             mov_write_meta_tag(pb_buf, mov, s);
1732         }
1733
1734         if (s->nb_chapters)
1735             mov_write_chpl_tag(pb_buf, s);
1736
1737     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
1738         avio_wb32(pb, size+8);
1739         ffio_wfourcc(pb, "udta");
1740         avio_write(pb, buf, size);
1741     }
1742     av_free(buf);
1743
1744     return 0;
1745 }
1746
1747 static void mov_write_psp_udta_tag(AVIOContext *pb,
1748                                   const char *str, const char *lang, int type)
1749 {
1750     int len = utf8len(str)+1;
1751     if(len<=0)
1752         return;
1753     avio_wb16(pb, len*2+10);            /* size */
1754     avio_wb32(pb, type);                /* type */
1755     avio_wb16(pb, language_code(lang)); /* language */
1756     avio_wb16(pb, 0x01);                /* ? */
1757     ascii_to_wc(pb, str);
1758 }
1759
1760 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
1761 {
1762     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
1763     int64_t pos, pos2;
1764
1765     if (title) {
1766         pos = avio_tell(pb);
1767         avio_wb32(pb, 0); /* size placeholder*/
1768         ffio_wfourcc(pb, "uuid");
1769         ffio_wfourcc(pb, "USMT");
1770         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
1771         avio_wb32(pb, 0xbb88695c);
1772         avio_wb32(pb, 0xfac9c740);
1773
1774         pos2 = avio_tell(pb);
1775         avio_wb32(pb, 0); /* size placeholder*/
1776         ffio_wfourcc(pb, "MTDT");
1777         avio_wb16(pb, 4);
1778
1779         // ?
1780         avio_wb16(pb, 0x0C);                 /* size */
1781         avio_wb32(pb, 0x0B);                 /* type */
1782         avio_wb16(pb, language_code("und")); /* language */
1783         avio_wb16(pb, 0x0);                  /* ? */
1784         avio_wb16(pb, 0x021C);               /* data */
1785
1786         mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1787         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1788 //        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);
1789         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1790
1791         updateSize(pb, pos2);
1792         return updateSize(pb, pos);
1793     }
1794
1795     return 0;
1796 }
1797
1798 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
1799                               AVFormatContext *s)
1800 {
1801     int i;
1802     int64_t pos = avio_tell(pb);
1803     avio_wb32(pb, 0); /* size placeholder*/
1804     ffio_wfourcc(pb, "moov");
1805
1806     for (i=0; i<mov->nb_streams; i++) {
1807         if(mov->tracks[i].entry <= 0) continue;
1808
1809         mov->tracks[i].time = mov->time;
1810         mov->tracks[i].trackID = i+1;
1811     }
1812
1813     if (mov->chapter_track)
1814         for (i=0; i<s->nb_streams; i++) {
1815             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
1816             mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].trackID;
1817         }
1818     for (i = 0; i < mov->nb_streams; i++) {
1819         if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
1820             mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
1821             mov->tracks[i].tref_id =
1822                 mov->tracks[mov->tracks[i].src_track].trackID;
1823         }
1824     }
1825
1826     mov_write_mvhd_tag(pb, mov);
1827     //mov_write_iods_tag(pb, mov);
1828     for (i=0; i<mov->nb_streams; i++) {
1829         if(mov->tracks[i].entry > 0) {
1830             mov_write_trak_tag(pb, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
1831         }
1832     }
1833
1834     if (mov->mode == MODE_PSP)
1835         mov_write_uuidusmt_tag(pb, s);
1836     else
1837         mov_write_udta_tag(pb, mov, s);
1838
1839     return updateSize(pb, pos);
1840 }
1841
1842 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
1843 {
1844     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
1845     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
1846
1847     mov->mdat_pos = avio_tell(pb);
1848     avio_wb32(pb, 0); /* size placeholder*/
1849     ffio_wfourcc(pb, "mdat");
1850     return 0;
1851 }
1852
1853 /* TODO: This needs to be more general */
1854 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
1855 {
1856     MOVMuxContext *mov = s->priv_data;
1857     int64_t pos = avio_tell(pb);
1858     int has_h264 = 0, has_video = 0;
1859     int minor = 0x200;
1860     int i;
1861
1862     for (i = 0; i < s->nb_streams; i++) {
1863         AVStream *st = s->streams[i];
1864         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1865             has_video = 1;
1866         if (st->codec->codec_id == CODEC_ID_H264)
1867             has_h264 = 1;
1868     }
1869
1870     avio_wb32(pb, 0); /* size */
1871     ffio_wfourcc(pb, "ftyp");
1872
1873     if (mov->mode == MODE_3GP) {
1874         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
1875         minor =     has_h264 ?   0x100 :   0x200;
1876     } else if (mov->mode & MODE_3G2) {
1877         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
1878         minor =     has_h264 ? 0x20000 : 0x10000;
1879     }else if (mov->mode == MODE_PSP)
1880         ffio_wfourcc(pb, "MSNV");
1881     else if (mov->mode == MODE_MP4)
1882         ffio_wfourcc(pb, "isom");
1883     else if (mov->mode == MODE_IPOD)
1884         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
1885     else
1886         ffio_wfourcc(pb, "qt  ");
1887
1888     avio_wb32(pb, minor);
1889
1890     if(mov->mode == MODE_MOV)
1891         ffio_wfourcc(pb, "qt  ");
1892     else{
1893         ffio_wfourcc(pb, "isom");
1894         ffio_wfourcc(pb, "iso2");
1895         if(has_h264)
1896             ffio_wfourcc(pb, "avc1");
1897     }
1898
1899     if (mov->mode == MODE_3GP)
1900         ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
1901     else if (mov->mode & MODE_3G2)
1902         ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
1903     else if (mov->mode == MODE_PSP)
1904         ffio_wfourcc(pb, "MSNV");
1905     else if (mov->mode == MODE_MP4)
1906         ffio_wfourcc(pb, "mp41");
1907     return updateSize(pb, pos);
1908 }
1909
1910 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
1911 {
1912     AVCodecContext *VideoCodec = s->streams[0]->codec;
1913     AVCodecContext *AudioCodec = s->streams[1]->codec;
1914     int AudioRate = AudioCodec->sample_rate;
1915     int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1916     int audio_kbitrate= AudioCodec->bit_rate / 1000;
1917     int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1918
1919     avio_wb32(pb, 0x94); /* size */
1920     ffio_wfourcc(pb, "uuid");
1921     ffio_wfourcc(pb, "PROF");
1922
1923     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
1924     avio_wb32(pb, 0xbb88695c);
1925     avio_wb32(pb, 0xfac9c740);
1926
1927     avio_wb32(pb, 0x0);  /* ? */
1928     avio_wb32(pb, 0x3);  /* 3 sections ? */
1929
1930     avio_wb32(pb, 0x14); /* size */
1931     ffio_wfourcc(pb, "FPRF");
1932     avio_wb32(pb, 0x0);  /* ? */
1933     avio_wb32(pb, 0x0);  /* ? */
1934     avio_wb32(pb, 0x0);  /* ? */
1935
1936     avio_wb32(pb, 0x2c);  /* size */
1937     ffio_wfourcc(pb, "APRF");/* audio */
1938     avio_wb32(pb, 0x0);
1939     avio_wb32(pb, 0x2);   /* TrackID */
1940     ffio_wfourcc(pb, "mp4a");
1941     avio_wb32(pb, 0x20f);
1942     avio_wb32(pb, 0x0);
1943     avio_wb32(pb, audio_kbitrate);
1944     avio_wb32(pb, audio_kbitrate);
1945     avio_wb32(pb, AudioRate);
1946     avio_wb32(pb, AudioCodec->channels);
1947
1948     avio_wb32(pb, 0x34);  /* size */
1949     ffio_wfourcc(pb, "VPRF");   /* video */
1950     avio_wb32(pb, 0x0);
1951     avio_wb32(pb, 0x1);    /* TrackID */
1952     if (VideoCodec->codec_id == CODEC_ID_H264) {
1953         ffio_wfourcc(pb, "avc1");
1954         avio_wb16(pb, 0x014D);
1955         avio_wb16(pb, 0x0015);
1956     } else {
1957         ffio_wfourcc(pb, "mp4v");
1958         avio_wb16(pb, 0x0000);
1959         avio_wb16(pb, 0x0103);
1960     }
1961     avio_wb32(pb, 0x0);
1962     avio_wb32(pb, video_kbitrate);
1963     avio_wb32(pb, video_kbitrate);
1964     avio_wb32(pb, FrameRate);
1965     avio_wb32(pb, FrameRate);
1966     avio_wb16(pb, VideoCodec->width);
1967     avio_wb16(pb, VideoCodec->height);
1968     avio_wb32(pb, 0x010001); /* ? */
1969 }
1970
1971 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
1972 {
1973     uint32_t c = -1;
1974     int i, closed_gop = 0;
1975
1976     for (i = 0; i < pkt->size - 4; i++) {
1977         c = (c<<8) + pkt->data[i];
1978         if (c == 0x1b8) { // gop
1979             closed_gop = pkt->data[i+4]>>6 & 0x01;
1980         } else if (c == 0x100) { // pic
1981             int temp_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
1982             if (!temp_ref || closed_gop) // I picture is not reordered
1983                 *flags = MOV_SYNC_SAMPLE;
1984             else
1985                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
1986             break;
1987         }
1988     }
1989     return 0;
1990 }
1991
1992 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1993 {
1994     MOVMuxContext *mov = s->priv_data;
1995     AVIOContext *pb = s->pb;
1996     MOVTrack *trk = &mov->tracks[pkt->stream_index];
1997     AVCodecContext *enc = trk->enc;
1998     unsigned int samplesInChunk = 0;
1999     int size= pkt->size;
2000
2001     if (!s->pb->seekable) return 0; /* Can't handle that */
2002     if (!size) return 0; /* Discard 0 sized packets */
2003
2004     if (enc->codec_id == CODEC_ID_AMR_NB) {
2005         /* We must find out how many AMR blocks there are in one packet */
2006         static uint16_t packed_size[16] =
2007             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
2008         int len = 0;
2009
2010         while (len < size && samplesInChunk < 100) {
2011             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
2012             samplesInChunk++;
2013         }
2014         if(samplesInChunk > 1){
2015             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
2016             return -1;
2017         }
2018     } else if (enc->codec_id == CODEC_ID_ADPCM_MS ||
2019                enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
2020         samplesInChunk = enc->frame_size;
2021     } else if (trk->sampleSize)
2022         samplesInChunk = size/trk->sampleSize;
2023     else
2024         samplesInChunk = 1;
2025
2026     /* copy extradata if it exists */
2027     if (trk->vosLen == 0 && enc->extradata_size > 0) {
2028         trk->vosLen = enc->extradata_size;
2029         trk->vosData = av_malloc(trk->vosLen);
2030         memcpy(trk->vosData, enc->extradata, trk->vosLen);
2031     }
2032
2033     if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
2034         /* from x264 or from bytestream h264 */
2035         /* nal reformating needed */
2036         size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
2037     } else {
2038         avio_write(pb, pkt->data, size);
2039     }
2040
2041     if ((enc->codec_id == CODEC_ID_DNXHD ||
2042          enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
2043         /* copy frame to create needed atoms */
2044         trk->vosLen = size;
2045         trk->vosData = av_malloc(size);
2046         if (!trk->vosData)
2047             return AVERROR(ENOMEM);
2048         memcpy(trk->vosData, pkt->data, size);
2049     }
2050
2051     if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
2052         trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
2053         if (!trk->cluster)
2054             return -1;
2055     }
2056
2057     trk->cluster[trk->entry].pos = avio_tell(pb) - size;
2058     trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
2059     trk->cluster[trk->entry].size = size;
2060     trk->cluster[trk->entry].entries = samplesInChunk;
2061     trk->cluster[trk->entry].dts = pkt->dts;
2062     trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
2063
2064     if (pkt->pts == AV_NOPTS_VALUE) {
2065         av_log(s, AV_LOG_WARNING, "pts has no value\n");
2066         pkt->pts = pkt->dts;
2067     }
2068     if (pkt->dts != pkt->pts)
2069         trk->flags |= MOV_TRACK_CTTS;
2070     trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
2071     trk->cluster[trk->entry].flags = 0;
2072     if (pkt->flags & AV_PKT_FLAG_KEY) {
2073         if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO &&
2074             trk->entry > 0) { // force sync sample for the first key frame
2075             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
2076             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
2077                 trk->flags |= MOV_TRACK_STPS;
2078         } else {
2079             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
2080         }
2081         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
2082             trk->hasKeyframes++;
2083     }
2084     trk->entry++;
2085     trk->sampleCount += samplesInChunk;
2086     mov->mdat_size += size;
2087
2088     avio_flush(pb);
2089
2090     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
2091         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry);
2092     return 0;
2093 }
2094
2095 // QuickTime chapters involve an additional text track with the chapter names
2096 // as samples, and a tref pointing from the other tracks to the chapter one.
2097 static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
2098 {
2099     MOVMuxContext *mov = s->priv_data;
2100     MOVTrack *track = &mov->tracks[tracknum];
2101     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
2102     int i, len;
2103
2104     track->mode = mov->mode;
2105     track->tag = MKTAG('t','e','x','t');
2106     track->timescale = MOV_TIMESCALE;
2107     track->enc = avcodec_alloc_context3(NULL);
2108     track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
2109
2110     for (i = 0; i < s->nb_chapters; i++) {
2111         AVChapter *c = s->chapters[i];
2112         AVDictionaryEntry *t;
2113
2114         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
2115         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
2116         pkt.duration = end - pkt.dts;
2117
2118         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2119             len = strlen(t->value);
2120             pkt.size = len+2;
2121             pkt.data = av_malloc(pkt.size);
2122             AV_WB16(pkt.data, len);
2123             memcpy(pkt.data+2, t->value, len);
2124             ff_mov_write_packet(s, &pkt);
2125             av_freep(&pkt.data);
2126         }
2127     }
2128 }
2129
2130 static int mov_write_header(AVFormatContext *s)
2131 {
2132     AVIOContext *pb = s->pb;
2133     MOVMuxContext *mov = s->priv_data;
2134     AVDictionaryEntry *t;
2135     int i, hint_track = 0;
2136
2137     if (!s->pb->seekable) {
2138         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
2139         return -1;
2140     }
2141
2142     /* Default mode == MP4 */
2143     mov->mode = MODE_MP4;
2144
2145     if (s->oformat != NULL) {
2146         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
2147         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
2148         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
2149         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
2150         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
2151
2152         mov_write_ftyp_tag(pb,s);
2153         if (mov->mode == MODE_PSP) {
2154             if (s->nb_streams != 2) {
2155                 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
2156                 return -1;
2157             }
2158             mov_write_uuidprof_tag(pb,s);
2159         }
2160     }
2161
2162     mov->nb_streams = s->nb_streams;
2163     if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
2164         mov->chapter_track = mov->nb_streams++;
2165
2166 #if FF_API_FLAG_RTP_HINT
2167     if (s->flags & AVFMT_FLAG_RTP_HINT) {
2168         av_log(s, AV_LOG_WARNING, "The RTP_HINT flag is deprecated, enable it "
2169                                   "via the -movflags rtphint muxer option "
2170                                   "instead.\n");
2171         mov->flags |= FF_MOV_FLAG_RTP_HINT;
2172     }
2173 #endif
2174     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
2175         /* Add hint tracks for each audio and video stream */
2176         hint_track = mov->nb_streams;
2177         for (i = 0; i < s->nb_streams; i++) {
2178             AVStream *st = s->streams[i];
2179             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2180                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2181                 mov->nb_streams++;
2182             }
2183         }
2184     }
2185
2186     mov->tracks = av_mallocz(mov->nb_streams*sizeof(*mov->tracks));
2187     if (!mov->tracks)
2188         return AVERROR(ENOMEM);
2189
2190     for(i=0; i<s->nb_streams; i++){
2191         AVStream *st= s->streams[i];
2192         MOVTrack *track= &mov->tracks[i];
2193         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
2194
2195         track->enc = st->codec;
2196         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
2197         if (track->language < 0)
2198             track->language = 0;
2199         track->mode = mov->mode;
2200         track->tag = mov_find_codec_tag(s, track);
2201         if (!track->tag) {
2202             av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
2203                    "codec not currently supported in container\n", i);
2204             goto error;
2205         }
2206         /* If hinting of this track is enabled by a later hint track,
2207          * this is updated. */
2208         track->hint_track = -1;
2209         if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2210             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
2211                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
2212                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
2213                 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
2214                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
2215                     goto error;
2216                 }
2217                 track->height = track->tag>>24 == 'n' ? 486 : 576;
2218             }
2219             track->timescale = st->codec->time_base.den;
2220             if (track->mode == MODE_MOV && track->timescale > 100000)
2221                 av_log(s, AV_LOG_WARNING,
2222                        "WARNING codec timebase is very high. If duration is too long,\n"
2223                        "file may not be playable by quicktime. Specify a shorter timebase\n"
2224                        "or choose different container.\n");
2225         }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO){
2226             track->timescale = st->codec->sample_rate;
2227             if(!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
2228                 av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
2229                 goto error;
2230             }else if(st->codec->codec_id == CODEC_ID_ADPCM_MS ||
2231                      st->codec->codec_id == CODEC_ID_ADPCM_IMA_WAV){
2232                 if (!st->codec->block_align) {
2233                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
2234                     goto error;
2235                 }
2236                 track->sampleSize = st->codec->block_align;
2237             }else if(st->codec->frame_size > 1){ /* assume compressed audio */
2238                 track->audio_vbr = 1;
2239             }else{
2240                 st->codec->frame_size = 1;
2241                 track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
2242             }
2243             if (track->mode != MODE_MOV) {
2244                 if (track->timescale > UINT16_MAX) {
2245                     av_log(s, AV_LOG_ERROR, "track %d: output format does not support "
2246                            "sample rate %dhz\n", i, track->timescale);
2247                     goto error;
2248                 }
2249                 if (track->enc->codec_id == CODEC_ID_MP3 && track->timescale < 16000) {
2250                     av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
2251                            i, track->enc->sample_rate);
2252                     goto error;
2253                 }
2254             }
2255         }else if(st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE){
2256             track->timescale = st->codec->time_base.den;
2257         }
2258         if (!track->height)
2259             track->height = st->codec->height;
2260
2261         av_set_pts_info(st, 64, 1, track->timescale);
2262     }
2263
2264     mov_write_mdat_tag(pb, mov);
2265
2266 #if FF_API_TIMESTAMP
2267     if (s->timestamp)
2268         mov->time = s->timestamp;
2269     else
2270 #endif
2271     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
2272         mov->time = ff_iso8601_to_unix_time(t->value);
2273     mov->time += 0x7C25B080; //1970 based -> 1904 based
2274
2275     if (mov->chapter_track)
2276         mov_create_chapter_track(s, mov->chapter_track);
2277
2278     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
2279         /* Initialize the hint tracks for each audio and video stream */
2280         for (i = 0; i < s->nb_streams; i++) {
2281             AVStream *st = s->streams[i];
2282             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2283                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2284                 ff_mov_init_hinting(s, hint_track, i);
2285                 hint_track++;
2286             }
2287         }
2288     }
2289
2290     avio_flush(pb);
2291
2292     return 0;
2293  error:
2294     av_freep(&mov->tracks);
2295     return -1;
2296 }
2297
2298 static int mov_write_trailer(AVFormatContext *s)
2299 {
2300     MOVMuxContext *mov = s->priv_data;
2301     AVIOContext *pb = s->pb;
2302     int res = 0;
2303     int i;
2304
2305     int64_t moov_pos = avio_tell(pb);
2306
2307     /* Write size of mdat tag */
2308     if (mov->mdat_size+8 <= UINT32_MAX) {
2309         avio_seek(pb, mov->mdat_pos, SEEK_SET);
2310         avio_wb32(pb, mov->mdat_size+8);
2311     } else {
2312         /* overwrite 'wide' placeholder atom */
2313         avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
2314         avio_wb32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
2315         ffio_wfourcc(pb, "mdat");
2316         avio_wb64(pb, mov->mdat_size+16);
2317     }
2318     avio_seek(pb, moov_pos, SEEK_SET);
2319
2320     mov_write_moov_tag(pb, mov, s);
2321
2322     if (mov->chapter_track)
2323         av_freep(&mov->tracks[mov->chapter_track].enc);
2324
2325     for (i=0; i<mov->nb_streams; i++) {
2326         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
2327             ff_mov_close_hinting(&mov->tracks[i]);
2328         av_freep(&mov->tracks[i].cluster);
2329
2330         if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2331
2332     }
2333
2334     avio_flush(pb);
2335
2336     av_freep(&mov->tracks);
2337
2338     return res;
2339 }
2340
2341 #if CONFIG_MOV_MUXER
2342 MOV_CLASS(mov)
2343 AVOutputFormat ff_mov_muxer = {
2344     .name              = "mov",
2345     .long_name         = NULL_IF_CONFIG_SMALL("MOV format"),
2346     .extensions        = "mov",
2347     .priv_data_size    = sizeof(MOVMuxContext),
2348     .audio_codec       = CODEC_ID_AAC,
2349 #if CONFIG_LIBX264_ENCODER
2350     .video_codec       = CODEC_ID_H264,
2351 #else
2352     .video_codec       = CODEC_ID_MPEG4,
2353 #endif
2354     .write_header      = mov_write_header,
2355     .write_packet      = ff_mov_write_packet,
2356     .write_trailer     = mov_write_trailer,
2357     .flags = AVFMT_GLOBALHEADER,
2358     .codec_tag = (const AVCodecTag* const []){codec_movvideo_tags, codec_movaudio_tags, 0},
2359     .priv_class = &mov_muxer_class,
2360 };
2361 #endif
2362 #if CONFIG_TGP_MUXER
2363 MOV_CLASS(tgp)
2364 AVOutputFormat ff_tgp_muxer = {
2365     .name              = "3gp",
2366     .long_name         = NULL_IF_CONFIG_SMALL("3GP format"),
2367     .extensions        = "3gp",
2368     .priv_data_size    = sizeof(MOVMuxContext),
2369     .audio_codec       = CODEC_ID_AMR_NB,
2370     .video_codec       = CODEC_ID_H263,
2371     .write_header      = mov_write_header,
2372     .write_packet      = ff_mov_write_packet,
2373     .write_trailer     = mov_write_trailer,
2374     .flags = AVFMT_GLOBALHEADER,
2375     .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2376     .priv_class = &tgp_muxer_class,
2377 };
2378 #endif
2379 #if CONFIG_MP4_MUXER
2380 MOV_CLASS(mp4)
2381 AVOutputFormat ff_mp4_muxer = {
2382     .name              = "mp4",
2383     .long_name         = NULL_IF_CONFIG_SMALL("MP4 format"),
2384     .mime_type         = "application/mp4",
2385     .extensions        = "mp4",
2386     .priv_data_size    = sizeof(MOVMuxContext),
2387     .audio_codec       = CODEC_ID_AAC,
2388 #if CONFIG_LIBX264_ENCODER
2389     .video_codec       = CODEC_ID_H264,
2390 #else
2391     .video_codec       = CODEC_ID_MPEG4,
2392 #endif
2393     .write_header      = mov_write_header,
2394     .write_packet      = ff_mov_write_packet,
2395     .write_trailer     = mov_write_trailer,
2396     .flags = AVFMT_GLOBALHEADER,
2397     .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2398     .priv_class = &mp4_muxer_class,
2399 };
2400 #endif
2401 #if CONFIG_PSP_MUXER
2402 MOV_CLASS(psp)
2403 AVOutputFormat ff_psp_muxer = {
2404     .name              = "psp",
2405     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 format"),
2406     .extensions        = "mp4,psp",
2407     .priv_data_size    = sizeof(MOVMuxContext),
2408     .audio_codec       = CODEC_ID_AAC,
2409 #if CONFIG_LIBX264_ENCODER
2410     .video_codec       = CODEC_ID_H264,
2411 #else
2412     .video_codec       = CODEC_ID_MPEG4,
2413 #endif
2414     .write_header      = mov_write_header,
2415     .write_packet      = ff_mov_write_packet,
2416     .write_trailer     = mov_write_trailer,
2417     .flags = AVFMT_GLOBALHEADER,
2418     .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2419     .priv_class = &psp_muxer_class,
2420 };
2421 #endif
2422 #if CONFIG_TG2_MUXER
2423 MOV_CLASS(tg2)
2424 AVOutputFormat ff_tg2_muxer = {
2425     .name              = "3g2",
2426     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 format"),
2427     .extensions        = "3g2",
2428     .priv_data_size    = sizeof(MOVMuxContext),
2429     .audio_codec       = CODEC_ID_AMR_NB,
2430     .video_codec       = CODEC_ID_H263,
2431     .write_header      = mov_write_header,
2432     .write_packet      = ff_mov_write_packet,
2433     .write_trailer     = mov_write_trailer,
2434     .flags = AVFMT_GLOBALHEADER,
2435     .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2436     .priv_class = &tg2_muxer_class,
2437 };
2438 #endif
2439 #if CONFIG_IPOD_MUXER
2440 MOV_CLASS(ipod)
2441 AVOutputFormat ff_ipod_muxer = {
2442     .name              = "ipod",
2443     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
2444     .mime_type         = "application/mp4",
2445     .extensions        = "m4v,m4a",
2446     .priv_data_size    = sizeof(MOVMuxContext),
2447     .audio_codec       = CODEC_ID_AAC,
2448     .video_codec       = CODEC_ID_H264,
2449     .write_header      = mov_write_header,
2450     .write_packet      = ff_mov_write_packet,
2451     .write_trailer     = mov_write_trailer,
2452     .flags = AVFMT_GLOBALHEADER,
2453     .codec_tag = (const AVCodecTag* const []){codec_ipod_tags, 0},
2454     .priv_class = &ipod_muxer_class,
2455 };
2456 #endif