Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ e1315fb1

History | View | Annotate | Download (51.8 KB)

1
/*
2
 * MOV, 3GP, MP4 muxer
3
 * Copyright (c) 2003 Thomas Raivio.
4
 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>.
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22
#include "avformat.h"
23
#include "riff.h"
24
#include "avio.h"
25
#include "isom.h"
26

    
27
#undef NDEBUG
28
#include <assert.h>
29

    
30
#define MOV_INDEX_CLUSTER_SIZE 16384
31
#define globalTimescale 1000
32

    
33
#define MODE_MP4 0
34
#define MODE_MOV 1
35
#define MODE_3GP 2
36
#define MODE_PSP 3 // example working PSP command line:
37
// ffmpeg -i testinput.avi  -f psp -r 14.985 -s 320x240 -b 768 -ar 24000 -ab 32 M4V00001.MP4
38
#define MODE_3G2 4
39

    
40
typedef struct MOVIentry {
41
    unsigned int flags, size;
42
    uint64_t     pos;
43
    unsigned int samplesInChunk;
44
    char         key_frame;
45
    unsigned int entries;
46
    int64_t      cts;
47
    int64_t      dts;
48
} MOVIentry;
49

    
50
typedef struct MOVIndex {
51
    int         mode;
52
    int         entry;
53
    long        timescale;
54
    long        time;
55
    int64_t     trackDuration;
56
    long        sampleCount;
57
    long        sampleSize;
58
    int         hasKeyframes;
59
    int         hasBframes;
60
    int         language;
61
    int         trackID;
62
    int         tag;
63
    AVCodecContext *enc;
64

    
65
    int         vosLen;
66
    uint8_t     *vosData;
67
    MOVIentry   *cluster;
68
    int         audio_vbr;
69
} MOVTrack;
70

    
71
typedef struct MOVContext {
72
    int     mode;
73
    int64_t time;
74
    int     nb_streams;
75
    offset_t mdat_pos;
76
    uint64_t mdat_size;
77
    long    timescale;
78
    MOVTrack tracks[MAX_STREAMS];
79
} MOVContext;
80

    
81
//FIXME supprt 64bit varaint with wide placeholders
82
static offset_t updateSize (ByteIOContext *pb, offset_t pos)
83
{
84
    offset_t curpos = url_ftell(pb);
85
    url_fseek(pb, pos, SEEK_SET);
86
    put_be32(pb, curpos - pos); /* rewrite size */
87
    url_fseek(pb, curpos, SEEK_SET);
88

    
89
    return curpos - pos;
90
}
91

    
92
/* Chunk offset atom */
93
static int mov_write_stco_tag(ByteIOContext *pb, MOVTrack* track)
94
{
95
    int i;
96
    int mode64 = 0; //   use 32 bit size variant if possible
97
    offset_t pos = url_ftell(pb);
98
    put_be32(pb, 0); /* size */
99
    if (pos > UINT32_MAX) {
100
        mode64 = 1;
101
        put_tag(pb, "co64");
102
    } else
103
        put_tag(pb, "stco");
104
    put_be32(pb, 0); /* version & flags */
105
    put_be32(pb, track->entry); /* entry count */
106
    for (i=0; i<track->entry; i++) {
107
        if(mode64 == 1)
108
            put_be64(pb, track->cluster[i].pos);
109
        else
110
            put_be32(pb, track->cluster[i].pos);
111
    }
112
    return updateSize (pb, pos);
113
}
114

    
115
/* Sample size atom */
116
static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack* track)
117
{
118
    int equalChunks = 1;
119
    int i, j, entries = 0, tst = -1, oldtst = -1;
120

    
121
    offset_t pos = url_ftell(pb);
122
    put_be32(pb, 0); /* size */
123
    put_tag(pb, "stsz");
124
    put_be32(pb, 0); /* version & flags */
125

    
126
    for (i=0; i<track->entry; i++) {
127
        tst = track->cluster[i].size/track->cluster[i].entries;
128
        if(oldtst != -1 && tst != oldtst) {
129
            equalChunks = 0;
130
        }
131
        oldtst = tst;
132
        entries += track->cluster[i].entries;
133
    }
134
    if (equalChunks) {
135
        int sSize = track->cluster[0].size/track->cluster[0].entries;
136
        put_be32(pb, sSize); // sample size
137
        put_be32(pb, entries); // sample count
138
    }
139
    else {
140
        put_be32(pb, 0); // sample size
141
        put_be32(pb, entries); // sample count
142
        for (i=0; i<track->entry; i++) {
143
            for ( j=0; j<track->cluster[i].entries; j++) {
144
                put_be32(pb, track->cluster[i].size /
145
                         track->cluster[i].entries);
146
            }
147
        }
148
    }
149
    return updateSize (pb, pos);
150
}
151

    
152
/* Sample to chunk atom */
153
static int mov_write_stsc_tag(ByteIOContext *pb, MOVTrack* track)
154
{
155
    int index = 0, oldval = -1, i;
156
    offset_t entryPos, curpos;
157

    
158
    offset_t pos = url_ftell(pb);
159
    put_be32(pb, 0); /* size */
160
    put_tag(pb, "stsc");
161
    put_be32(pb, 0); // version & flags
162
    entryPos = url_ftell(pb);
163
    put_be32(pb, track->entry); // entry count
164
    for (i=0; i<track->entry; i++) {
165
        if(oldval != track->cluster[i].samplesInChunk)
166
        {
167
            put_be32(pb, i+1); // first chunk
168
            put_be32(pb, track->cluster[i].samplesInChunk); // samples per chunk
169
            put_be32(pb, 0x1); // sample description index
170
            oldval = track->cluster[i].samplesInChunk;
171
            index++;
172
        }
173
    }
174
    curpos = url_ftell(pb);
175
    url_fseek(pb, entryPos, SEEK_SET);
176
    put_be32(pb, index); // rewrite size
177
    url_fseek(pb, curpos, SEEK_SET);
178

    
179
    return updateSize (pb, pos);
180
}
181

    
182
/* Sync sample atom */
183
static int mov_write_stss_tag(ByteIOContext *pb, MOVTrack* track)
184
{
185
    offset_t curpos, entryPos;
186
    int i, index = 0;
187
    offset_t pos = url_ftell(pb);
188
    put_be32(pb, 0); // size
189
    put_tag(pb, "stss");
190
    put_be32(pb, 0); // version & flags
191
    entryPos = url_ftell(pb);
192
    put_be32(pb, track->entry); // entry count
193
    for (i=0; i<track->entry; i++) {
194
        if(track->cluster[i].key_frame == 1) {
195
            put_be32(pb, i+1);
196
            index++;
197
        }
198
    }
199
    curpos = url_ftell(pb);
200
    url_fseek(pb, entryPos, SEEK_SET);
201
    put_be32(pb, index); // rewrite size
202
    url_fseek(pb, curpos, SEEK_SET);
203
    return updateSize (pb, pos);
204
}
205

    
206
static int mov_write_amr_tag(ByteIOContext *pb, MOVTrack *track)
207
{
208
    put_be32(pb, 0x11); /* size */
209
    if (track->mode == MODE_MOV) put_tag(pb, "samr");
210
    else                         put_tag(pb, "damr");
211
    put_tag(pb, "FFMP");
212
    put_byte(pb, 0); /* decoder version */
213

    
214
    put_be16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
215
    put_byte(pb, 0x00); /* Mode change period (no restriction) */
216
    put_byte(pb, 0x01); /* Frames per sample */
217
    return 0x11;
218
}
219

    
220
static int mov_write_enda_tag(ByteIOContext *pb)
221
{
222
    put_be32(pb, 10);
223
    put_tag(pb, "enda");
224
    put_be16(pb, 1); /* little endian */
225
    return 10;
226
}
227

    
228
static unsigned int descrLength(unsigned int len)
229
{
230
    int i;
231
    for(i=1; len>>(7*i); i++);
232
    return len + 1 + i;
233
}
234

    
235
static void putDescr(ByteIOContext *pb, int tag, unsigned int size)
236
{
237
    int i= descrLength(size) - size - 2;
238
    put_byte(pb, tag);
239
    for(; i>0; i--)
240
        put_byte(pb, (size>>(7*i)) | 0x80);
241
    put_byte(pb, size & 0x7F);
242
}
243

    
244
static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track) // Basic
245
{
246
    offset_t pos = url_ftell(pb);
247
    int decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
248

    
249
    put_be32(pb, 0);               // size
250
    put_tag(pb, "esds");
251
    put_be32(pb, 0);               // Version
252

    
253
    // ES descriptor
254
    putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
255
             descrLength(1));
256
    put_be16(pb, track->trackID);
257
    put_byte(pb, 0x00);            // flags (= no flags)
258

    
259
    // DecoderConfig descriptor
260
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
261

    
262
    // Object type indication
263
    put_byte(pb, codec_get_tag(ff_mov_obj_type, track->enc->codec_id));
264

    
265
    // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
266
    // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
267
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
268
        put_byte(pb, 0x15);            // flags (= Audiostream)
269
    else
270
        put_byte(pb, 0x11);            // flags (= Visualstream)
271

    
272
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));             // Buffersize DB (24 bits)
273
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF);          // Buffersize DB
274

    
275
    put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate));     // maxbitrate  (FIXME should be max rate in any 1 sec window)
276
    if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
277
        put_be32(pb, 0);     // vbr
278
    else
279
        put_be32(pb, track->enc->rc_max_rate);     // avg bitrate
280

    
281
    if (track->vosLen)
282
    {
283
        // DecoderSpecific info descriptor
284
        putDescr(pb, 0x05, track->vosLen);
285
        put_buffer(pb, track->vosData, track->vosLen);
286
    }
287

    
288

    
289
    // SL descriptor
290
    putDescr(pb, 0x06, 1);
291
    put_byte(pb, 0x02);
292
    return updateSize (pb, pos);
293
}
294

    
295
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack* track)
296
{
297
    offset_t pos = url_ftell(pb);
298

    
299
    put_be32(pb, 0);     /* size */
300
    put_tag(pb, "wave");
301

    
302
    put_be32(pb, 12);    /* size */
303
    put_tag(pb, "frma");
304
    put_le32(pb, track->tag);
305

    
306
    if (track->enc->codec_id == CODEC_ID_AAC) {
307
        /* useless atom needed by mplayer, ipod, not needed by quicktime */
308
        put_be32(pb, 12); /* size */
309
        put_tag(pb, "mp4a");
310
        put_be32(pb, 0);
311
        mov_write_esds_tag(pb, track);
312
    } else if (track->enc->codec_id == CODEC_ID_PCM_S24LE ||
313
               track->enc->codec_id == CODEC_ID_PCM_S32LE) {
314
        mov_write_enda_tag(pb);
315
    } else if (track->enc->codec_id == CODEC_ID_AMR_NB) {
316
        mov_write_amr_tag(pb, track);
317
    }
318

    
319
    put_be32(pb, 8);     /* size */
320
    put_be32(pb, 0);     /* null tag */
321

    
322
    return updateSize (pb, pos);
323
}
324

    
325
static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack* track)
326
{
327
    offset_t pos = url_ftell(pb);
328
    int version = track->mode == MODE_MOV &&
329
        (track->audio_vbr ||
330
         track->enc->codec_id == CODEC_ID_PCM_S32LE ||
331
         track->enc->codec_id == CODEC_ID_PCM_S24LE);
332

    
333
    put_be32(pb, 0); /* size */
334
    put_le32(pb, track->tag); // store it byteswapped
335
    put_be32(pb, 0); /* Reserved */
336
    put_be16(pb, 0); /* Reserved */
337
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
338

    
339
    /* SoundDescription */
340
    put_be16(pb, version); /* Version */
341
    put_be16(pb, 0); /* Revision level */
342
    put_be32(pb, 0); /* Reserved */
343

    
344
    if (track->mode == MODE_MOV) {
345
        put_be16(pb, track->enc->channels);
346
        if (track->enc->codec_id == CODEC_ID_PCM_U8 ||
347
            track->enc->codec_id == CODEC_ID_PCM_S8)
348
            put_be16(pb, 8); /* bits per sample */
349
        else
350
            put_be16(pb, 16);
351
        put_be16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
352
    } else { /* reserved for mp4/3gp */
353
        put_be16(pb, 2);
354
        put_be16(pb, 16);
355
        put_be16(pb, 0);
356
    }
357

    
358
    put_be16(pb, 0); /* packet size (= 0) */
359
    put_be16(pb, track->timescale); /* Time scale */
360
    put_be16(pb, 0); /* Reserved */
361

    
362
    if(version == 1) { /* SoundDescription V1 extended info */
363
        put_be32(pb, track->enc->frame_size); /* Samples per packet */
364
        put_be32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
365
        put_be32(pb, track->sampleSize); /* Bytes per frame */
366
        put_be32(pb, 2); /* Bytes per sample */
367
    }
368

    
369
    if(track->mode == MODE_MOV &&
370
       (track->enc->codec_id == CODEC_ID_AAC ||
371
        track->enc->codec_id == CODEC_ID_AMR_NB ||
372
        track->enc->codec_id == CODEC_ID_PCM_S24LE ||
373
        track->enc->codec_id == CODEC_ID_PCM_S32LE))
374
        mov_write_wave_tag(pb, track);
375
    else if(track->enc->codec_id == CODEC_ID_AAC)
376
        mov_write_esds_tag(pb, track);
377
    else if(track->enc->codec_id == CODEC_ID_AMR_NB)
378
        mov_write_amr_tag(pb, track);
379

    
380
    return updateSize (pb, pos);
381
}
382

    
383
static int mov_write_d263_tag(ByteIOContext *pb)
384
{
385
    put_be32(pb, 0xf); /* size */
386
    put_tag(pb, "d263");
387
    put_tag(pb, "FFMP");
388
    put_byte(pb, 0); /* decoder version */
389
    /* FIXME use AVCodecContext level/profile, when encoder will set values */
390
    put_byte(pb, 0xa); /* level */
391
    put_byte(pb, 0); /* profile */
392
    return 0xf;
393
}
394

    
395
/* TODO: No idea about these values */
396
static int mov_write_svq3_tag(ByteIOContext *pb)
397
{
398
    put_be32(pb, 0x15);
399
    put_tag(pb, "SMI ");
400
    put_tag(pb, "SEQH");
401
    put_be32(pb, 0x5);
402
    put_be32(pb, 0xe2c0211d);
403
    put_be32(pb, 0xc0000000);
404
    put_byte(pb, 0);
405
    return 0x15;
406
}
407

    
408
static uint8_t *avc_find_startcode( uint8_t *p, uint8_t *end )
409
{
410
    uint8_t *a = p + 4 - ((int)p & 3);
411

    
412
    for( end -= 3; p < a && p < end; p++ ) {
413
        if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
414
            return p;
415
    }
416

    
417
    for( end -= 3; p < end; p += 4 ) {
418
        uint32_t x = *(uint32_t*)p;
419
//      if( (x - 0x01000100) & (~x) & 0x80008000 ) // little endian
420
//      if( (x - 0x00010001) & (~x) & 0x00800080 ) // big endian
421
        if( (x - 0x01010101) & (~x) & 0x80808080 ) { // generic
422
            if( p[1] == 0 ) {
423
                if( p[0] == 0 && p[2] == 1 )
424
                    return p-1;
425
                if( p[2] == 0 && p[3] == 1 )
426
                    return p;
427
            }
428
            if( p[3] == 0 ) {
429
                if( p[2] == 0 && p[4] == 1 )
430
                    return p+1;
431
                if( p[4] == 0 && p[5] == 1 )
432
                    return p+2;
433
            }
434
        }
435
    }
436

    
437
    for( end += 3; p < end; p++ ) {
438
        if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
439
            return p;
440
    }
441

    
442
    return end + 3;
443
}
444

    
445
static void avc_parse_nal_units(uint8_t **buf, int *size)
446
{
447
    ByteIOContext pb;
448
    uint8_t *p = *buf;
449
    uint8_t *end = p + *size;
450
    uint8_t *nal_start, *nal_end;
451

    
452
    url_open_dyn_buf(&pb);
453
    nal_start = avc_find_startcode(p, end);
454
    while (nal_start < end) {
455
        while(!*(nal_start++));
456
        nal_end = avc_find_startcode(nal_start, end);
457
        put_be32(&pb, nal_end - nal_start);
458
        put_buffer(&pb, nal_start, nal_end - nal_start);
459
        nal_start = nal_end;
460
    }
461
    av_freep(buf);
462
    *size = url_close_dyn_buf(&pb, buf);
463
}
464

    
465
static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
466
{
467
    offset_t pos = url_ftell(pb);
468

    
469
    put_be32(pb, 0);
470
    put_tag(pb, "avcC");
471
    if (track->vosLen > 6) {
472
        /* check for h264 start code */
473
        if (AV_RB32(track->vosData) == 0x00000001) {
474
            uint8_t *buf, *end;
475
            uint32_t sps_size=0, pps_size=0;
476
            uint8_t *sps=0, *pps=0;
477

    
478
            avc_parse_nal_units(&track->vosData, &track->vosLen);
479
            buf = track->vosData;
480
            end = track->vosData + track->vosLen;
481

    
482
            /* look for sps and pps */
483
            while (buf < end) {
484
                unsigned int size;
485
                uint8_t nal_type;
486
                size = AV_RB32(buf);
487
                nal_type = buf[4] & 0x1f;
488
                if (nal_type == 7) { /* SPS */
489
                    sps = buf + 4;
490
                    sps_size = size;
491
                } else if (nal_type == 8) { /* PPS */
492
                    pps = buf + 4;
493
                    pps_size = size;
494
                }
495
                buf += size + 4;
496
            }
497
            assert(sps);
498
            assert(pps);
499

    
500
            put_byte(pb, 1); /* version */
501
            put_byte(pb, sps[1]); /* profile */
502
            put_byte(pb, sps[2]); /* profile compat */
503
            put_byte(pb, sps[3]); /* level */
504
            put_byte(pb, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 1 (11) */
505
            put_byte(pb, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
506

    
507
            put_be16(pb, sps_size);
508
            put_buffer(pb, sps, sps_size);
509
            put_byte(pb, 1); /* number of pps */
510
            put_be16(pb, pps_size);
511
            put_buffer(pb, pps, pps_size);
512
        } else {
513
            put_buffer(pb, track->vosData, track->vosLen);
514
        }
515
    }
516
    return updateSize(pb, pos);
517
}
518

    
519
static int mov_find_video_codec_tag(AVFormatContext *s, MOVTrack *track)
520
{
521
    int tag = track->enc->codec_tag;
522
    if (!tag) {
523
        if (track->enc->codec_id == CODEC_ID_DVVIDEO) {
524
            if (track->enc->height == 480) { /* NTSC */
525
                if (track->enc->pix_fmt == PIX_FMT_YUV422P)
526
                    tag = MKTAG('d', 'v', '5', 'n');
527
                else
528
                    tag = MKTAG('d', 'v', 'c', ' ');
529
            } else { /* assume PAL */
530
                if (track->enc->pix_fmt == PIX_FMT_YUV422P)
531
                    tag = MKTAG('d', 'v', '5', 'p');
532
                else if (track->enc->pix_fmt == PIX_FMT_YUV420P)
533
                    tag = MKTAG('d', 'v', 'c', 'p');
534
                else
535
                    tag = MKTAG('d', 'v', 'p', 'p');
536
            }
537
        } else if (track->enc->codec_id == CODEC_ID_H263) {
538
            if (track->mode == MODE_MOV)
539
                tag = MKTAG('h', '2', '6', '3');
540
            else
541
                tag = MKTAG('s', '2', '6', '3');
542
        } else {
543
            tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
544
        }
545
    }
546
    // if no mac fcc found, try with Microsoft tags
547
    if (!tag) {
548
        tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
549
        if (tag) {
550
            av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, the file may be unplayable!\n");
551
        }
552
    }
553
    assert(tag);
554
    return tag;
555
}
556

    
557
static int mov_find_audio_codec_tag(AVFormatContext *s, MOVTrack *track)
558
{
559
    int tag = track->enc->codec_tag;
560
    if (!tag) {
561
        tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
562
    }
563
    // if no mac fcc found, try with Microsoft tags
564
    if (!tag) {
565
        int ms_tag = codec_get_tag(codec_wav_tags, track->enc->codec_id);
566
        if (ms_tag) {
567
            tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
568
            av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, the file may be unplayable!\n");
569
        }
570
    }
571
    assert(tag);
572
    return tag;
573
}
574

    
575
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
576
{
577
    offset_t pos = url_ftell(pb);
578
    char compressor_name[32];
579

    
580
    put_be32(pb, 0); /* size */
581
    put_le32(pb, track->tag); // store it byteswapped
582
    put_be32(pb, 0); /* Reserved */
583
    put_be16(pb, 0); /* Reserved */
584
    put_be16(pb, 1); /* Data-reference index */
585

    
586
    put_be16(pb, 0); /* Codec stream version */
587
    put_be16(pb, 0); /* Codec stream revision (=0) */
588
    if (track->mode == MODE_MOV) {
589
        put_tag(pb, "FFMP"); /* Vendor */
590
        if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
591
            put_be32(pb, 0); /* Temporal Quality */
592
            put_be32(pb, 0x400); /* Spatial Quality = lossless*/
593
        } else {
594
            put_be32(pb, 0x200); /* Temporal Quality = normal */
595
            put_be32(pb, 0x200); /* Spatial Quality = normal */
596
        }
597
    } else {
598
        put_be32(pb, 0); /* Reserved */
599
        put_be32(pb, 0); /* Reserved */
600
        put_be32(pb, 0); /* Reserved */
601
    }
602
    put_be16(pb, track->enc->width); /* Video width */
603
    put_be16(pb, track->enc->height); /* Video height */
604
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
605
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
606
    put_be32(pb, 0); /* Data size (= 0) */
607
    put_be16(pb, 1); /* Frame count (= 1) */
608

    
609
    memset(compressor_name,0,32);
610
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
611
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
612
        strncpy(compressor_name,track->enc->codec->name,31);
613
    put_byte(pb, strlen(compressor_name));
614
    put_buffer(pb, compressor_name, 31);
615

    
616
    put_be16(pb, 0x18); /* Reserved */
617
    put_be16(pb, 0xffff); /* Reserved */
618
    if(track->enc->codec_id == CODEC_ID_MPEG4)
619
        mov_write_esds_tag(pb, track);
620
    else if(track->enc->codec_id == CODEC_ID_H263)
621
        mov_write_d263_tag(pb);
622
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
623
        mov_write_svq3_tag(pb);
624
    else if(track->enc->codec_id == CODEC_ID_H264)
625
        mov_write_avcc_tag(pb, track);
626

    
627
    return updateSize (pb, pos);
628
}
629

    
630
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack* track)
631
{
632
    offset_t pos = url_ftell(pb);
633
    put_be32(pb, 0); /* size */
634
    put_tag(pb, "stsd");
635
    put_be32(pb, 0); /* version & flags */
636
    put_be32(pb, 1); /* entry count */
637
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
638
        mov_write_video_tag(pb, track);
639
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
640
        mov_write_audio_tag(pb, track);
641
    return updateSize(pb, pos);
642
}
643

    
644
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack* track)
645
{
646
    Time2Sample *ctts_entries;
647
    uint32_t entries = 0;
648
    uint32_t atom_size;
649
    int i;
650

    
651
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
652
    ctts_entries[0].count = 1;
653
    ctts_entries[0].duration = track->cluster[0].cts;
654
    for (i=1; i<track->entry; i++) {
655
        if (track->cluster[i].cts == ctts_entries[entries].duration) {
656
            ctts_entries[entries].count++; /* compress */
657
        } else {
658
            entries++;
659
            ctts_entries[entries].duration = track->cluster[i].cts;
660
            ctts_entries[entries].count = 1;
661
        }
662
    }
663
    entries++; /* last one */
664
    atom_size = 16 + (entries * 8);
665
    put_be32(pb, atom_size); /* size */
666
    put_tag(pb, "ctts");
667
    put_be32(pb, 0); /* version & flags */
668
    put_be32(pb, entries); /* entry count */
669
    for (i=0; i<entries; i++) {
670
        put_be32(pb, ctts_entries[i].count);
671
        put_be32(pb, ctts_entries[i].duration);
672
    }
673
    av_free(ctts_entries);
674
    return atom_size;
675
}
676

    
677
/* Time to sample atom */
678
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack* track)
679
{
680
    Time2Sample *stts_entries;
681
    uint32_t entries = -1;
682
    uint32_t atom_size;
683
    int i;
684

    
685
    if (track->enc->codec_type == CODEC_TYPE_AUDIO && !track->audio_vbr) {
686
        stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
687
        stts_entries[0].count = track->sampleCount;
688
        stts_entries[0].duration = 1;
689
        entries = 1;
690
    } else {
691
        stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
692
        for (i=0; i<track->entry; i++) {
693
            int64_t duration = i + 1 == track->entry ?
694
                track->trackDuration - track->cluster[i].dts + track->cluster[0].dts : /* readjusting */
695
                track->cluster[i+1].dts - track->cluster[i].dts;
696
            if (i && duration == stts_entries[entries].duration) {
697
                stts_entries[entries].count++; /* compress */
698
            } else {
699
                entries++;
700
                stts_entries[entries].duration = duration;
701
                stts_entries[entries].count = 1;
702
            }
703
        }
704
        entries++; /* last one */
705
    }
706
    atom_size = 16 + (entries * 8);
707
    put_be32(pb, atom_size); /* size */
708
    put_tag(pb, "stts");
709
    put_be32(pb, 0); /* version & flags */
710
    put_be32(pb, entries); /* entry count */
711
    for (i=0; i<entries; i++) {
712
        put_be32(pb, stts_entries[i].count);
713
        put_be32(pb, stts_entries[i].duration);
714
    }
715
    av_free(stts_entries);
716
    return atom_size;
717
}
718

    
719
static int mov_write_dref_tag(ByteIOContext *pb)
720
{
721
    put_be32(pb, 28); /* size */
722
    put_tag(pb, "dref");
723
    put_be32(pb, 0); /* version & flags */
724
    put_be32(pb, 1); /* entry count */
725

    
726
    put_be32(pb, 0xc); /* size */
727
    put_tag(pb, "url ");
728
    put_be32(pb, 1); /* version & flags */
729

    
730
    return 28;
731
}
732

    
733
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track)
734
{
735
    offset_t pos = url_ftell(pb);
736
    put_be32(pb, 0); /* size */
737
    put_tag(pb, "stbl");
738
    mov_write_stsd_tag(pb, track);
739
    mov_write_stts_tag(pb, track);
740
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
741
        track->hasKeyframes < track->entry)
742
        mov_write_stss_tag(pb, track);
743
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
744
        track->hasBframes)
745
        mov_write_ctts_tag(pb, track);
746
    mov_write_stsc_tag(pb, track);
747
    mov_write_stsz_tag(pb, track);
748
    mov_write_stco_tag(pb, track);
749
    return updateSize(pb, pos);
750
}
751

    
752
static int mov_write_dinf_tag(ByteIOContext *pb)
753
{
754
    offset_t pos = url_ftell(pb);
755
    put_be32(pb, 0); /* size */
756
    put_tag(pb, "dinf");
757
    mov_write_dref_tag(pb);
758
    return updateSize(pb, pos);
759
}
760

    
761
static int mov_write_smhd_tag(ByteIOContext *pb)
762
{
763
    put_be32(pb, 16); /* size */
764
    put_tag(pb, "smhd");
765
    put_be32(pb, 0); /* version & flags */
766
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
767
    put_be16(pb, 0); /* reserved */
768
    return 16;
769
}
770

    
771
static int mov_write_vmhd_tag(ByteIOContext *pb)
772
{
773
    put_be32(pb, 0x14); /* size (always 0x14) */
774
    put_tag(pb, "vmhd");
775
    put_be32(pb, 0x01); /* version & flags */
776
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
777
    return 0x14;
778
}
779

    
780
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack* track)
781
{
782
    const char *descr, *hdlr, *hdlr_type;
783
    offset_t pos = url_ftell(pb);
784

    
785
    if (!track) { /* no media --> data handler */
786
        hdlr = "dhlr";
787
        hdlr_type = "url ";
788
        descr = "DataHandler";
789
    } else {
790
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
791
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
792
            hdlr_type = "vide";
793
            descr = "VideoHandler";
794
        } else {
795
            hdlr_type = "soun";
796
            descr = "SoundHandler";
797
        }
798
    }
799

    
800
    put_be32(pb, 0); /* size */
801
    put_tag(pb, "hdlr");
802
    put_be32(pb, 0); /* Version & flags */
803
    put_buffer(pb, hdlr, 4); /* handler */
804
    put_tag(pb, hdlr_type); /* handler type */
805
    put_be32(pb ,0); /* reserved */
806
    put_be32(pb ,0); /* reserved */
807
    put_be32(pb ,0); /* reserved */
808
    put_byte(pb, strlen(descr)); /* string counter */
809
    put_buffer(pb, descr, strlen(descr)); /* handler description */
810
    return updateSize(pb, pos);
811
}
812

    
813
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack* track)
814
{
815
    offset_t pos = url_ftell(pb);
816
    put_be32(pb, 0); /* size */
817
    put_tag(pb, "minf");
818
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
819
        mov_write_vmhd_tag(pb);
820
    else
821
        mov_write_smhd_tag(pb);
822
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
823
        mov_write_hdlr_tag(pb, NULL);
824
    mov_write_dinf_tag(pb);
825
    mov_write_stbl_tag(pb, track);
826
    return updateSize(pb, pos);
827
}
828

    
829
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack* track)
830
{
831
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
832

    
833
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
834
    put_tag(pb, "mdhd");
835
    put_byte(pb, version);
836
    put_be24(pb, 0); /* flags */
837
    if (version == 1) {
838
        put_be64(pb, track->time);
839
        put_be64(pb, track->time);
840
    } else {
841
        put_be32(pb, track->time); /* creation time */
842
        put_be32(pb, track->time); /* modification time */
843
    }
844
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
845
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
846
    put_be16(pb, track->language); /* language */
847
    put_be16(pb, 0); /* reserved (quality) */
848
    return 32;
849
}
850

    
851
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack* track)
852
{
853
    offset_t pos = url_ftell(pb);
854
    put_be32(pb, 0); /* size */
855
    put_tag(pb, "mdia");
856
    mov_write_mdhd_tag(pb, track);
857
    mov_write_hdlr_tag(pb, track);
858
    mov_write_minf_tag(pb, track);
859
    return updateSize(pb, pos);
860
}
861

    
862
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)
863
{
864
    int64_t duration = av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP);
865
    int version = duration < INT32_MAX ? 0 : 1;
866

    
867
    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
868
    put_tag(pb, "tkhd");
869
    put_byte(pb, version);
870
    put_be24(pb, 0xf); /* flags (track enabled) */
871
    if (version == 1) {
872
        put_be64(pb, track->time);
873
        put_be64(pb, track->time);
874
    } else {
875
        put_be32(pb, track->time); /* creation time */
876
        put_be32(pb, track->time); /* modification time */
877
    }
878
    put_be32(pb, track->trackID); /* track-id */
879
    put_be32(pb, 0); /* reserved */
880
    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
881

    
882
    put_be32(pb, 0); /* reserved */
883
    put_be32(pb, 0); /* reserved */
884
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
885
    /* Volume, only for audio */
886
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
887
        put_be16(pb, 0x0100);
888
    else
889
        put_be16(pb, 0);
890
    put_be16(pb, 0); /* reserved */
891

    
892
    /* Matrix structure */
893
    put_be32(pb, 0x00010000); /* reserved */
894
    put_be32(pb, 0x0); /* reserved */
895
    put_be32(pb, 0x0); /* reserved */
896
    put_be32(pb, 0x0); /* reserved */
897
    put_be32(pb, 0x00010000); /* reserved */
898
    put_be32(pb, 0x0); /* reserved */
899
    put_be32(pb, 0x0); /* reserved */
900
    put_be32(pb, 0x0); /* reserved */
901
    put_be32(pb, 0x40000000); /* reserved */
902

    
903
    /* Track width and height, for visual only */
904
    if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
905
        double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
906
        if( !sample_aspect_ratio ) sample_aspect_ratio = 1;
907
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
908
        put_be32(pb, track->enc->height*0x10000);
909
    }
910
    else {
911
        put_be32(pb, 0);
912
        put_be32(pb, 0);
913
    }
914
    return 0x5c;
915
}
916

    
917
// This box seems important for the psp playback ... without it the movie seems to hang
918
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
919
{
920
    put_be32(pb, 0x24); /* size  */
921
    put_tag(pb, "edts");
922
    put_be32(pb, 0x1c); /* size  */
923
    put_tag(pb, "elst");
924
    put_be32(pb, 0x0);
925
    put_be32(pb, 0x1);
926

    
927
    put_be32(pb, av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP)); /* duration   ... doesn't seem to effect psp */
928

    
929
    put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
930
    put_be32(pb, 0x00010000);
931
    return 0x24;
932
}
933

    
934
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
935
static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
936
{
937
    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
938
    put_tag(pb, "uuid");
939
    put_tag(pb, "USMT");
940
    put_be32(pb, 0x21d24fce);
941
    put_be32(pb, 0xbb88695c);
942
    put_be32(pb, 0xfac9c740);
943
    put_be32(pb, 0x1c);     // another size here!
944
    put_tag(pb, "MTDT");
945
    put_be32(pb, 0x00010012);
946
    put_be32(pb, 0x0a);
947
    put_be32(pb, 0x55c40000);
948
    put_be32(pb, 0x1);
949
    put_be32(pb, 0x0);
950
    return 0x34;
951
}
952

    
953
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack* track)
954
{
955
    offset_t pos = url_ftell(pb);
956
    put_be32(pb, 0); /* size */
957
    put_tag(pb, "trak");
958
    mov_write_tkhd_tag(pb, track);
959
    if (track->mode == MODE_PSP || track->hasBframes)
960
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
961
    mov_write_mdia_tag(pb, track);
962
    if (track->mode == MODE_PSP)
963
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
964
    return updateSize(pb, pos);
965
}
966

    
967
#if 0
968
/* TODO: Not sorted out, but not necessary either */
969
static int mov_write_iods_tag(ByteIOContext *pb, MOVContext *mov)
970
{
971
    put_be32(pb, 0x15); /* size */
972
    put_tag(pb, "iods");
973
    put_be32(pb, 0);    /* version & flags */
974
    put_be16(pb, 0x1007);
975
    put_byte(pb, 0);
976
    put_be16(pb, 0x4fff);
977
    put_be16(pb, 0xfffe);
978
    put_be16(pb, 0x01ff);
979
    return 0x15;
980
}
981
#endif
982

    
983
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
984
{
985
    int maxTrackID = 1, i;
986
    int64_t maxTrackLenTemp, maxTrackLen = 0;
987
    int version;
988

    
989
    for (i=0; i<mov->nb_streams; i++) {
990
        if(mov->tracks[i].entry > 0) {
991
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
992
            if(maxTrackLen < maxTrackLenTemp)
993
                maxTrackLen = maxTrackLenTemp;
994
            if(maxTrackID < mov->tracks[i].trackID)
995
                maxTrackID = mov->tracks[i].trackID;
996
        }
997
    }
998

    
999
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1000
    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1001
    put_tag(pb, "mvhd");
1002
    put_byte(pb, version);
1003
    put_be24(pb, 0); /* flags */
1004
    if (version == 1) {
1005
        put_be64(pb, mov->time);
1006
        put_be64(pb, mov->time);
1007
    } else {
1008
        put_be32(pb, mov->time); /* creation time */
1009
        put_be32(pb, mov->time); /* modification time */
1010
    }
1011
    put_be32(pb, mov->timescale); /* timescale */
1012
    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1013

    
1014
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1015
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1016
    put_be16(pb, 0); /* reserved */
1017
    put_be32(pb, 0); /* reserved */
1018
    put_be32(pb, 0); /* reserved */
1019

    
1020
    /* Matrix structure */
1021
    put_be32(pb, 0x00010000); /* reserved */
1022
    put_be32(pb, 0x0); /* reserved */
1023
    put_be32(pb, 0x0); /* reserved */
1024
    put_be32(pb, 0x0); /* reserved */
1025
    put_be32(pb, 0x00010000); /* reserved */
1026
    put_be32(pb, 0x0); /* reserved */
1027
    put_be32(pb, 0x0); /* reserved */
1028
    put_be32(pb, 0x0); /* reserved */
1029
    put_be32(pb, 0x40000000); /* reserved */
1030

    
1031
    put_be32(pb, 0); /* reserved (preview time) */
1032
    put_be32(pb, 0); /* reserved (preview duration) */
1033
    put_be32(pb, 0); /* reserved (poster time) */
1034
    put_be32(pb, 0); /* reserved (selection time) */
1035
    put_be32(pb, 0); /* reserved (selection duration) */
1036
    put_be32(pb, 0); /* reserved (current time) */
1037
    put_be32(pb, maxTrackID+1); /* Next track id */
1038
    return 0x6c;
1039
}
1040

    
1041
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVContext* mov,
1042
                                     AVFormatContext *s)
1043
{
1044
    offset_t pos = url_ftell(pb);
1045
    put_be32(pb, 0); /* size */
1046
    put_tag(pb, "hdlr");
1047
    put_be32(pb, 0);
1048
    put_be32(pb, 0);
1049
    put_tag(pb, "mdir");
1050
    put_tag(pb, "appl");
1051
    put_be32(pb, 0);
1052
    put_be32(pb, 0);
1053
    put_be16(pb, 0);
1054
    return updateSize(pb, pos);
1055
}
1056

    
1057
/* helper function to write a data tag with the specified string as data */
1058
static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int long_style)
1059
{
1060
    if(long_style){
1061
        offset_t pos = url_ftell(pb);
1062
        put_be32(pb, 0); /* size */
1063
        put_tag(pb, "data");
1064
        put_be32(pb, 1);
1065
        put_be32(pb, 0);
1066
        put_buffer(pb, data, strlen(data));
1067
        return updateSize(pb, pos);
1068
    }else{
1069
        put_be16(pb, strlen(data)); /* string length */
1070
        put_be16(pb, 0);
1071
        put_buffer(pb, data, strlen(data));
1072
        return strlen(data) + 4;
1073
    }
1074
}
1075

    
1076
static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int long_style){
1077
    int size = 0;
1078
    if ( value && value[0] ) {
1079
        offset_t pos = url_ftell(pb);
1080
        put_be32(pb, 0); /* size */
1081
        put_tag(pb, name);
1082
        mov_write_string_data_tag(pb, value, long_style);
1083
        size= updateSize(pb, pos);
1084
    }
1085
    return size;
1086
}
1087

    
1088
/* iTunes year */
1089
static int mov_write_day_tag(ByteIOContext *pb, int year, int long_style)
1090
{
1091
    if(year){
1092
        char year_str[5];
1093
        snprintf(year_str, sizeof(year_str), "%04d", year);
1094
        return mov_write_string_tag(pb, "\251day", year_str, long_style);
1095
    }else
1096
        return 0;
1097
}
1098

    
1099
/* iTunes track number */
1100
static int mov_write_trkn_tag(ByteIOContext *pb, MOVContext* mov,
1101
                              AVFormatContext *s)
1102
{
1103
    int size = 0;
1104
    if ( s->track ) {
1105
        offset_t pos = url_ftell(pb);
1106
        put_be32(pb, 0); /* size */
1107
        put_tag(pb, "trkn");
1108
        {
1109
            offset_t pos = url_ftell(pb);
1110
            put_be32(pb, 0); /* size */
1111
            put_tag(pb, "data");
1112
            put_be32(pb, 0);        // 8 bytes empty
1113
            put_be32(pb, 0);
1114
            put_be16(pb, 0);        // empty
1115
            put_be16(pb, s->track); // track number
1116
            put_be16(pb, 0);        // total track number
1117
            put_be16(pb, 0);        // empty
1118
            updateSize(pb, pos);
1119
        }
1120
        size = updateSize(pb, pos);
1121
    }
1122
    return size;
1123
}
1124

    
1125
/* iTunes meta data list */
1126
static int mov_write_ilst_tag(ByteIOContext *pb, MOVContext* mov,
1127
                              AVFormatContext *s)
1128
{
1129
    offset_t pos = url_ftell(pb);
1130
    put_be32(pb, 0); /* size */
1131
    put_tag(pb, "ilst");
1132
    mov_write_string_tag(pb, "\251nam", s->title         , 1);
1133
    mov_write_string_tag(pb, "\251ART", s->author        , 1);
1134
    mov_write_string_tag(pb, "\251wrt", s->author        , 1);
1135
    mov_write_string_tag(pb, "\251alb", s->album         , 1);
1136
    mov_write_day_tag(pb, s->year ,1);
1137
    if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1138
        mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 1);
1139
    mov_write_string_tag(pb, "\251cmt", s->comment       , 1);
1140
    mov_write_string_tag(pb, "\251gen", s->genre         , 1);
1141
    mov_write_trkn_tag(pb, mov, s);
1142
    return updateSize(pb, pos);
1143
}
1144

    
1145
/* iTunes meta data tag */
1146
static int mov_write_meta_tag(ByteIOContext *pb, MOVContext* mov,
1147
                              AVFormatContext *s)
1148
{
1149
    int size = 0;
1150

    
1151
    // only save meta tag if required
1152
    if ( s->title[0] || s->author[0] || s->album[0] || s->year ||
1153
         s->comment[0] || s->genre[0] || s->track ) {
1154
        offset_t pos = url_ftell(pb);
1155
        put_be32(pb, 0); /* size */
1156
        put_tag(pb, "meta");
1157
        put_be32(pb, 0);
1158
        mov_write_itunes_hdlr_tag(pb, mov, s);
1159
        mov_write_ilst_tag(pb, mov, s);
1160
        size = updateSize(pb, pos);
1161
    }
1162
    return size;
1163
}
1164

    
1165
static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1166
                              AVFormatContext *s)
1167
{
1168
    offset_t pos = url_ftell(pb);
1169
    int i;
1170

    
1171
    put_be32(pb, 0); /* size */
1172
    put_tag(pb, "udta");
1173

    
1174
    /* iTunes meta data */
1175
    mov_write_meta_tag(pb, mov, s);
1176

    
1177
  if(mov->mode == MODE_MOV){ // the title field breaks gtkpod with mp4 and my suspicion is that stuff isnt valid in mp4
1178
    /* Requirements */
1179
    for (i=0; i<mov->nb_streams; i++) {
1180
        if(mov->tracks[i].entry <= 0) continue;
1181
        if (mov->tracks[i].enc->codec_id == CODEC_ID_AAC ||
1182
            mov->tracks[i].enc->codec_id == CODEC_ID_MPEG4) {
1183
            mov_write_string_tag(pb, "\251req", "QuickTime 6.0 or greater", 0);
1184
            break;
1185
        }
1186
    }
1187

    
1188
    mov_write_string_tag(pb, "\251nam", s->title         , 0);
1189
    mov_write_string_tag(pb, "\251aut", s->author        , 0);
1190
    mov_write_string_tag(pb, "\251alb", s->album         , 0);
1191
    mov_write_day_tag(pb, s->year, 0);
1192
    if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1193
        mov_write_string_tag(pb, "\251enc", LIBAVFORMAT_IDENT, 0);
1194
    mov_write_string_tag(pb, "\251des", s->comment       , 0);
1195
    mov_write_string_tag(pb, "\251gen", s->genre         , 0);
1196
  }
1197

    
1198
    return updateSize(pb, pos);
1199
}
1200

    
1201
static int utf8len(uint8_t *b){
1202
    int len=0;
1203
    int val;
1204
    while(*b){
1205
        GET_UTF8(val, *b++, return -1;)
1206
        len++;
1207
    }
1208
    return len;
1209
}
1210

    
1211
static int ascii_to_wc (ByteIOContext *pb, uint8_t *b)
1212
{
1213
    int val;
1214
    while(*b){
1215
        GET_UTF8(val, *b++, return -1;)
1216
        put_be16(pb, val);
1217
    }
1218
    put_be16(pb, 0x00);
1219
    return 0;
1220
}
1221

    
1222
static uint16_t language_code (const char *str)
1223
{
1224
    return ((((str[0]-0x60) & 0x1F)<<10) + (((str[1]-0x60) & 0x1F)<<5) + ((str[2]-0x60) & 0x1F));
1225
}
1226

    
1227
static int mov_write_uuidusmt_tag (ByteIOContext *pb, AVFormatContext *s)
1228
{
1229
    size_t len, size;
1230
    offset_t pos, curpos;
1231

    
1232
    size = 0;
1233
    if (s->title[0]) {
1234
        pos = url_ftell(pb);
1235
        put_be32(pb, 0); /* size placeholder*/
1236
        put_tag(pb, "uuid");
1237
        put_tag(pb, "USMT");
1238
        put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1239
        put_be32(pb, 0xbb88695c );
1240
        put_be32(pb, 0xfac9c740 );
1241
        size += 24;
1242

    
1243
        put_be32(pb, 0); /* size placeholder*/
1244
        put_tag(pb, "MTDT");
1245
        put_be16(pb, 4);
1246
        size += 10;
1247

    
1248
        // ?
1249
        put_be16(pb, 0x0C);                 /* size */
1250
        put_be32(pb, 0x0B);                 /* type */
1251
        put_be16(pb, language_code("und")); /* language */
1252
        put_be16(pb, 0x0);                  /* ? */
1253
        put_be16(pb, 0x021C);               /* data */
1254
        size += 12;
1255

    
1256
        // Encoder
1257
        len = utf8len(LIBAVCODEC_IDENT)+1;
1258
        if(len<=0)
1259
            goto not_utf8;
1260
        put_be16(pb, len*2+10);             /* size */
1261
        put_be32(pb, 0x04);                 /* type */
1262
        put_be16(pb, language_code("eng")); /* language */
1263
        put_be16(pb, 0x01);                 /* ? */
1264
        ascii_to_wc(pb, LIBAVCODEC_IDENT);
1265
        size += len*2+10;
1266

    
1267
        // Title
1268
        len = utf8len(s->title)+1;
1269
        if(len<=0)
1270
            goto not_utf8;
1271
        put_be16(pb, len*2+10);             /* size */
1272
        put_be32(pb, 0x01);                 /* type */
1273
        put_be16(pb, language_code("eng")); /* language */
1274
        put_be16(pb, 0x01);                 /* ? */
1275
        ascii_to_wc (pb, s->title);
1276
        size += len*2+10;
1277

    
1278
        // Date
1279
//        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);
1280
        len = utf8len("2006/04/01 11:11:11")+1;
1281
        if(len<=0)
1282
            goto not_utf8;
1283
        put_be16(pb, len*2+10);    /* size */
1284
        put_be32(pb, 0x03);        /* type */
1285
        put_be16(pb, language_code("und")); /* language */
1286
        put_be16(pb, 0x01);        /* ? */
1287
        ascii_to_wc (pb, "2006/04/01 11:11:11");
1288
        size += len*2+10;
1289

    
1290
        // size
1291
        curpos = url_ftell(pb);
1292
        url_fseek(pb, pos, SEEK_SET);
1293
        put_be32(pb, size);
1294
        url_fseek(pb, pos+24, SEEK_SET);
1295
        put_be32(pb, size-24);
1296
        url_fseek(pb, curpos, SEEK_SET);
1297
    }
1298

    
1299
    return size;
1300
not_utf8:
1301
    av_log(s, AV_LOG_ERROR, "not utf8\n");
1302
    return -1;
1303
}
1304

    
1305
static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1306
                              AVFormatContext *s)
1307
{
1308
    int i;
1309
    offset_t pos = url_ftell(pb);
1310
    put_be32(pb, 0); /* size placeholder*/
1311
    put_tag(pb, "moov");
1312
    mov->timescale = globalTimescale;
1313

    
1314
    for (i=0; i<mov->nb_streams; i++) {
1315
        if(mov->tracks[i].entry <= 0) continue;
1316

    
1317
        mov->tracks[i].time = mov->time;
1318
        mov->tracks[i].trackID = i+1;
1319
    }
1320

    
1321
    mov_write_mvhd_tag(pb, mov);
1322
    //mov_write_iods_tag(pb, mov);
1323
    for (i=0; i<mov->nb_streams; i++) {
1324
        if(mov->tracks[i].entry > 0) {
1325
            mov_write_trak_tag(pb, &(mov->tracks[i]));
1326
        }
1327
    }
1328

    
1329
    if (mov->mode == MODE_PSP)
1330
        mov_write_uuidusmt_tag(pb, s);
1331
    else
1332
        mov_write_udta_tag(pb, mov, s);
1333

    
1334
    return updateSize(pb, pos);
1335
}
1336

    
1337
static int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1338
{
1339
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1340
    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1341

    
1342
    mov->mdat_pos = url_ftell(pb);
1343
    put_be32(pb, 0); /* size placeholder*/
1344
    put_tag(pb, "mdat");
1345
    return 0;
1346
}
1347

    
1348
/* TODO: This needs to be more general */
1349
static void mov_write_ftyp_tag (ByteIOContext *pb, AVFormatContext *s)
1350
{
1351
    MOVContext *mov = s->priv_data;
1352

    
1353
    put_be32(pb, 0x14 ); /* size */
1354
    put_tag(pb, "ftyp");
1355

    
1356
    if ( mov->mode == MODE_3GP )
1357
        put_tag(pb, "3gp4");
1358
    else if ( mov->mode == MODE_3G2 )
1359
        put_tag(pb, "3g2a");
1360
    else if ( mov->mode == MODE_PSP )
1361
        put_tag(pb, "MSNV");
1362
    else if ( mov->mode == MODE_MP4 )
1363
        put_tag(pb, "isom");
1364
    else
1365
        put_tag(pb, "qt  ");
1366

    
1367
    put_be32(pb, 0x200 );
1368

    
1369
    if ( mov->mode == MODE_3GP )
1370
        put_tag(pb, "3gp4");
1371
    else if ( mov->mode == MODE_3G2 )
1372
        put_tag(pb, "3g2a");
1373
    else if ( mov->mode == MODE_PSP )
1374
        put_tag(pb, "MSNV");
1375
    else if ( mov->mode == MODE_MP4 )
1376
        put_tag(pb, "mp41");
1377
    else
1378
        put_tag(pb, "qt  ");
1379
}
1380

    
1381
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1382
{
1383
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1384
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1385
    int AudioRate = AudioCodec->sample_rate;
1386
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1387
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1388
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1389

    
1390
    put_be32(pb, 0x94 ); /* size */
1391
    put_tag(pb, "uuid");
1392
    put_tag(pb, "PROF");
1393

    
1394
    put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1395
    put_be32(pb, 0xbb88695c );
1396
    put_be32(pb, 0xfac9c740 );
1397

    
1398
    put_be32(pb, 0x0 );  /* ? */
1399
    put_be32(pb, 0x3 );  /* 3 sections ? */
1400

    
1401
    put_be32(pb, 0x14 ); /* size */
1402
    put_tag(pb, "FPRF");
1403
    put_be32(pb, 0x0 );  /* ? */
1404
    put_be32(pb, 0x0 );  /* ? */
1405
    put_be32(pb, 0x0 );  /* ? */
1406

    
1407
    put_be32(pb, 0x2c );  /* size */
1408
    put_tag(pb, "APRF");   /* audio */
1409
    put_be32(pb, 0x0 );
1410
    put_be32(pb, 0x2 );   /* TrackID */
1411
    put_tag(pb, "mp4a");
1412
    put_be32(pb, 0x20f );
1413
    put_be32(pb, 0x0 );
1414
    put_be32(pb, audio_kbitrate);
1415
    put_be32(pb, audio_kbitrate);
1416
    put_be32(pb, AudioRate );
1417
    put_be32(pb, AudioCodec->channels );
1418

    
1419
    put_be32(pb, 0x34 );  /* size */
1420
    put_tag(pb, "VPRF");   /* video */
1421
    put_be32(pb, 0x0 );
1422
    put_be32(pb, 0x1 );    /* TrackID */
1423
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1424
        put_tag(pb, "avc1");
1425
        put_be16(pb, 0x014D );
1426
        put_be16(pb, 0x0015 );
1427
    } else {
1428
        put_tag(pb, "mp4v");
1429
        put_be16(pb, 0x0000 );
1430
        put_be16(pb, 0x0103 );
1431
    }
1432
    put_be32(pb, 0x0 );
1433
    put_be32(pb, video_kbitrate);
1434
    put_be32(pb, video_kbitrate);
1435
    put_be32(pb, FrameRate);
1436
    put_be32(pb, FrameRate);
1437
    put_be16(pb, VideoCodec->width);
1438
    put_be16(pb, VideoCodec->height);
1439
    put_be32(pb, 0x010001); /* ? */
1440
}
1441

    
1442
static int mov_write_header(AVFormatContext *s)
1443
{
1444
    ByteIOContext *pb = &s->pb;
1445
    MOVContext *mov = s->priv_data;
1446
    int i;
1447

    
1448
    /* Default mode == MP4 */
1449
    mov->mode = MODE_MP4;
1450

    
1451
    if (s->oformat != NULL) {
1452
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1453
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3G2;
1454
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1455
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1456

    
1457
        mov_write_ftyp_tag(pb,s);
1458
        if ( mov->mode == MODE_PSP ) {
1459
            if ( s->nb_streams != 2 ) {
1460
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1461
                return -1;
1462
            }
1463
            mov_write_uuidprof_tag(pb,s);
1464
        }
1465
    }
1466

    
1467
    for(i=0; i<s->nb_streams; i++){
1468
        AVStream *st= s->streams[i];
1469
        MOVTrack *track= &mov->tracks[i];
1470

    
1471
        track->enc = st->codec;
1472
        track->language = ff_mov_iso639_to_lang(st->language, mov->mode != MODE_MOV);
1473
        track->mode = mov->mode;
1474
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1475
            track->tag = mov_find_video_codec_tag(s, track);
1476
            track->timescale = st->codec->time_base.den;
1477
            av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1478
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO){
1479
            track->tag = mov_find_audio_codec_tag(s, track);
1480
            track->timescale = st->codec->sample_rate;
1481
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1482
            switch(track->enc->codec_id){
1483
            case CODEC_ID_MP3:
1484
            case CODEC_ID_AAC:
1485
            case CODEC_ID_AMR_NB:
1486
            case CODEC_ID_AMR_WB:
1487
                track->audio_vbr = 1;
1488
                break;
1489
            default:
1490
                track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
1491
            }
1492
            if (!st->codec->frame_size) {
1493
                av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
1494
                return -1;
1495
            }
1496
        }
1497
    }
1498

    
1499
    mov_write_mdat_tag(pb, mov);
1500
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1501
    mov->nb_streams = s->nb_streams;
1502

    
1503
    put_flush_packet(pb);
1504

    
1505
    return 0;
1506
}
1507

    
1508
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1509
{
1510
    MOVContext *mov = s->priv_data;
1511
    ByteIOContext *pb = &s->pb;
1512
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1513
    AVCodecContext *enc = trk->enc;
1514
    unsigned int samplesInChunk = 0;
1515
    int size= pkt->size;
1516

    
1517
    if (url_is_streamed(&s->pb)) return 0; /* Can't handle that */
1518
    if (!size) return 0; /* Discard 0 sized packets */
1519

    
1520
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1521
        /* We must find out how many AMR blocks there are in one packet */
1522
        static uint16_t packed_size[16] =
1523
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1524
        int len = 0;
1525

    
1526
        while (len < size && samplesInChunk < 100) {
1527
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1528
            samplesInChunk++;
1529
        }
1530
        if(samplesInChunk > 1){
1531
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, inplement a AVParser for it\n");
1532
            return -1;
1533
        }
1534
    } else if (trk->sampleSize)
1535
        samplesInChunk = size/trk->sampleSize;
1536
    else
1537
        samplesInChunk = 1;
1538

    
1539
    /* copy extradata if it exists */
1540
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1541
        trk->vosLen = enc->extradata_size;
1542
        trk->vosData = av_malloc(trk->vosLen);
1543
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1544
    }
1545

    
1546
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1547
        /* from x264 or from bytestream h264 */
1548
        /* nal reformating needed */
1549
        avc_parse_nal_units(&pkt->data, &pkt->size);
1550
        assert(pkt->size);
1551
        size = pkt->size;
1552
    }
1553

    
1554
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1555
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1556
        if (!trk->cluster)
1557
            return -1;
1558
    }
1559

    
1560
    trk->cluster[trk->entry].pos = url_ftell(pb);
1561
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1562
    trk->cluster[trk->entry].size = size;
1563
    trk->cluster[trk->entry].entries = samplesInChunk;
1564
    trk->cluster[trk->entry].dts = pkt->dts;
1565
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1566

    
1567
    if(enc->codec_type == CODEC_TYPE_VIDEO) {
1568
        if (pkt->dts != pkt->pts)
1569
            trk->hasBframes = 1;
1570
        trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1571
        trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1572
        if(trk->cluster[trk->entry].key_frame)
1573
            trk->hasKeyframes++;
1574
    }
1575
    trk->entry++;
1576
    trk->sampleCount += samplesInChunk;
1577
    mov->mdat_size += size;
1578

    
1579
    put_buffer(pb, pkt->data, size);
1580

    
1581
    put_flush_packet(pb);
1582
    return 0;
1583
}
1584

    
1585
static int mov_write_trailer(AVFormatContext *s)
1586
{
1587
    MOVContext *mov = s->priv_data;
1588
    ByteIOContext *pb = &s->pb;
1589
    int res = 0;
1590
    int i;
1591

    
1592
    offset_t moov_pos = url_ftell(pb);
1593

    
1594
    /* Write size of mdat tag */
1595
    if (mov->mdat_size+8 <= UINT32_MAX) {
1596
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
1597
        put_be32(pb, mov->mdat_size+8);
1598
    } else {
1599
        /* overwrite 'wide' placeholder atom */
1600
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1601
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1602
        put_tag(pb, "mdat");
1603
        put_be64(pb, mov->mdat_size+16);
1604
    }
1605
    url_fseek(pb, moov_pos, SEEK_SET);
1606

    
1607
    mov_write_moov_tag(pb, mov, s);
1608

    
1609
    for (i=0; i<mov->nb_streams; i++) {
1610
        av_freep(&mov->tracks[i].cluster);
1611

    
1612
        if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1613

    
1614
    }
1615

    
1616
    put_flush_packet(pb);
1617

    
1618
    return res;
1619
}
1620

    
1621
#ifdef CONFIG_MOV_MUXER
1622
AVOutputFormat mov_muxer = {
1623
    "mov",
1624
    "mov format",
1625
    NULL,
1626
    "mov",
1627
    sizeof(MOVContext),
1628
    CODEC_ID_AAC,
1629
    CODEC_ID_MPEG4,
1630
    mov_write_header,
1631
    mov_write_packet,
1632
    mov_write_trailer,
1633
    .flags = AVFMT_GLOBALHEADER,
1634
};
1635
#endif
1636
#ifdef CONFIG_TGP_MUXER
1637
AVOutputFormat tgp_muxer = {
1638
    "3gp",
1639
    "3gp format",
1640
    NULL,
1641
    "3gp",
1642
    sizeof(MOVContext),
1643
    CODEC_ID_AMR_NB,
1644
    CODEC_ID_H263,
1645
    mov_write_header,
1646
    mov_write_packet,
1647
    mov_write_trailer,
1648
    .flags = AVFMT_GLOBALHEADER,
1649
};
1650
#endif
1651
#ifdef CONFIG_MP4_MUXER
1652
AVOutputFormat mp4_muxer = {
1653
    "mp4",
1654
    "mp4 format",
1655
    "application/mp4",
1656
    "mp4,m4a",
1657
    sizeof(MOVContext),
1658
    CODEC_ID_AAC,
1659
    CODEC_ID_MPEG4,
1660
    mov_write_header,
1661
    mov_write_packet,
1662
    mov_write_trailer,
1663
    .flags = AVFMT_GLOBALHEADER,
1664
};
1665
#endif
1666
#ifdef CONFIG_PSP_MUXER
1667
AVOutputFormat psp_muxer = {
1668
    "psp",
1669
    "psp mp4 format",
1670
    NULL,
1671
    "mp4,psp",
1672
    sizeof(MOVContext),
1673
    CODEC_ID_AAC,
1674
    CODEC_ID_MPEG4,
1675
    mov_write_header,
1676
    mov_write_packet,
1677
    mov_write_trailer,
1678
    .flags = AVFMT_GLOBALHEADER,
1679
};
1680
#endif
1681
#ifdef CONFIG_TG2_MUXER
1682
AVOutputFormat tg2_muxer = {
1683
    "3g2",
1684
    "3gp2 format",
1685
    NULL,
1686
    "3g2",
1687
    sizeof(MOVContext),
1688
    CODEC_ID_AMR_NB,
1689
    CODEC_ID_H263,
1690
    mov_write_header,
1691
    mov_write_packet,
1692
    mov_write_trailer,
1693
    .flags = AVFMT_GLOBALHEADER,
1694
};
1695
#endif