Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 755bfeab

History | View | Annotate | Download (52.4 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_mp4_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
    MOV_stts_t *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
    MOV_stts_t *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

    
849
    if(version!=0 && track->mode == MODE_MOV){
850
        av_log(NULL, AV_LOG_ERROR,
851
            "FATAL error, file duration too long for timebase, this file will not be\n"
852
            "playable with quicktime. Choose a different timebase or a different\n"
853
            "container format\n");
854
    }
855

    
856
    return 32;
857
}
858

    
859
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack* track)
860
{
861
    offset_t pos = url_ftell(pb);
862
    put_be32(pb, 0); /* size */
863
    put_tag(pb, "mdia");
864
    mov_write_mdhd_tag(pb, track);
865
    mov_write_hdlr_tag(pb, track);
866
    mov_write_minf_tag(pb, track);
867
    return updateSize(pb, pos);
868
}
869

    
870
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)
871
{
872
    int64_t duration = av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP);
873
    int version = duration < INT32_MAX ? 0 : 1;
874

    
875
    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
876
    put_tag(pb, "tkhd");
877
    put_byte(pb, version);
878
    put_be24(pb, 0xf); /* flags (track enabled) */
879
    if (version == 1) {
880
        put_be64(pb, track->time);
881
        put_be64(pb, track->time);
882
    } else {
883
        put_be32(pb, track->time); /* creation time */
884
        put_be32(pb, track->time); /* modification time */
885
    }
886
    put_be32(pb, track->trackID); /* track-id */
887
    put_be32(pb, 0); /* reserved */
888
    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
889

    
890
    put_be32(pb, 0); /* reserved */
891
    put_be32(pb, 0); /* reserved */
892
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
893
    /* Volume, only for audio */
894
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
895
        put_be16(pb, 0x0100);
896
    else
897
        put_be16(pb, 0);
898
    put_be16(pb, 0); /* reserved */
899

    
900
    /* Matrix structure */
901
    put_be32(pb, 0x00010000); /* reserved */
902
    put_be32(pb, 0x0); /* reserved */
903
    put_be32(pb, 0x0); /* reserved */
904
    put_be32(pb, 0x0); /* reserved */
905
    put_be32(pb, 0x00010000); /* reserved */
906
    put_be32(pb, 0x0); /* reserved */
907
    put_be32(pb, 0x0); /* reserved */
908
    put_be32(pb, 0x0); /* reserved */
909
    put_be32(pb, 0x40000000); /* reserved */
910

    
911
    /* Track width and height, for visual only */
912
    if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
913
        double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
914
        if( !sample_aspect_ratio ) sample_aspect_ratio = 1;
915
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
916
        put_be32(pb, track->enc->height*0x10000);
917
    }
918
    else {
919
        put_be32(pb, 0);
920
        put_be32(pb, 0);
921
    }
922
    return 0x5c;
923
}
924

    
925
// This box seems important for the psp playback ... without it the movie seems to hang
926
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
927
{
928
    put_be32(pb, 0x24); /* size  */
929
    put_tag(pb, "edts");
930
    put_be32(pb, 0x1c); /* size  */
931
    put_tag(pb, "elst");
932
    put_be32(pb, 0x0);
933
    put_be32(pb, 0x1);
934

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

    
937
    put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
938
    put_be32(pb, 0x00010000);
939
    return 0x24;
940
}
941

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

    
961
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack* track)
962
{
963
    offset_t pos = url_ftell(pb);
964
    put_be32(pb, 0); /* size */
965
    put_tag(pb, "trak");
966
    mov_write_tkhd_tag(pb, track);
967
    if (track->mode == MODE_PSP || track->hasBframes)
968
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
969
    mov_write_mdia_tag(pb, track);
970
    if (track->mode == MODE_PSP)
971
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
972
    return updateSize(pb, pos);
973
}
974

    
975
#if 0
976
/* TODO: Not sorted out, but not necessary either */
977
static int mov_write_iods_tag(ByteIOContext *pb, MOVContext *mov)
978
{
979
    put_be32(pb, 0x15); /* size */
980
    put_tag(pb, "iods");
981
    put_be32(pb, 0);    /* version & flags */
982
    put_be16(pb, 0x1007);
983
    put_byte(pb, 0);
984
    put_be16(pb, 0x4fff);
985
    put_be16(pb, 0xfffe);
986
    put_be16(pb, 0x01ff);
987
    return 0x15;
988
}
989
#endif
990

    
991
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
992
{
993
    int maxTrackID = 1, i;
994
    int64_t maxTrackLenTemp, maxTrackLen = 0;
995
    int version;
996

    
997
    for (i=0; i<mov->nb_streams; i++) {
998
        if(mov->tracks[i].entry > 0) {
999
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
1000
            if(maxTrackLen < maxTrackLenTemp)
1001
                maxTrackLen = maxTrackLenTemp;
1002
            if(maxTrackID < mov->tracks[i].trackID)
1003
                maxTrackID = mov->tracks[i].trackID;
1004
        }
1005
    }
1006

    
1007
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1008
    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1009
    put_tag(pb, "mvhd");
1010
    put_byte(pb, version);
1011
    put_be24(pb, 0); /* flags */
1012
    if (version == 1) {
1013
        put_be64(pb, mov->time);
1014
        put_be64(pb, mov->time);
1015
    } else {
1016
        put_be32(pb, mov->time); /* creation time */
1017
        put_be32(pb, mov->time); /* modification time */
1018
    }
1019
    put_be32(pb, mov->timescale); /* timescale */
1020
    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1021

    
1022
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1023
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1024
    put_be16(pb, 0); /* reserved */
1025
    put_be32(pb, 0); /* reserved */
1026
    put_be32(pb, 0); /* reserved */
1027

    
1028
    /* Matrix structure */
1029
    put_be32(pb, 0x00010000); /* reserved */
1030
    put_be32(pb, 0x0); /* reserved */
1031
    put_be32(pb, 0x0); /* reserved */
1032
    put_be32(pb, 0x0); /* reserved */
1033
    put_be32(pb, 0x00010000); /* reserved */
1034
    put_be32(pb, 0x0); /* reserved */
1035
    put_be32(pb, 0x0); /* reserved */
1036
    put_be32(pb, 0x0); /* reserved */
1037
    put_be32(pb, 0x40000000); /* reserved */
1038

    
1039
    put_be32(pb, 0); /* reserved (preview time) */
1040
    put_be32(pb, 0); /* reserved (preview duration) */
1041
    put_be32(pb, 0); /* reserved (poster time) */
1042
    put_be32(pb, 0); /* reserved (selection time) */
1043
    put_be32(pb, 0); /* reserved (selection duration) */
1044
    put_be32(pb, 0); /* reserved (current time) */
1045
    put_be32(pb, maxTrackID+1); /* Next track id */
1046
    return 0x6c;
1047
}
1048

    
1049
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVContext* mov,
1050
                                     AVFormatContext *s)
1051
{
1052
    offset_t pos = url_ftell(pb);
1053
    put_be32(pb, 0); /* size */
1054
    put_tag(pb, "hdlr");
1055
    put_be32(pb, 0);
1056
    put_be32(pb, 0);
1057
    put_tag(pb, "mdir");
1058
    put_tag(pb, "appl");
1059
    put_be32(pb, 0);
1060
    put_be32(pb, 0);
1061
    put_be16(pb, 0);
1062
    return updateSize(pb, pos);
1063
}
1064

    
1065
/* helper function to write a data tag with the specified string as data */
1066
static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int long_style)
1067
{
1068
    if(long_style){
1069
        offset_t pos = url_ftell(pb);
1070
        put_be32(pb, 0); /* size */
1071
        put_tag(pb, "data");
1072
        put_be32(pb, 1);
1073
        put_be32(pb, 0);
1074
        put_buffer(pb, data, strlen(data));
1075
        return updateSize(pb, pos);
1076
    }else{
1077
        put_be16(pb, strlen(data)); /* string length */
1078
        put_be16(pb, 0);
1079
        put_buffer(pb, data, strlen(data));
1080
        return strlen(data) + 4;
1081
    }
1082
}
1083

    
1084
static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int long_style){
1085
    int size = 0;
1086
    if ( value && value[0] ) {
1087
        offset_t pos = url_ftell(pb);
1088
        put_be32(pb, 0); /* size */
1089
        put_tag(pb, name);
1090
        mov_write_string_data_tag(pb, value, long_style);
1091
        size= updateSize(pb, pos);
1092
    }
1093
    return size;
1094
}
1095

    
1096
/* iTunes year */
1097
static int mov_write_day_tag(ByteIOContext *pb, int year, int long_style)
1098
{
1099
    if(year){
1100
        char year_str[5];
1101
        snprintf(year_str, sizeof(year_str), "%04d", year);
1102
        return mov_write_string_tag(pb, "\251day", year_str, long_style);
1103
    }else
1104
        return 0;
1105
}
1106

    
1107
/* iTunes track number */
1108
static int mov_write_trkn_tag(ByteIOContext *pb, MOVContext* mov,
1109
                              AVFormatContext *s)
1110
{
1111
    int size = 0;
1112
    if ( s->track ) {
1113
        offset_t pos = url_ftell(pb);
1114
        put_be32(pb, 0); /* size */
1115
        put_tag(pb, "trkn");
1116
        {
1117
            offset_t pos = url_ftell(pb);
1118
            put_be32(pb, 0); /* size */
1119
            put_tag(pb, "data");
1120
            put_be32(pb, 0);        // 8 bytes empty
1121
            put_be32(pb, 0);
1122
            put_be16(pb, 0);        // empty
1123
            put_be16(pb, s->track); // track number
1124
            put_be16(pb, 0);        // total track number
1125
            put_be16(pb, 0);        // empty
1126
            updateSize(pb, pos);
1127
        }
1128
        size = updateSize(pb, pos);
1129
    }
1130
    return size;
1131
}
1132

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

    
1153
/* iTunes meta data tag */
1154
static int mov_write_meta_tag(ByteIOContext *pb, MOVContext* mov,
1155
                              AVFormatContext *s)
1156
{
1157
    int size = 0;
1158

    
1159
    // only save meta tag if required
1160
    if ( s->title[0] || s->author[0] || s->album[0] || s->year ||
1161
         s->comment[0] || s->genre[0] || s->track ) {
1162
        offset_t pos = url_ftell(pb);
1163
        put_be32(pb, 0); /* size */
1164
        put_tag(pb, "meta");
1165
        put_be32(pb, 0);
1166
        mov_write_itunes_hdlr_tag(pb, mov, s);
1167
        mov_write_ilst_tag(pb, mov, s);
1168
        size = updateSize(pb, pos);
1169
    }
1170
    return size;
1171
}
1172

    
1173
static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1174
                              AVFormatContext *s)
1175
{
1176
    offset_t pos = url_ftell(pb);
1177
    int i;
1178

    
1179
    put_be32(pb, 0); /* size */
1180
    put_tag(pb, "udta");
1181

    
1182
    /* iTunes meta data */
1183
    mov_write_meta_tag(pb, mov, s);
1184

    
1185
  if(mov->mode == MODE_MOV){ // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1186
    /* Requirements */
1187
    for (i=0; i<mov->nb_streams; i++) {
1188
        if(mov->tracks[i].entry <= 0) continue;
1189
        if (mov->tracks[i].enc->codec_id == CODEC_ID_AAC ||
1190
            mov->tracks[i].enc->codec_id == CODEC_ID_MPEG4) {
1191
            mov_write_string_tag(pb, "\251req", "QuickTime 6.0 or greater", 0);
1192
            break;
1193
        }
1194
    }
1195

    
1196
    mov_write_string_tag(pb, "\251nam", s->title         , 0);
1197
    mov_write_string_tag(pb, "\251aut", s->author        , 0);
1198
    mov_write_string_tag(pb, "\251alb", s->album         , 0);
1199
    mov_write_day_tag(pb, s->year, 0);
1200
    if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1201
        mov_write_string_tag(pb, "\251enc", LIBAVFORMAT_IDENT, 0);
1202
    mov_write_string_tag(pb, "\251des", s->comment       , 0);
1203
    mov_write_string_tag(pb, "\251gen", s->genre         , 0);
1204
  }
1205

    
1206
    return updateSize(pb, pos);
1207
}
1208

    
1209
static int utf8len(uint8_t *b){
1210
    int len=0;
1211
    int val;
1212
    while(*b){
1213
        GET_UTF8(val, *b++, return -1;)
1214
        len++;
1215
    }
1216
    return len;
1217
}
1218

    
1219
static int ascii_to_wc (ByteIOContext *pb, uint8_t *b)
1220
{
1221
    int val;
1222
    while(*b){
1223
        GET_UTF8(val, *b++, return -1;)
1224
        put_be16(pb, val);
1225
    }
1226
    put_be16(pb, 0x00);
1227
    return 0;
1228
}
1229

    
1230
static uint16_t language_code (const char *str)
1231
{
1232
    return ((((str[0]-0x60) & 0x1F)<<10) + (((str[1]-0x60) & 0x1F)<<5) + ((str[2]-0x60) & 0x1F));
1233
}
1234

    
1235
static int mov_write_uuidusmt_tag (ByteIOContext *pb, AVFormatContext *s)
1236
{
1237
    size_t len, size;
1238
    offset_t pos, curpos;
1239

    
1240
    size = 0;
1241
    if (s->title[0]) {
1242
        pos = url_ftell(pb);
1243
        put_be32(pb, 0); /* size placeholder*/
1244
        put_tag(pb, "uuid");
1245
        put_tag(pb, "USMT");
1246
        put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1247
        put_be32(pb, 0xbb88695c );
1248
        put_be32(pb, 0xfac9c740 );
1249
        size += 24;
1250

    
1251
        put_be32(pb, 0); /* size placeholder*/
1252
        put_tag(pb, "MTDT");
1253
        put_be16(pb, 4);
1254
        size += 10;
1255

    
1256
        // ?
1257
        put_be16(pb, 0x0C);                 /* size */
1258
        put_be32(pb, 0x0B);                 /* type */
1259
        put_be16(pb, language_code("und")); /* language */
1260
        put_be16(pb, 0x0);                  /* ? */
1261
        put_be16(pb, 0x021C);               /* data */
1262
        size += 12;
1263

    
1264
        // Encoder
1265
        len = utf8len(LIBAVCODEC_IDENT)+1;
1266
        if(len<=0)
1267
            goto not_utf8;
1268
        put_be16(pb, len*2+10);             /* size */
1269
        put_be32(pb, 0x04);                 /* type */
1270
        put_be16(pb, language_code("eng")); /* language */
1271
        put_be16(pb, 0x01);                 /* ? */
1272
        ascii_to_wc(pb, LIBAVCODEC_IDENT);
1273
        size += len*2+10;
1274

    
1275
        // Title
1276
        len = utf8len(s->title)+1;
1277
        if(len<=0)
1278
            goto not_utf8;
1279
        put_be16(pb, len*2+10);             /* size */
1280
        put_be32(pb, 0x01);                 /* type */
1281
        put_be16(pb, language_code("eng")); /* language */
1282
        put_be16(pb, 0x01);                 /* ? */
1283
        ascii_to_wc (pb, s->title);
1284
        size += len*2+10;
1285

    
1286
        // Date
1287
//        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);
1288
        len = utf8len("2006/04/01 11:11:11")+1;
1289
        if(len<=0)
1290
            goto not_utf8;
1291
        put_be16(pb, len*2+10);    /* size */
1292
        put_be32(pb, 0x03);        /* type */
1293
        put_be16(pb, language_code("und")); /* language */
1294
        put_be16(pb, 0x01);        /* ? */
1295
        ascii_to_wc (pb, "2006/04/01 11:11:11");
1296
        size += len*2+10;
1297

    
1298
        // size
1299
        curpos = url_ftell(pb);
1300
        url_fseek(pb, pos, SEEK_SET);
1301
        put_be32(pb, size);
1302
        url_fseek(pb, pos+24, SEEK_SET);
1303
        put_be32(pb, size-24);
1304
        url_fseek(pb, curpos, SEEK_SET);
1305
    }
1306

    
1307
    return size;
1308
not_utf8:
1309
    av_log(s, AV_LOG_ERROR, "not utf8\n");
1310
    return -1;
1311
}
1312

    
1313
static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1314
                              AVFormatContext *s)
1315
{
1316
    int i;
1317
    offset_t pos = url_ftell(pb);
1318
    put_be32(pb, 0); /* size placeholder*/
1319
    put_tag(pb, "moov");
1320
    mov->timescale = globalTimescale;
1321

    
1322
    for (i=0; i<mov->nb_streams; i++) {
1323
        if(mov->tracks[i].entry <= 0) continue;
1324

    
1325
        mov->tracks[i].time = mov->time;
1326
        mov->tracks[i].trackID = i+1;
1327
    }
1328

    
1329
    mov_write_mvhd_tag(pb, mov);
1330
    //mov_write_iods_tag(pb, mov);
1331
    for (i=0; i<mov->nb_streams; i++) {
1332
        if(mov->tracks[i].entry > 0) {
1333
            mov_write_trak_tag(pb, &(mov->tracks[i]));
1334
        }
1335
    }
1336

    
1337
    if (mov->mode == MODE_PSP)
1338
        mov_write_uuidusmt_tag(pb, s);
1339
    else
1340
        mov_write_udta_tag(pb, mov, s);
1341

    
1342
    return updateSize(pb, pos);
1343
}
1344

    
1345
static int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1346
{
1347
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1348
    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1349

    
1350
    mov->mdat_pos = url_ftell(pb);
1351
    put_be32(pb, 0); /* size placeholder*/
1352
    put_tag(pb, "mdat");
1353
    return 0;
1354
}
1355

    
1356
/* TODO: This needs to be more general */
1357
static void mov_write_ftyp_tag (ByteIOContext *pb, AVFormatContext *s)
1358
{
1359
    MOVContext *mov = s->priv_data;
1360

    
1361
    put_be32(pb, 0x14 ); /* size */
1362
    put_tag(pb, "ftyp");
1363

    
1364
    if ( mov->mode == MODE_3GP )
1365
        put_tag(pb, "3gp4");
1366
    else if ( mov->mode == MODE_3G2 )
1367
        put_tag(pb, "3g2a");
1368
    else if ( mov->mode == MODE_PSP )
1369
        put_tag(pb, "MSNV");
1370
    else if ( mov->mode == MODE_MP4 )
1371
        put_tag(pb, "isom");
1372
    else
1373
        put_tag(pb, "qt  ");
1374

    
1375
    put_be32(pb, 0x200 );
1376

    
1377
    if ( mov->mode == MODE_3GP )
1378
        put_tag(pb, "3gp4");
1379
    else if ( mov->mode == MODE_3G2 )
1380
        put_tag(pb, "3g2a");
1381
    else if ( mov->mode == MODE_PSP )
1382
        put_tag(pb, "MSNV");
1383
    else if ( mov->mode == MODE_MP4 )
1384
        put_tag(pb, "mp41");
1385
    else
1386
        put_tag(pb, "qt  ");
1387
}
1388

    
1389
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1390
{
1391
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1392
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1393
    int AudioRate = AudioCodec->sample_rate;
1394
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1395
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1396
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1397

    
1398
    put_be32(pb, 0x94 ); /* size */
1399
    put_tag(pb, "uuid");
1400
    put_tag(pb, "PROF");
1401

    
1402
    put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1403
    put_be32(pb, 0xbb88695c );
1404
    put_be32(pb, 0xfac9c740 );
1405

    
1406
    put_be32(pb, 0x0 );  /* ? */
1407
    put_be32(pb, 0x3 );  /* 3 sections ? */
1408

    
1409
    put_be32(pb, 0x14 ); /* size */
1410
    put_tag(pb, "FPRF");
1411
    put_be32(pb, 0x0 );  /* ? */
1412
    put_be32(pb, 0x0 );  /* ? */
1413
    put_be32(pb, 0x0 );  /* ? */
1414

    
1415
    put_be32(pb, 0x2c );  /* size */
1416
    put_tag(pb, "APRF");   /* audio */
1417
    put_be32(pb, 0x0 );
1418
    put_be32(pb, 0x2 );   /* TrackID */
1419
    put_tag(pb, "mp4a");
1420
    put_be32(pb, 0x20f );
1421
    put_be32(pb, 0x0 );
1422
    put_be32(pb, audio_kbitrate);
1423
    put_be32(pb, audio_kbitrate);
1424
    put_be32(pb, AudioRate );
1425
    put_be32(pb, AudioCodec->channels );
1426

    
1427
    put_be32(pb, 0x34 );  /* size */
1428
    put_tag(pb, "VPRF");   /* video */
1429
    put_be32(pb, 0x0 );
1430
    put_be32(pb, 0x1 );    /* TrackID */
1431
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1432
        put_tag(pb, "avc1");
1433
        put_be16(pb, 0x014D );
1434
        put_be16(pb, 0x0015 );
1435
    } else {
1436
        put_tag(pb, "mp4v");
1437
        put_be16(pb, 0x0000 );
1438
        put_be16(pb, 0x0103 );
1439
    }
1440
    put_be32(pb, 0x0 );
1441
    put_be32(pb, video_kbitrate);
1442
    put_be32(pb, video_kbitrate);
1443
    put_be32(pb, FrameRate);
1444
    put_be32(pb, FrameRate);
1445
    put_be16(pb, VideoCodec->width);
1446
    put_be16(pb, VideoCodec->height);
1447
    put_be32(pb, 0x010001); /* ? */
1448
}
1449

    
1450
static int mov_write_header(AVFormatContext *s)
1451
{
1452
    ByteIOContext *pb = &s->pb;
1453
    MOVContext *mov = s->priv_data;
1454
    int i;
1455

    
1456
    if (url_is_streamed(&s->pb)) {
1457
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
1458
        return -1;
1459
    }
1460

    
1461
    /* Default mode == MP4 */
1462
    mov->mode = MODE_MP4;
1463

    
1464
    if (s->oformat != NULL) {
1465
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1466
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3G2;
1467
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1468
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1469

    
1470
        mov_write_ftyp_tag(pb,s);
1471
        if ( mov->mode == MODE_PSP ) {
1472
            if ( s->nb_streams != 2 ) {
1473
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1474
                return -1;
1475
            }
1476
            mov_write_uuidprof_tag(pb,s);
1477
        }
1478
    }
1479

    
1480
    for(i=0; i<s->nb_streams; i++){
1481
        AVStream *st= s->streams[i];
1482
        MOVTrack *track= &mov->tracks[i];
1483

    
1484
        track->enc = st->codec;
1485
        track->language = ff_mov_iso639_to_lang(st->language, mov->mode != MODE_MOV);
1486
        track->mode = mov->mode;
1487
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1488
            track->tag = mov_find_video_codec_tag(s, track);
1489
            track->timescale = st->codec->time_base.den;
1490
            av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1491
            if (track->timescale > 100000)
1492
                av_log(NULL, AV_LOG_WARNING,
1493
                       "WARNING codec timebase is very high. If duration is too long,\n"
1494
                       "file may not be playable by quicktime. Specify a shorter timebase\n"
1495
                       "or choose different container.\n");
1496
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO){
1497
            track->tag = mov_find_audio_codec_tag(s, track);
1498
            track->timescale = st->codec->sample_rate;
1499
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1500
            if(!st->codec->frame_size){
1501
                av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
1502
                return -1;
1503
            }else if(st->codec->frame_size > 1){ /* assume compressed audio */
1504
                track->audio_vbr = 1;
1505
            }else{
1506
                track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
1507
            }
1508
        }
1509
    }
1510

    
1511
    mov_write_mdat_tag(pb, mov);
1512
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1513
    mov->nb_streams = s->nb_streams;
1514

    
1515
    put_flush_packet(pb);
1516

    
1517
    return 0;
1518
}
1519

    
1520
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1521
{
1522
    MOVContext *mov = s->priv_data;
1523
    ByteIOContext *pb = &s->pb;
1524
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1525
    AVCodecContext *enc = trk->enc;
1526
    unsigned int samplesInChunk = 0;
1527
    int size= pkt->size;
1528

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

    
1532
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1533
        /* We must find out how many AMR blocks there are in one packet */
1534
        static uint16_t packed_size[16] =
1535
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1536
        int len = 0;
1537

    
1538
        while (len < size && samplesInChunk < 100) {
1539
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1540
            samplesInChunk++;
1541
        }
1542
        if(samplesInChunk > 1){
1543
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, inplement a AVParser for it\n");
1544
            return -1;
1545
        }
1546
    } else if (trk->sampleSize)
1547
        samplesInChunk = size/trk->sampleSize;
1548
    else
1549
        samplesInChunk = 1;
1550

    
1551
    /* copy extradata if it exists */
1552
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1553
        trk->vosLen = enc->extradata_size;
1554
        trk->vosData = av_malloc(trk->vosLen);
1555
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1556
    }
1557

    
1558
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1559
        /* from x264 or from bytestream h264 */
1560
        /* nal reformating needed */
1561
        avc_parse_nal_units(&pkt->data, &pkt->size);
1562
        assert(pkt->size);
1563
        size = pkt->size;
1564
    }
1565

    
1566
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1567
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1568
        if (!trk->cluster)
1569
            return -1;
1570
    }
1571

    
1572
    trk->cluster[trk->entry].pos = url_ftell(pb);
1573
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1574
    trk->cluster[trk->entry].size = size;
1575
    trk->cluster[trk->entry].entries = samplesInChunk;
1576
    trk->cluster[trk->entry].dts = pkt->dts;
1577
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1578

    
1579
    if(enc->codec_type == CODEC_TYPE_VIDEO) {
1580
        if (pkt->dts != pkt->pts)
1581
            trk->hasBframes = 1;
1582
        trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1583
        trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1584
        if(trk->cluster[trk->entry].key_frame)
1585
            trk->hasKeyframes++;
1586
    }
1587
    trk->entry++;
1588
    trk->sampleCount += samplesInChunk;
1589
    mov->mdat_size += size;
1590

    
1591
    put_buffer(pb, pkt->data, size);
1592

    
1593
    put_flush_packet(pb);
1594
    return 0;
1595
}
1596

    
1597
static int mov_write_trailer(AVFormatContext *s)
1598
{
1599
    MOVContext *mov = s->priv_data;
1600
    ByteIOContext *pb = &s->pb;
1601
    int res = 0;
1602
    int i;
1603

    
1604
    offset_t moov_pos = url_ftell(pb);
1605

    
1606
    /* Write size of mdat tag */
1607
    if (mov->mdat_size+8 <= UINT32_MAX) {
1608
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
1609
        put_be32(pb, mov->mdat_size+8);
1610
    } else {
1611
        /* overwrite 'wide' placeholder atom */
1612
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1613
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1614
        put_tag(pb, "mdat");
1615
        put_be64(pb, mov->mdat_size+16);
1616
    }
1617
    url_fseek(pb, moov_pos, SEEK_SET);
1618

    
1619
    mov_write_moov_tag(pb, mov, s);
1620

    
1621
    for (i=0; i<mov->nb_streams; i++) {
1622
        av_freep(&mov->tracks[i].cluster);
1623

    
1624
        if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1625

    
1626
    }
1627

    
1628
    put_flush_packet(pb);
1629

    
1630
    return res;
1631
}
1632

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