]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
gcc 2.95 fix
[ffmpeg] / libavformat / movenc.c
1 /*
2  * MOV, 3GP, MP4 encoder.
3  * Copyright (c) 2003 Thomas Raivio.
4  * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 #include "avformat.h"
21 #include "avi.h"
22 #include "avio.h"
23
24 #undef NDEBUG
25 #include <assert.h>
26
27 #define MOV_INDEX_CLUSTER_SIZE 16384
28 #define globalTimescale 1000
29
30 #define MODE_MP4 0
31 #define MODE_MOV 1
32 #define MODE_3GP 2
33 #define MODE_PSP 3 // example working PSP command line:
34 // ffmpeg -i testinput.avi  -f psp -r 14.985 -s 320x240 -b 768 -ar 24000 -ab 32 M4V00001.MP4
35 #define MODE_3G2 4
36
37 typedef struct MOVIentry {
38     unsigned int flags, size;
39     uint64_t     pos;
40     unsigned int samplesInChunk;
41     char         key_frame;
42     unsigned int entries;
43 } MOVIentry;
44
45 typedef struct MOVIndex {
46     int         mode;
47     int         entry;
48     uint64_t    mdat_size;
49     int         ents_allocated;
50     long        timescale;
51     long        time;
52     long        trackDuration;
53     long        sampleCount;
54     long        sampleDuration;
55     int         hasKeyframes;
56     int         language;
57     int         trackID;
58     AVCodecContext *enc;
59
60     int         vosLen;
61     uint8_t     *vosData;
62     MOVIentry** cluster;
63 } MOVTrack;
64
65 typedef struct MOVContext {
66     int     mode;
67     long    time;
68     int     nb_streams;
69     int     mdat_written;
70     offset_t mdat_pos;
71     long    timescale;
72     MOVTrack tracks[MAX_STREAMS];
73 } MOVContext;
74
75 static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track);
76
77 /* output language code from iso639 language name */
78 extern int ff_mov_iso639_to_lang(const char *lang, int mp4);
79
80 const CodecTag ff_mov_obj_type[] = {
81     { CODEC_ID_MPEG4     ,  32 },
82     { CODEC_ID_AAC       ,  64 },
83     { CODEC_ID_MPEG1VIDEO, 106 },
84     { CODEC_ID_MPEG2VIDEO,  96 },//mpeg2 profiles
85     { CODEC_ID_MP2       , 107 },//FIXME mpeg2 mpeg audio -> 105
86     { CODEC_ID_MP3       , 107 },//FIXME mpeg2 mpeg audio -> 105
87     { CODEC_ID_H264      ,  33 },
88     { CODEC_ID_H263      , 242 },
89     { CODEC_ID_H261      , 243 },
90     { CODEC_ID_MJPEG     , 108 },
91     { CODEC_ID_PCM_S16LE , 224 },
92     { CODEC_ID_VORBIS    , 225 },
93     { CODEC_ID_AC3       , 226 },
94     { CODEC_ID_PCM_ALAW  , 227 },
95     { CODEC_ID_PCM_MULAW , 228 },
96     { CODEC_ID_PCM_S16BE , 230 },
97     { 0,0  },
98 };
99
100 //FIXME supprt 64bit varaint with wide placeholders
101 static offset_t updateSize (ByteIOContext *pb, offset_t pos)
102 {
103     offset_t curpos = url_ftell(pb);
104     url_fseek(pb, pos, SEEK_SET);
105     put_be32(pb, curpos - pos); /* rewrite size */
106     url_fseek(pb, curpos, SEEK_SET);
107
108     return curpos - pos;
109 }
110
111 /* Chunk offset atom */
112 static int mov_write_stco_tag(ByteIOContext *pb, MOVTrack* track)
113 {
114     int i;
115     int mode64 = 0; //   use 32 bit size variant if possible
116     offset_t pos = url_ftell(pb);
117     put_be32(pb, 0); /* size */
118     if (pos > UINT32_MAX) {
119         mode64 = 1;
120         put_tag(pb, "co64");
121     } else
122         put_tag(pb, "stco");
123     put_be32(pb, 0); /* version & flags */
124     put_be32(pb, track->entry); /* entry count */
125     for (i=0; i<track->entry; i++) {
126         int cl = i / MOV_INDEX_CLUSTER_SIZE;
127         int id = i % MOV_INDEX_CLUSTER_SIZE;
128         if(mode64 == 1)
129             put_be64(pb, track->cluster[cl][id].pos);
130         else
131             put_be32(pb, track->cluster[cl][id].pos);
132     }
133     return updateSize (pb, pos);
134 }
135
136 /* Sample size atom */
137 static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack* track)
138 {
139     int equalChunks = 1;
140     int i, j, entries = 0, tst = -1, oldtst = -1;
141
142     offset_t pos = url_ftell(pb);
143     put_be32(pb, 0); /* size */
144     put_tag(pb, "stsz");
145     put_be32(pb, 0); /* version & flags */
146
147     for (i=0; i<track->entry; i++) {
148         int cl = i / MOV_INDEX_CLUSTER_SIZE;
149         int id = i % MOV_INDEX_CLUSTER_SIZE;
150         tst = track->cluster[cl][id].size/track->cluster[cl][id].entries;
151         if(oldtst != -1 && tst != oldtst) {
152             equalChunks = 0;
153         }
154         oldtst = tst;
155         entries += track->cluster[cl][id].entries;
156     }
157     if (equalChunks) {
158         int sSize = track->cluster[0][0].size/track->cluster[0][0].entries;
159         put_be32(pb, sSize); // sample size
160         put_be32(pb, entries); // sample count
161     }
162     else {
163         put_be32(pb, 0); // sample size
164         put_be32(pb, entries); // sample count
165         for (i=0; i<track->entry; i++) {
166             int cl = i / MOV_INDEX_CLUSTER_SIZE;
167             int id = i % MOV_INDEX_CLUSTER_SIZE;
168             for ( j=0; j<track->cluster[cl][id].entries; j++) {
169                 put_be32(pb, track->cluster[cl][id].size /
170                          track->cluster[cl][id].entries);
171             }
172         }
173     }
174     return updateSize (pb, pos);
175 }
176
177 /* Sample to chunk atom */
178 static int mov_write_stsc_tag(ByteIOContext *pb, MOVTrack* track)
179 {
180     int index = 0, oldval = -1, i;
181     offset_t entryPos, curpos;
182
183     offset_t pos = url_ftell(pb);
184     put_be32(pb, 0); /* size */
185     put_tag(pb, "stsc");
186     put_be32(pb, 0); // version & flags
187     entryPos = url_ftell(pb);
188     put_be32(pb, track->entry); // entry count
189     for (i=0; i<track->entry; i++) {
190         int cl = i / MOV_INDEX_CLUSTER_SIZE;
191         int id = i % MOV_INDEX_CLUSTER_SIZE;
192         if(oldval != track->cluster[cl][id].samplesInChunk)
193         {
194             put_be32(pb, i+1); // first chunk
195             put_be32(pb, track->cluster[cl][id].samplesInChunk); // samples per chunk
196             put_be32(pb, 0x1); // sample description index
197             oldval = track->cluster[cl][id].samplesInChunk;
198             index++;
199         }
200     }
201     curpos = url_ftell(pb);
202     url_fseek(pb, entryPos, SEEK_SET);
203     put_be32(pb, index); // rewrite size
204     url_fseek(pb, curpos, SEEK_SET);
205
206     return updateSize (pb, pos);
207 }
208
209 /* Sync sample atom */
210 static int mov_write_stss_tag(ByteIOContext *pb, MOVTrack* track)
211 {
212     offset_t curpos, entryPos;
213     int i, index = 0;
214     offset_t pos = url_ftell(pb);
215     put_be32(pb, 0); // size
216     put_tag(pb, "stss");
217     put_be32(pb, 0); // version & flags
218     entryPos = url_ftell(pb);
219     put_be32(pb, track->entry); // entry count
220     for (i=0; i<track->entry; i++) {
221         int cl = i / MOV_INDEX_CLUSTER_SIZE;
222         int id = i % MOV_INDEX_CLUSTER_SIZE;
223         if(track->cluster[cl][id].key_frame == 1) {
224             put_be32(pb, i+1);
225             index++;
226         }
227     }
228     curpos = url_ftell(pb);
229     url_fseek(pb, entryPos, SEEK_SET);
230     put_be32(pb, index); // rewrite size
231     url_fseek(pb, curpos, SEEK_SET);
232     return updateSize (pb, pos);
233 }
234
235 static int mov_write_damr_tag(ByteIOContext *pb)
236 {
237     put_be32(pb, 0x11); /* size */
238     put_tag(pb, "damr");
239     put_tag(pb, "FFMP");
240     put_byte(pb, 0);
241
242     put_be16(pb, 0x80); /* Mode set (all modes for AMR_NB) */
243     put_be16(pb, 0xa); /* Mode change period (no restriction) */
244     //put_be16(pb, 0x81ff); /* Mode set (all modes for AMR_NB) */
245     //put_be16(pb, 1); /* Mode change period (no restriction) */
246     return 0x11;
247 }
248
249 static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack* track)
250 {
251     offset_t pos = url_ftell(pb);
252
253     put_be32(pb, 0);     /* size */
254     put_tag(pb, "wave");
255
256     put_be32(pb, 12);    /* size */
257     put_tag(pb, "frma");
258     put_tag(pb, "mp4a");
259
260     put_be32(pb, 12);    /* size */
261     put_tag(pb, "mp4a");
262     put_be32(pb, 0);
263
264     mov_write_esds_tag(pb, track);
265
266     put_be32(pb, 12);    /* size */
267     put_tag(pb, "srcq");
268     put_be32(pb, 0x40);
269
270     put_be32(pb, 8);     /* size */
271     put_be32(pb, 0);     /* null tag */
272
273     return updateSize (pb, pos);
274 }
275
276 static const CodecTag codec_movaudio_tags[] = {
277     { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') },
278     { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') },
279     { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') },
280     { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') },
281     { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') },
282     { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
283     { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') },
284     { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') },
285     { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') },
286     { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') },
287     { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') },
288     { 0, 0 },
289 };
290
291 static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack* track)
292 {
293     offset_t pos = url_ftell(pb);
294     int tag;
295
296     put_be32(pb, 0); /* size */
297
298     tag = track->enc->codec_tag;
299     if (!tag)
300     tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
301     // if no mac fcc found, try with Microsoft tags
302     if (!tag)
303     {
304         int tmp = codec_get_tag(codec_wav_tags, track->enc->codec_id);
305         tag = MKTAG('m', 's', ((tmp >> 8) & 0xff), (tmp & 0xff));
306     }
307     put_le32(pb, tag); // store it byteswapped
308
309     put_be32(pb, 0); /* Reserved */
310     put_be16(pb, 0); /* Reserved */
311     put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
312
313     /* SoundDescription */
314     if(track->mode == MODE_MOV && track->enc->codec_id == CODEC_ID_AAC)
315         put_be16(pb, 1); /* Version 1 */
316     else
317         put_be16(pb, 0); /* Version 0 */
318     put_be16(pb, 0); /* Revision level */
319     put_be32(pb, 0); /* Reserved */
320
321     put_be16(pb, track->enc->channels); /* Number of channels */
322     /* TODO: Currently hard-coded to 16-bit, there doesn't seem
323                  to be a good way to get number of bits of audio */
324     put_be16(pb, 0x10); /* Reserved */
325
326     if(track->enc->codec_id == CODEC_ID_AAC ||
327        track->enc->codec_id == CODEC_ID_MP3)
328     {
329         put_be16(pb, 0xfffe); /* compression ID (vbr)*/
330     }
331     else
332     {
333         put_be16(pb, 0); /* compression ID (= 0) */
334     }
335     put_be16(pb, 0); /* packet size (= 0) */
336     put_be16(pb, track->timescale); /* Time scale */
337     put_be16(pb, 0); /* Reserved */
338
339     if(track->mode == MODE_MOV && track->enc->codec_id == CODEC_ID_AAC)
340     {
341         /* SoundDescription V1 extended info */
342         put_be32(pb, track->enc->frame_size); /* Samples per packet  */
343         put_be32(pb, 1536); /* Bytes per packet */
344         put_be32(pb, 2); /* Bytes per frame */
345         put_be32(pb, 2); /* Bytes per sample */
346     }
347
348     if(track->enc->codec_id == CODEC_ID_AAC) {
349         if( track->mode == MODE_MOV ) mov_write_wave_tag(pb, track);
350         else mov_write_esds_tag(pb, track);
351     }
352     if(track->enc->codec_id == CODEC_ID_AMR_NB)
353         mov_write_damr_tag(pb);
354     return updateSize (pb, pos);
355 }
356
357 static int mov_write_d263_tag(ByteIOContext *pb)
358 {
359     put_be32(pb, 0xf); /* size */
360     put_tag(pb, "d263");
361     put_tag(pb, "FFMP");
362     put_be16(pb, 0x0a);
363     put_byte(pb, 0);
364     return 0xf;
365 }
366
367 /* TODO: No idea about these values */
368 static int mov_write_svq3_tag(ByteIOContext *pb)
369 {
370     put_be32(pb, 0x15);
371     put_tag(pb, "SMI ");
372     put_tag(pb, "SEQH");
373     put_be32(pb, 0x5);
374     put_be32(pb, 0xe2c0211d);
375     put_be32(pb, 0xc0000000);
376     put_byte(pb, 0);
377     return 0x15;
378 }
379
380 static unsigned int descrLength(unsigned int len)
381 {
382     if (len < 0x00000080)
383         return 2 + len;
384     else if (len < 0x00004000)
385         return 3 + len;
386     else if(len < 0x00200000)
387         return 4 + len;
388     else
389         return 5 + len;
390 }
391
392 static void putDescr(ByteIOContext *pb, int tag, int size)
393 {
394     uint32_t len;
395     uint8_t  vals[4];
396
397     len = size;
398     vals[3] = (uint8_t)(len & 0x7f);
399     len >>= 7;
400     vals[2] = (uint8_t)((len & 0x7f) | 0x80);
401     len >>= 7;
402     vals[1] = (uint8_t)((len & 0x7f) | 0x80);
403     len >>= 7;
404     vals[0] = (uint8_t)((len & 0x7f) | 0x80);
405
406     put_byte(pb, tag); // DescriptorTag
407
408     if (size < 0x00000080)
409     {
410         put_byte(pb, vals[3]);
411     }
412     else if (size < 0x00004000)
413     {
414         put_byte(pb, vals[2]);
415         put_byte(pb, vals[3]);
416     }
417     else if (size < 0x00200000)
418     {
419         put_byte(pb, vals[1]);
420         put_byte(pb, vals[2]);
421         put_byte(pb, vals[3]);
422     }
423     else if (size < 0x10000000)
424     {
425         put_byte(pb, vals[0]);
426         put_byte(pb, vals[1]);
427         put_byte(pb, vals[2]);
428         put_byte(pb, vals[3]);
429     }
430 }
431
432 static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track) // Basic
433 {
434     int decoderSpecificInfoLen;
435     offset_t pos = url_ftell(pb);
436     void *vosDataBackup=track->vosData;
437     int vosLenBackup=track->vosLen;
438
439     // we should be able to have these passed in, via vosData, then we wouldn't need to attack this routine at all
440     static const char PSPAACData[]={0x13,0x10};
441     static const char PSPMP4Data[]={0x00,0x00,0x01,0xB0,0x03,0x00,0x00,0x01,0xB5,0x09,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x20,0x00,0x84,0x5D,0x4C,0x28,0x50,0x20,0xF0,0xA3,0x1F };
442
443
444     if (track->mode == MODE_PSP)  // fails on psp if this is not here
445     {
446         if (track->enc->codec_id == CODEC_ID_AAC)
447         {
448             track->vosLen = 2;
449             track->vosData = (uint8_t *) PSPAACData;
450         }
451
452         if (track->enc->codec_id == CODEC_ID_MPEG4)
453         {
454             track->vosLen = 28;
455             track->vosData = (uint8_t *) PSPMP4Data;
456         }
457     }
458
459     decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
460
461     put_be32(pb, 0);               // size
462     put_tag(pb, "esds");
463     put_be32(pb, 0);               // Version
464
465     // ES descriptor
466     putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
467              descrLength(1));
468     put_be16(pb, track->trackID);
469     put_byte(pb, 0x00);            // flags (= no flags)
470
471     // DecoderConfig descriptor
472     putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
473
474     // Object type indication
475     put_byte(pb, codec_get_tag(ff_mov_obj_type, track->enc->codec_id));
476
477     // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
478     // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
479     if(track->enc->codec_type == CODEC_TYPE_AUDIO)
480         put_byte(pb, 0x15);            // flags (= Audiostream)
481     else
482         put_byte(pb, 0x11);            // flags (= Visualstream)
483
484     put_byte(pb,  track->enc->rc_buffer_size>>(3+16));             // Buffersize DB (24 bits)
485     put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF);          // Buffersize DB
486
487     put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate));     // maxbitrate  (FIXME should be max rate in any 1 sec window)
488     if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
489         put_be32(pb, 0);     // vbr
490     else
491         put_be32(pb, track->enc->rc_max_rate);     // avg bitrate
492
493     if (track->vosLen)
494     {
495         // DecoderSpecific info descriptor
496         putDescr(pb, 0x05, track->vosLen);
497         put_buffer(pb, track->vosData, track->vosLen);
498     }
499
500     track->vosData = vosDataBackup;
501     track->vosLen = vosLenBackup;
502
503     // SL descriptor
504     putDescr(pb, 0x06, 1);
505     put_byte(pb, 0x02);
506     return updateSize (pb, pos);
507 }
508
509 static const CodecTag codec_movvideo_tags[] = {
510     { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') },
511     { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') },
512     { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
513     { CODEC_ID_H263, MKTAG('s', '2', '6', '3') },
514     { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
515     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') },
516     { 0, 0 },
517 };
518
519 static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
520 {
521     offset_t pos = url_ftell(pb);
522     char compressor_name[32];
523     int tag;
524
525     put_be32(pb, 0); /* size */
526
527     tag = track->enc->codec_tag;
528     if (!tag)
529     tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
530     // if no mac fcc found, try with Microsoft tags
531     if (!tag)
532         tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
533     put_le32(pb, tag); // store it byteswapped
534
535     put_be32(pb, 0); /* Reserved */
536     put_be16(pb, 0); /* Reserved */
537     put_be16(pb, 1); /* Data-reference index */
538
539     put_be16(pb, 0); /* Codec stream version */
540     put_be16(pb, 0); /* Codec stream revision (=0) */
541     put_tag(pb, "FFMP"); /* Vendor */
542     if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
543         put_be32(pb, 0); /* Temporal Quality */
544         put_be32(pb, 0x400); /* Spatial Quality = lossless*/
545     } else {
546         put_be32(pb, 0x200); /* Temporal Quality = normal */
547         put_be32(pb, 0x200); /* Spatial Quality = normal */
548     }
549     put_be16(pb, track->enc->width); /* Video width */
550     put_be16(pb, track->enc->height); /* Video height */
551     put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
552     put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
553     put_be32(pb, 0); /* Data size (= 0) */
554     put_be16(pb, 1); /* Frame count (= 1) */
555
556     memset(compressor_name,0,32);
557     if (track->enc->codec && track->enc->codec->name)
558         strncpy(compressor_name,track->enc->codec->name,31);
559     put_byte(pb, strlen(compressor_name));
560     put_buffer(pb, compressor_name, 31);
561
562     put_be16(pb, 0x18); /* Reserved */
563     put_be16(pb, 0xffff); /* Reserved */
564     if(track->enc->codec_id == CODEC_ID_MPEG4)
565         mov_write_esds_tag(pb, track);
566     else if(track->enc->codec_id == CODEC_ID_H263)
567         mov_write_d263_tag(pb);
568     else if(track->enc->codec_id == CODEC_ID_SVQ3)
569         mov_write_svq3_tag(pb);
570
571     return updateSize (pb, pos);
572 }
573
574 static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack* track)
575 {
576     offset_t pos = url_ftell(pb);
577     put_be32(pb, 0); /* size */
578     put_tag(pb, "stsd");
579     put_be32(pb, 0); /* version & flags */
580     put_be32(pb, 1); /* entry count */
581     if (track->enc->codec_type == CODEC_TYPE_VIDEO)
582         mov_write_video_tag(pb, track);
583     else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
584         mov_write_audio_tag(pb, track);
585     return updateSize(pb, pos);
586 }
587
588 /* TODO: */
589 /* Time to sample atom */
590 static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack* track)
591 {
592     put_be32(pb, 0x18); /* size */
593     put_tag(pb, "stts");
594     put_be32(pb, 0); /* version & flags */
595     put_be32(pb, 1); /* entry count */
596
597     put_be32(pb, track->sampleCount); /* sample count */
598     put_be32(pb, track->sampleDuration); /* sample duration */
599     return 0x18;
600 }
601
602 static int mov_write_dref_tag(ByteIOContext *pb)
603 {
604     put_be32(pb, 28); /* size */
605     put_tag(pb, "dref");
606     put_be32(pb, 0); /* version & flags */
607     put_be32(pb, 1); /* entry count */
608
609     put_be32(pb, 0xc); /* size */
610     put_tag(pb, "url ");
611     put_be32(pb, 1); /* version & flags */
612
613     return 28;
614 }
615
616 static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track)
617 {
618     offset_t pos = url_ftell(pb);
619     put_be32(pb, 0); /* size */
620     put_tag(pb, "stbl");
621     mov_write_stsd_tag(pb, track);
622     mov_write_stts_tag(pb, track);
623     if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
624         track->hasKeyframes)
625         mov_write_stss_tag(pb, track);
626     mov_write_stsc_tag(pb, track);
627     mov_write_stsz_tag(pb, track);
628     mov_write_stco_tag(pb, track);
629     return updateSize(pb, pos);
630 }
631
632 static int mov_write_dinf_tag(ByteIOContext *pb)
633 {
634     offset_t pos = url_ftell(pb);
635     put_be32(pb, 0); /* size */
636     put_tag(pb, "dinf");
637     mov_write_dref_tag(pb);
638     return updateSize(pb, pos);
639 }
640
641 static int mov_write_smhd_tag(ByteIOContext *pb)
642 {
643     put_be32(pb, 16); /* size */
644     put_tag(pb, "smhd");
645     put_be32(pb, 0); /* version & flags */
646     put_be16(pb, 0); /* reserved (balance, normally = 0) */
647     put_be16(pb, 0); /* reserved */
648     return 16;
649 }
650
651 static int mov_write_vmhd_tag(ByteIOContext *pb)
652 {
653     put_be32(pb, 0x14); /* size (always 0x14) */
654     put_tag(pb, "vmhd");
655     put_be32(pb, 0x01); /* version & flags */
656     put_be64(pb, 0); /* reserved (graphics mode = copy) */
657     return 0x14;
658 }
659
660 static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack* track)
661 {
662     char *descr, *hdlr, *hdlr_type;
663     offset_t pos = url_ftell(pb);
664
665     if (!track) { /* no media --> data handler */
666         hdlr = "dhlr";
667         hdlr_type = "url ";
668         descr = "DataHandler";
669     } else {
670         hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
671         if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
672             hdlr_type = "vide";
673             descr = "VideoHandler";
674         } else {
675             hdlr_type = "soun";
676             descr = "SoundHandler";
677         }
678     }
679
680     put_be32(pb, 0); /* size */
681     put_tag(pb, "hdlr");
682     put_be32(pb, 0); /* Version & flags */
683     put_buffer(pb, hdlr, 4); /* handler */
684     put_tag(pb, hdlr_type); /* handler type */
685     put_be32(pb ,0); /* reserved */
686     put_be32(pb ,0); /* reserved */
687     put_be32(pb ,0); /* reserved */
688     put_byte(pb, strlen(descr)); /* string counter */
689     put_buffer(pb, descr, strlen(descr)); /* handler description */
690     return updateSize(pb, pos);
691 }
692
693 static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack* track)
694 {
695     offset_t pos = url_ftell(pb);
696     put_be32(pb, 0); /* size */
697     put_tag(pb, "minf");
698     if(track->enc->codec_type == CODEC_TYPE_VIDEO)
699         mov_write_vmhd_tag(pb);
700     else
701         mov_write_smhd_tag(pb);
702     if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
703         mov_write_hdlr_tag(pb, NULL);
704     mov_write_dinf_tag(pb);
705     mov_write_stbl_tag(pb, track);
706     return updateSize(pb, pos);
707 }
708
709 static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack* track)
710 {
711     put_be32(pb, 32); /* size */
712     put_tag(pb, "mdhd");
713     put_be32(pb, 0); /* Version & flags */
714     put_be32(pb, track->time); /* creation time */
715     put_be32(pb, track->time); /* modification time */
716     put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
717     put_be32(pb, track->trackDuration); /* duration */
718     put_be16(pb, track->language); /* language */
719     put_be16(pb, 0); /* reserved (quality) */
720     return 32;
721 }
722
723 static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack* track)
724 {
725     offset_t pos = url_ftell(pb);
726     put_be32(pb, 0); /* size */
727     put_tag(pb, "mdia");
728     mov_write_mdhd_tag(pb, track);
729     mov_write_hdlr_tag(pb, track);
730     mov_write_minf_tag(pb, track);
731     return updateSize(pb, pos);
732 }
733
734 static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)
735 {
736     put_be32(pb, 0x5c); /* size (always 0x5c) */
737     put_tag(pb, "tkhd");
738     put_be32(pb, 0xf); /* version & flags (track enabled) */
739     put_be32(pb, track->time); /* creation time */
740     put_be32(pb, track->time); /* modification time */
741     put_be32(pb, track->trackID); /* track-id */
742     put_be32(pb, 0); /* reserved */
743     put_be32(pb, av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP)); /* duration */
744
745     put_be32(pb, 0); /* reserved */
746     put_be32(pb, 0); /* reserved */
747     put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
748     /* Volume, only for audio */
749     if(track->enc->codec_type == CODEC_TYPE_AUDIO)
750         put_be16(pb, 0x0100);
751     else
752         put_be16(pb, 0);
753     put_be16(pb, 0); /* reserved */
754
755     /* Matrix structure */
756     put_be32(pb, 0x00010000); /* reserved */
757     put_be32(pb, 0x0); /* reserved */
758     put_be32(pb, 0x0); /* reserved */
759     put_be32(pb, 0x0); /* reserved */
760     put_be32(pb, 0x00010000); /* reserved */
761     put_be32(pb, 0x0); /* reserved */
762     put_be32(pb, 0x0); /* reserved */
763     put_be32(pb, 0x0); /* reserved */
764     put_be32(pb, 0x40000000); /* reserved */
765
766     /* Track width and height, for visual only */
767     if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
768         double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
769         if( !sample_aspect_ratio ) sample_aspect_ratio = 1;
770         put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
771         put_be32(pb, track->enc->height*0x10000);
772     }
773     else {
774         put_be32(pb, 0);
775         put_be32(pb, 0);
776     }
777     return 0x5c;
778 }
779
780 // This box seems important for the psp playback ... without it the movie seems to hang
781 static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
782 {
783     put_be32(pb, 0x24); /* size  */
784     put_tag(pb, "edts");
785     put_be32(pb, 0x1c); /* size  */
786     put_tag(pb, "elst");
787     put_be32(pb, 0x0);
788     put_be32(pb, 0x1);
789
790     put_be32(pb, av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP)); /* duration   ... doesn't seem to effect psp */
791
792     put_be32(pb, 0x0);
793     put_be32(pb, 0x00010000);
794     return 0x24;
795 }
796
797 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
798 static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
799 {
800     put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
801     put_tag(pb, "uuid");
802     put_tag(pb, "USMT");
803     put_be32(pb, 0x21d24fce);
804     put_be32(pb, 0xbb88695c);
805     put_be32(pb, 0xfac9c740);
806     put_be32(pb, 0x1c);     // another size here!
807     put_tag(pb, "MTDT");
808     put_be32(pb, 0x00010012);
809     put_be32(pb, 0x0a);
810     put_be32(pb, 0x55c40000);
811     put_be32(pb, 0x1);
812     put_be32(pb, 0x0);
813     return 0x34;
814 }
815
816 static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack* track)
817 {
818     offset_t pos = url_ftell(pb);
819     put_be32(pb, 0); /* size */
820     put_tag(pb, "trak");
821     mov_write_tkhd_tag(pb, track);
822     if (track->mode == MODE_PSP)
823         mov_write_edts_tag(pb, track);  // PSP Movies require edts box
824     mov_write_mdia_tag(pb, track);
825     if (track->mode == MODE_PSP)
826         mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
827     return updateSize(pb, pos);
828 }
829
830 #if 0
831 /* TODO: Not sorted out, but not necessary either */
832 static int mov_write_iods_tag(ByteIOContext *pb, MOVContext *mov)
833 {
834     put_be32(pb, 0x15); /* size */
835     put_tag(pb, "iods");
836     put_be32(pb, 0);    /* version & flags */
837     put_be16(pb, 0x1007);
838     put_byte(pb, 0);
839     put_be16(pb, 0x4fff);
840     put_be16(pb, 0xfffe);
841     put_be16(pb, 0x01ff);
842     return 0x15;
843 }
844 #endif
845
846 static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
847 {
848     int maxTrackID = 1, i;
849     int64_t maxTrackLenTemp, maxTrackLen = 0;
850
851     put_be32(pb, 0x6c); /* size (always 0x6c) */
852     put_tag(pb, "mvhd");
853     put_be32(pb, 0); /* version & flags */
854     put_be32(pb, mov->time); /* creation time */
855     put_be32(pb, mov->time); /* modification time */
856     put_be32(pb, mov->timescale); /* timescale */
857     for (i=0; i<MAX_STREAMS; i++) {
858         if(mov->tracks[i].entry > 0) {
859             maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
860             if(maxTrackLen < maxTrackLenTemp)
861                 maxTrackLen = maxTrackLenTemp;
862             if(maxTrackID < mov->tracks[i].trackID)
863                 maxTrackID = mov->tracks[i].trackID;
864         }
865     }
866     put_be32(pb, maxTrackLen); /* duration of longest track */
867
868     put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
869     put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
870     put_be16(pb, 0); /* reserved */
871     put_be32(pb, 0); /* reserved */
872     put_be32(pb, 0); /* reserved */
873
874     /* Matrix structure */
875     put_be32(pb, 0x00010000); /* reserved */
876     put_be32(pb, 0x0); /* reserved */
877     put_be32(pb, 0x0); /* reserved */
878     put_be32(pb, 0x0); /* reserved */
879     put_be32(pb, 0x00010000); /* reserved */
880     put_be32(pb, 0x0); /* reserved */
881     put_be32(pb, 0x0); /* reserved */
882     put_be32(pb, 0x0); /* reserved */
883     put_be32(pb, 0x40000000); /* reserved */
884
885     put_be32(pb, 0); /* reserved (preview time) */
886     put_be32(pb, 0); /* reserved (preview duration) */
887     put_be32(pb, 0); /* reserved (poster time) */
888     put_be32(pb, 0); /* reserved (selection time) */
889     put_be32(pb, 0); /* reserved (selection duration) */
890     put_be32(pb, 0); /* reserved (current time) */
891     put_be32(pb, maxTrackID+1); /* Next track id */
892     return 0x6c;
893 }
894
895 static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVContext* mov,
896                                      AVFormatContext *s)
897 {
898     offset_t pos = url_ftell(pb);
899     put_be32(pb, 0); /* size */
900     put_tag(pb, "hdlr");
901     put_be32(pb, 0);
902     put_be32(pb, 0);
903     put_tag(pb, "mdir");
904     put_tag(pb, "appl");
905     put_be32(pb, 0);
906     put_be32(pb, 0);
907     put_be16(pb, 0);
908     return updateSize(pb, pos);
909 }
910
911 /* helper function to write a data tag with the specified string as data */
912 static int mov_write_string_data_tag(ByteIOContext *pb, MOVContext* mov,
913                                      AVFormatContext *s, const char *data)
914 {
915     offset_t pos = url_ftell(pb);
916     put_be32(pb, 0); /* size */
917     put_tag(pb, "data");
918     put_be32(pb, 1);
919     put_be32(pb, 0);
920     put_buffer(pb, data, strlen(data));
921     return updateSize(pb, pos);
922 }
923
924 /* iTunes name of the song/movie */
925 static int mov_write_nam_tag(ByteIOContext *pb, MOVContext* mov,
926                              AVFormatContext *s)
927 {
928     int size = 0;
929     if ( s->title[0] ) {
930         offset_t pos = url_ftell(pb);
931         put_be32(pb, 0); /* size */
932         put_tag(pb, "\251nam");
933         mov_write_string_data_tag(pb, mov, s, s->title);
934         size = updateSize(pb, pos);
935     }
936     return size;
937 }
938
939 /* iTunes name of the artist/performer */
940 static int mov_write_ART_tag(ByteIOContext *pb, MOVContext* mov,
941                              AVFormatContext *s)
942 {
943     int size = 0;
944     if ( s->author[0] ) {
945         offset_t pos = url_ftell(pb);
946         put_be32(pb, 0); /* size */
947         put_tag(pb, "\251ART");
948         // we use the author here as this is the only thing that we have...
949         mov_write_string_data_tag(pb, mov, s, s->author);
950         size = updateSize(pb, pos);
951     }
952     return size;
953 }
954
955 /* iTunes name of the writer */
956 static int mov_write_wrt_tag(ByteIOContext *pb, MOVContext* mov,
957                              AVFormatContext *s)
958 {
959     int size = 0;
960     if ( s->author[0] ) {
961         offset_t pos = url_ftell(pb);
962         put_be32(pb, 0); /* size */
963         put_tag(pb, "\251wrt");
964         mov_write_string_data_tag(pb, mov, s, s->author);
965         size = updateSize(pb, pos);
966     }
967     return size;
968 }
969
970 /* iTunes name of the album */
971 static int mov_write_alb_tag(ByteIOContext *pb, MOVContext* mov,
972                              AVFormatContext *s)
973 {
974     int size = 0;
975     if ( s->album[0] ) {
976         offset_t pos = url_ftell(pb);
977         put_be32(pb, 0); /* size */
978         put_tag(pb, "\251alb");
979         mov_write_string_data_tag(pb, mov, s, s->album);
980         size = updateSize(pb, pos);
981     }
982     return size;
983 }
984
985 /* iTunes year */
986 static int mov_write_day_tag(ByteIOContext *pb, MOVContext* mov,
987                              AVFormatContext *s)
988 {
989     char year[5];
990     int size = 0;
991     if ( s->year ) {
992         offset_t pos = url_ftell(pb);
993         put_be32(pb, 0); /* size */
994         put_tag(pb, "\251day");
995         snprintf(year, 5, "%04d", s->year);
996         mov_write_string_data_tag(pb, mov, s, year);
997         size = updateSize(pb, pos);
998     }
999     return size;
1000 }
1001
1002 /* iTunes tool used to create the file */
1003 static int mov_write_too_tag(ByteIOContext *pb, MOVContext* mov,
1004                              AVFormatContext *s)
1005 {
1006     offset_t pos = url_ftell(pb);
1007     put_be32(pb, 0); /* size */
1008     put_tag(pb, "\251too");
1009     mov_write_string_data_tag(pb, mov, s, LIBAVFORMAT_IDENT);
1010     return updateSize(pb, pos);
1011 }
1012
1013 /* iTunes comment */
1014 static int mov_write_cmt_tag(ByteIOContext *pb, MOVContext* mov,
1015                              AVFormatContext *s)
1016 {
1017     int size = 0;
1018     if ( s->comment[0] ) {
1019         offset_t pos = url_ftell(pb);
1020         put_be32(pb, 0); /* size */
1021         put_tag(pb, "\251cmt");
1022         mov_write_string_data_tag(pb, mov, s, s->comment);
1023         size = updateSize(pb, pos);
1024     }
1025     return size;
1026 }
1027
1028 /* iTunes custom genre */
1029 static int mov_write_gen_tag(ByteIOContext *pb, MOVContext* mov,
1030                              AVFormatContext *s)
1031 {
1032     int size = 0;
1033     if ( s->genre[0] ) {
1034         offset_t pos = url_ftell(pb);
1035         put_be32(pb, 0); /* size */
1036         put_tag(pb, "\251gen");
1037         mov_write_string_data_tag(pb, mov, s, s->genre);
1038         size = updateSize(pb, pos);
1039     }
1040     return size;
1041 }
1042
1043 /* iTunes track number */
1044 static int mov_write_trkn_tag(ByteIOContext *pb, MOVContext* mov,
1045                               AVFormatContext *s)
1046 {
1047     int size = 0;
1048     if ( s->track ) {
1049         offset_t pos = url_ftell(pb);
1050         put_be32(pb, 0); /* size */
1051         put_tag(pb, "trkn");
1052         {
1053             offset_t pos = url_ftell(pb);
1054             put_be32(pb, 0); /* size */
1055             put_tag(pb, "data");
1056             put_be32(pb, 0);        // 8 bytes empty
1057             put_be32(pb, 0);
1058             put_be16(pb, 0);        // empty
1059             put_be16(pb, s->track); // track number
1060             put_be16(pb, 0);        // total track number
1061             put_be16(pb, 0);        // empty
1062             updateSize(pb, pos);
1063         }
1064         size = updateSize(pb, pos);
1065     }
1066     return size;
1067 }
1068
1069 /* iTunes meta data list */
1070 static int mov_write_ilst_tag(ByteIOContext *pb, MOVContext* mov,
1071                               AVFormatContext *s)
1072 {
1073     offset_t pos = url_ftell(pb);
1074     put_be32(pb, 0); /* size */
1075     put_tag(pb, "ilst");
1076     mov_write_nam_tag(pb, mov, s);
1077     mov_write_ART_tag(pb, mov, s);
1078     mov_write_wrt_tag(pb, mov, s);
1079     mov_write_alb_tag(pb, mov, s);
1080     mov_write_day_tag(pb, mov, s);
1081     mov_write_too_tag(pb, mov, s);
1082     mov_write_cmt_tag(pb, mov, s);
1083     mov_write_gen_tag(pb, mov, s);
1084     mov_write_trkn_tag(pb, mov, s);
1085     return updateSize(pb, pos);
1086 }
1087
1088 /* iTunes meta data tag */
1089 static int mov_write_meta_tag(ByteIOContext *pb, MOVContext* mov,
1090                               AVFormatContext *s)
1091 {
1092     int size = 0;
1093
1094     // only save meta tag if required
1095     if ( s->title[0] || s->author[0] || s->album[0] || s->year ||
1096          s->comment[0] || s->genre[0] || s->track ) {
1097         offset_t pos = url_ftell(pb);
1098         put_be32(pb, 0); /* size */
1099         put_tag(pb, "meta");
1100         put_be32(pb, 0);
1101         mov_write_itunes_hdlr_tag(pb, mov, s);
1102         mov_write_ilst_tag(pb, mov, s);
1103         size = updateSize(pb, pos);
1104     }
1105     return size;
1106 }
1107
1108 static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1109                               AVFormatContext *s)
1110 {
1111     offset_t pos = url_ftell(pb);
1112     int i;
1113
1114     put_be32(pb, 0); /* size */
1115     put_tag(pb, "udta");
1116
1117     /* iTunes meta data */
1118     mov_write_meta_tag(pb, mov, s);
1119
1120     /* Requirements */
1121     for (i=0; i<MAX_STREAMS; i++) {
1122         if(mov->tracks[i].entry <= 0) continue;
1123         if (mov->tracks[i].enc->codec_id == CODEC_ID_AAC ||
1124             mov->tracks[i].enc->codec_id == CODEC_ID_MPEG4) {
1125             offset_t pos = url_ftell(pb);
1126             put_be32(pb, 0); /* size */
1127             put_tag(pb, "\251req");
1128             put_be16(pb, sizeof("QuickTime 6.0 or greater") - 1);
1129             put_be16(pb, 0);
1130             put_buffer(pb, "QuickTime 6.0 or greater",
1131                        sizeof("QuickTime 6.0 or greater") - 1);
1132             updateSize(pb, pos);
1133             break;
1134         }
1135     }
1136
1137     /* Encoder */
1138     if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1139     {
1140         offset_t pos = url_ftell(pb);
1141         put_be32(pb, 0); /* size */
1142         put_tag(pb, "\251enc");
1143         put_be16(pb, sizeof(LIBAVFORMAT_IDENT) - 1); /* string length */
1144         put_be16(pb, 0);
1145         put_buffer(pb, LIBAVFORMAT_IDENT, sizeof(LIBAVFORMAT_IDENT) - 1);
1146         updateSize(pb, pos);
1147     }
1148
1149     if( s->title[0] )
1150     {
1151         offset_t pos = url_ftell(pb);
1152         put_be32(pb, 0); /* size */
1153         put_tag(pb, "\251nam");
1154         put_be16(pb, strlen(s->title)); /* string length */
1155         put_be16(pb, 0);
1156         put_buffer(pb, s->title, strlen(s->title));
1157         updateSize(pb, pos);
1158     }
1159
1160     if( s->author[0] )
1161     {
1162         offset_t pos = url_ftell(pb);
1163         put_be32(pb, 0); /* size */
1164         put_tag(pb, /*"\251aut"*/ "\251day" );
1165         put_be16(pb, strlen(s->author)); /* string length */
1166         put_be16(pb, 0);
1167         put_buffer(pb, s->author, strlen(s->author));
1168         updateSize(pb, pos);
1169     }
1170
1171     if( s->comment[0] )
1172     {
1173         offset_t pos = url_ftell(pb);
1174         put_be32(pb, 0); /* size */
1175         put_tag(pb, "\251des");
1176         put_be16(pb, strlen(s->comment)); /* string length */
1177         put_be16(pb, 0);
1178         put_buffer(pb, s->comment, strlen(s->comment));
1179         updateSize(pb, pos);
1180     }
1181
1182     return updateSize(pb, pos);
1183 }
1184
1185 static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1186                               AVFormatContext *s)
1187 {
1188     int i;
1189     offset_t pos = url_ftell(pb);
1190     put_be32(pb, 0); /* size placeholder*/
1191     put_tag(pb, "moov");
1192     mov->timescale = globalTimescale;
1193
1194     for (i=0; i<MAX_STREAMS; i++) {
1195         if(mov->tracks[i].entry <= 0) continue;
1196
1197         if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {
1198             mov->tracks[i].timescale = mov->tracks[i].enc->time_base.den;
1199             mov->tracks[i].sampleDuration = mov->tracks[i].enc->time_base.num;
1200         }
1201         else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {
1202             /* If AMR, track timescale = 8000, AMR_WB = 16000 */
1203             if(mov->tracks[i].enc->codec_id == CODEC_ID_AMR_NB) {
1204                 mov->tracks[i].sampleDuration = 160;  // Bytes per chunk
1205                 mov->tracks[i].timescale = 8000;
1206             }
1207             else {
1208                 mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;
1209                 mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;
1210             }
1211         }
1212
1213         mov->tracks[i].trackDuration =
1214             mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;
1215         mov->tracks[i].time = mov->time;
1216         mov->tracks[i].trackID = i+1;
1217     }
1218
1219     mov_write_mvhd_tag(pb, mov);
1220     //mov_write_iods_tag(pb, mov);
1221     for (i=0; i<MAX_STREAMS; i++) {
1222         if(mov->tracks[i].entry > 0) {
1223             mov_write_trak_tag(pb, &(mov->tracks[i]));
1224         }
1225     }
1226
1227     mov_write_udta_tag(pb, mov, s);
1228
1229     return updateSize(pb, pos);
1230 }
1231
1232 int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1233 {
1234     put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1235     put_tag(pb, "wide");
1236
1237     mov->mdat_pos = url_ftell(pb);
1238     put_be32(pb, 0); /* size placeholder*/
1239     put_tag(pb, "mdat");
1240     return 0;
1241 }
1242
1243 /* TODO: This needs to be more general */
1244 int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
1245 {
1246     MOVContext *mov = s->priv_data;
1247
1248     put_be32(pb, 0x14 ); /* size */
1249     put_tag(pb, "ftyp");
1250
1251     if ( mov->mode == MODE_3GP )
1252         put_tag(pb, "3gp4");
1253     else if ( mov->mode == MODE_3G2 )
1254         put_tag(pb, "3g2a");
1255     else if ( mov->mode == MODE_PSP )
1256         put_tag(pb, "MSNV");
1257     else
1258         put_tag(pb, "isom");
1259
1260     put_be32(pb, 0x200 );
1261
1262     if ( mov->mode == MODE_3GP )
1263         put_tag(pb, "3gp4");
1264     else if ( mov->mode == MODE_3G2 )
1265         put_tag(pb, "3g2a");
1266     else if ( mov->mode == MODE_PSP )
1267         put_tag(pb, "MSNV");
1268     else
1269         put_tag(pb, "mp41");
1270
1271     return 0x14;
1272 }
1273
1274 static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1275 {
1276     int AudioRate = s->streams[1]->codec->sample_rate;
1277     int FrameRate = ((s->streams[0]->codec->time_base.den) * (0x10000))/ (s->streams[0]->codec->time_base.num);
1278
1279     //printf("audiorate = %d\n",AudioRate);
1280     //printf("framerate = %d / %d = 0x%x\n",s->streams[0]->codec->time_base.den,s->streams[0]->codec->time_base.num,FrameRate);
1281
1282     put_be32(pb, 0x94 ); /* size */
1283     put_tag(pb, "uuid");
1284     put_tag(pb, "PROF");
1285
1286     put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1287     put_be32(pb, 0xbb88695c );
1288     put_be32(pb, 0xfac9c740 );
1289
1290     put_be32(pb, 0x0 );  /* ? */
1291     put_be32(pb, 0x3 );  /* 3 sections ? */
1292
1293     put_be32(pb, 0x14 ); /* size */
1294     put_tag(pb, "FPRF");
1295     put_be32(pb, 0x0 );  /* ? */
1296     put_be32(pb, 0x0 );  /* ? */
1297     put_be32(pb, 0x0 );  /* ? */
1298
1299     put_be32(pb, 0x2c );  /* size */
1300     put_tag(pb, "APRF");   /* audio */
1301     put_be32(pb, 0x0 );
1302     put_be32(pb, 0x2 );
1303     put_tag(pb, "mp4a");
1304     put_be32(pb, 0x20f );
1305     put_be32(pb, 0x0 );
1306     put_be32(pb, 0x40 );
1307     put_be32(pb, 0x40 );
1308     put_be32(pb, AudioRate ); //24000   ... audio rate?
1309     put_be32(pb, 0x2 );
1310
1311     put_be32(pb, 0x34 );  /* size */
1312     put_tag(pb, "VPRF");   /* video */
1313     put_be32(pb, 0x0 );
1314     put_be32(pb, 0x1 );
1315     put_tag(pb, "mp4v");
1316     put_be32(pb, 0x103 );
1317     put_be32(pb, 0x0 );
1318     put_be32(pb, 0xc0 );
1319     put_be32(pb, 0xc0 );
1320     put_be32(pb, FrameRate);  // was 0xefc29
1321     put_be32(pb, FrameRate );  // was 0xefc29
1322     put_be16(pb, s->streams[0]->codec->width);
1323     put_be16(pb, s->streams[0]->codec->height);
1324     put_be32(pb, 0x010001 );
1325 }
1326
1327 static int mov_write_header(AVFormatContext *s)
1328 {
1329     ByteIOContext *pb = &s->pb;
1330     MOVContext *mov = s->priv_data;
1331     int i;
1332
1333     for(i=0; i<s->nb_streams; i++){
1334         AVCodecContext *c= s->streams[i]->codec;
1335
1336         if      (c->codec_type == CODEC_TYPE_VIDEO){
1337             if (!codec_get_tag(codec_movvideo_tags, c->codec_id)){
1338                 if(!codec_get_tag(codec_bmp_tags, c->codec_id))
1339                     return -1;
1340                 else
1341                     av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, the file may be unplayable!\n");
1342             }
1343         }else if(c->codec_type == CODEC_TYPE_AUDIO){
1344             if (!codec_get_tag(codec_movaudio_tags, c->codec_id)){
1345                 if(!codec_get_tag(codec_wav_tags, c->codec_id))
1346                     return -1;
1347                 else
1348                     av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, the file may be unplayable!\n");
1349             }
1350         }
1351         /* don't know yet if mp4 or not */
1352         mov->tracks[i].language = ff_mov_iso639_to_lang(s->streams[i]->language, 1);
1353     }
1354
1355     /* Default mode == MP4 */
1356     mov->mode = MODE_MP4;
1357
1358     if (s->oformat != NULL) {
1359         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1360         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3G2;
1361         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1362         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1363
1364         if ( mov->mode == MODE_3GP || mov->mode == MODE_3G2 ||
1365              mov->mode == MODE_MP4 || mov->mode == MODE_PSP )
1366             mov_write_ftyp_tag(pb,s);
1367         if ( mov->mode == MODE_PSP ) {
1368             if ( s->nb_streams != 2 ) {
1369                 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1370                 return -1;
1371             }
1372             mov_write_uuidprof_tag(pb,s);
1373         }
1374     }
1375
1376     for (i=0; i<MAX_STREAMS; i++) {
1377         mov->tracks[i].mode = mov->mode;
1378     }
1379
1380     put_flush_packet(pb);
1381
1382     return 0;
1383 }
1384
1385 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1386 {
1387     MOVContext *mov = s->priv_data;
1388     ByteIOContext *pb = &s->pb;
1389     AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
1390     MOVTrack* trk = &mov->tracks[pkt->stream_index];
1391     int cl, id;
1392     unsigned int samplesInChunk = 0;
1393     int size= pkt->size;
1394
1395     if (url_is_streamed(&s->pb)) return 0; /* Can't handle that */
1396     if (!size) return 0; /* Discard 0 sized packets */
1397
1398     if (enc->codec_type == CODEC_TYPE_VIDEO ) {
1399         samplesInChunk = 1;
1400     }
1401     else if (enc->codec_type == CODEC_TYPE_AUDIO ) {
1402         if( enc->codec_id == CODEC_ID_AMR_NB) {
1403             /* We must find out how many AMR blocks there are in one packet */
1404             static uint16_t packed_size[16] =
1405                 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1406             int len = 0;
1407
1408             while (len < size && samplesInChunk < 100) {
1409                 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1410                 samplesInChunk++;
1411             }
1412         }
1413         else if(enc->codec_id == CODEC_ID_PCM_ALAW) {
1414             samplesInChunk = size/enc->channels;
1415         }
1416         else if(enc->codec_id == CODEC_ID_PCM_S16BE || enc->codec_id == CODEC_ID_PCM_S16LE) {
1417             samplesInChunk = size/(2*enc->channels);
1418         }
1419         else {
1420             samplesInChunk = 1;
1421         }
1422     }
1423
1424     if ((enc->codec_id == CODEC_ID_MPEG4 || enc->codec_id == CODEC_ID_AAC)
1425         && trk->vosLen == 0) {
1426 //        assert(enc->extradata_size);
1427
1428         trk->vosLen = enc->extradata_size;
1429         trk->vosData = av_malloc(trk->vosLen);
1430         memcpy(trk->vosData, enc->extradata, trk->vosLen);
1431     }
1432
1433     cl = trk->entry / MOV_INDEX_CLUSTER_SIZE;
1434     id = trk->entry % MOV_INDEX_CLUSTER_SIZE;
1435
1436     if (trk->ents_allocated <= trk->entry) {
1437         trk->cluster = av_realloc(trk->cluster, (cl+1)*sizeof(void*));
1438         if (!trk->cluster)
1439             return -1;
1440         trk->cluster[cl] = av_malloc(MOV_INDEX_CLUSTER_SIZE*sizeof(MOVIentry));
1441         if (!trk->cluster[cl])
1442             return -1;
1443         trk->ents_allocated += MOV_INDEX_CLUSTER_SIZE;
1444     }
1445     if (mov->mdat_written == 0) {
1446         mov_write_mdat_tag(pb, mov);
1447         mov->mdat_written = 1;
1448         mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1449     }
1450
1451     trk->cluster[cl][id].pos = url_ftell(pb);
1452     trk->cluster[cl][id].samplesInChunk = samplesInChunk;
1453     trk->cluster[cl][id].size = size;
1454     trk->cluster[cl][id].entries = samplesInChunk;
1455     if(enc->codec_type == CODEC_TYPE_VIDEO) {
1456         trk->cluster[cl][id].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1457         if(trk->cluster[cl][id].key_frame)
1458             trk->hasKeyframes = 1;
1459     }
1460     trk->enc = enc;
1461     trk->entry++;
1462     trk->sampleCount += samplesInChunk;
1463     trk->mdat_size += size;
1464
1465     put_buffer(pb, pkt->data, size);
1466
1467     put_flush_packet(pb);
1468     return 0;
1469 }
1470
1471 static int mov_write_trailer(AVFormatContext *s)
1472 {
1473     MOVContext *mov = s->priv_data;
1474     ByteIOContext *pb = &s->pb;
1475     int res = 0;
1476     int i;
1477     uint64_t j;
1478
1479     offset_t moov_pos = url_ftell(pb);
1480
1481     /* Write size of mdat tag */
1482     for (i=0, j=0; i<MAX_STREAMS; i++) {
1483         if(mov->tracks[i].ents_allocated > 0) {
1484             j += mov->tracks[i].mdat_size;
1485         }
1486     }
1487     if (j+8 <= UINT32_MAX) {
1488         url_fseek(pb, mov->mdat_pos, SEEK_SET);
1489         put_be32(pb, j+8);
1490     } else {
1491         /* overwrite 'wide' placeholder atom */
1492         url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1493         put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1494         put_tag(pb, "mdat");
1495         put_be64(pb, j+16);
1496     }
1497     url_fseek(pb, moov_pos, SEEK_SET);
1498
1499     mov_write_moov_tag(pb, mov, s);
1500
1501     for (i=0; i<MAX_STREAMS; i++) {
1502         for (j=0; j<mov->tracks[i].ents_allocated/MOV_INDEX_CLUSTER_SIZE; j++) {
1503             av_free(mov->tracks[i].cluster[j]);
1504         }
1505         av_free(mov->tracks[i].cluster);
1506         if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1507
1508         mov->tracks[i].cluster = NULL;
1509         mov->tracks[i].ents_allocated = mov->tracks[i].entry = 0;
1510     }
1511
1512     put_flush_packet(pb);
1513
1514     return res;
1515 }
1516
1517 static AVOutputFormat mov_oformat = {
1518     "mov",
1519     "mov format",
1520     NULL,
1521     "mov",
1522     sizeof(MOVContext),
1523     CODEC_ID_AAC,
1524     CODEC_ID_MPEG4,
1525     mov_write_header,
1526     mov_write_packet,
1527     mov_write_trailer,
1528     .flags = AVFMT_GLOBALHEADER,
1529 };
1530
1531 static AVOutputFormat _3gp_oformat = {
1532     "3gp",
1533     "3gp format",
1534     NULL,
1535     "3gp",
1536     sizeof(MOVContext),
1537     CODEC_ID_AMR_NB,
1538     CODEC_ID_H263,
1539     mov_write_header,
1540     mov_write_packet,
1541     mov_write_trailer,
1542     .flags = AVFMT_GLOBALHEADER,
1543 };
1544
1545 static AVOutputFormat mp4_oformat = {
1546     "mp4",
1547     "mp4 format",
1548     "application/mp4",
1549     "mp4,m4a",
1550     sizeof(MOVContext),
1551     CODEC_ID_AAC,
1552     CODEC_ID_MPEG4,
1553     mov_write_header,
1554     mov_write_packet,
1555     mov_write_trailer,
1556     .flags = AVFMT_GLOBALHEADER,
1557 };
1558
1559 static AVOutputFormat psp_oformat = {
1560     "psp",
1561     "psp mp4 format",
1562     NULL,
1563     "mp4,psp",
1564     sizeof(MOVContext),
1565     CODEC_ID_AAC,
1566     CODEC_ID_MPEG4,
1567     mov_write_header,
1568     mov_write_packet,
1569     mov_write_trailer,
1570 //    .flags = AVFMT_GLOBALHEADER,
1571 };
1572
1573 static AVOutputFormat _3g2_oformat = {
1574     "3g2",
1575     "3gp2 format",
1576     NULL,
1577     "3g2",
1578     sizeof(MOVContext),
1579     CODEC_ID_AMR_NB,
1580     CODEC_ID_H263,
1581     mov_write_header,
1582     mov_write_packet,
1583     mov_write_trailer,
1584     .flags = AVFMT_GLOBALHEADER,
1585 };
1586
1587 int movenc_init(void)
1588 {
1589     av_register_output_format(&mov_oformat);
1590     av_register_output_format(&_3gp_oformat);
1591     av_register_output_format(&mp4_oformat);
1592     av_register_output_format(&psp_oformat);
1593     av_register_output_format(&_3g2_oformat);
1594     return 0;
1595 }