Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 5340a0bc

History | View | Annotate | Download (51.9 KB)

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

    
25
#undef NDEBUG
26
#include <assert.h>
27

    
28
#define MOV_INDEX_CLUSTER_SIZE 16384
29
#define globalTimescale 1000
30

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

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

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

    
63
    int         vosLen;
64
    uint8_t     *vosData;
65
    MOVIentry   *cluster;
66
} MOVTrack;
67

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

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

    
86
    return curpos - pos;
87
}
88

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

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

    
118
    offset_t pos = url_ftell(pb);
119
    put_be32(pb, 0); /* size */
120
    put_tag(pb, "stsz");
121
    put_be32(pb, 0); /* version & flags */
122

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

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

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

    
176
    return updateSize (pb, pos);
177
}
178

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

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

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

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

    
225
static unsigned int descrLength(unsigned int len)
226
{
227
    int i;
228
    for(i=1; len>>(7*i); i++);
229
    return len + 1 + i;
230
}
231

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

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

    
246
    put_be32(pb, 0);               // size
247
    put_tag(pb, "esds");
248
    put_be32(pb, 0);               // Version
249

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

    
256
    // DecoderConfig descriptor
257
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
258

    
259
    // Object type indication
260
    put_byte(pb, codec_get_tag(ff_mov_obj_type, track->enc->codec_id));
261

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

    
269
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));             // Buffersize DB (24 bits)
270
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF);          // Buffersize DB
271

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

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

    
285

    
286
    // SL descriptor
287
    putDescr(pb, 0x06, 1);
288
    put_byte(pb, 0x02);
289
    return updateSize (pb, pos);
290
}
291

    
292
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack* track)
293
{
294
    offset_t pos = url_ftell(pb);
295

    
296
    put_be32(pb, 0);     /* size */
297
    put_tag(pb, "wave");
298

    
299
    put_be32(pb, 12);    /* size */
300
    put_tag(pb, "frma");
301
    put_le32(pb, track->tag);
302

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

    
316
    put_be32(pb, 8);     /* size */
317
    put_be32(pb, 0);     /* null tag */
318

    
319
    return updateSize (pb, pos);
320
}
321

    
322
static const CodecTag codec_movaudio_tags[] = {
323
    { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') },
324
    { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') },
325
    { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') },
326
    { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') },
327
    { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') },
328
    { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
329
    { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') },
330
    { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') },
331
    { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') },
332
    { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') },
333
    { CODEC_ID_PCM_S24BE, MKTAG('i', 'n', '2', '4') },
334
    { CODEC_ID_PCM_S24LE, MKTAG('i', 'n', '2', '4') },
335
    { CODEC_ID_PCM_S32BE, MKTAG('i', 'n', '3', '2') },
336
    { CODEC_ID_PCM_S32LE, MKTAG('i', 'n', '3', '2') },
337
    { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') },
338
    { CODEC_ID_NONE, 0 },
339
};
340

    
341
static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack* track)
342
{
343
    offset_t pos = url_ftell(pb);
344
    int vbr=  track->mode == MODE_MOV &&
345
        (track->enc->codec_id == CODEC_ID_AAC ||
346
         track->enc->codec_id == CODEC_ID_MP3 ||
347
         track->enc->codec_id == CODEC_ID_AMR_NB);
348
    int version = vbr ||
349
        track->enc->codec_id == CODEC_ID_PCM_S32LE ||
350
        track->enc->codec_id == CODEC_ID_PCM_S24LE;
351

    
352
    put_be32(pb, 0); /* size */
353
    put_le32(pb, track->tag); // store it byteswapped
354
    put_be32(pb, 0); /* Reserved */
355
    put_be16(pb, 0); /* Reserved */
356
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
357

    
358
    /* SoundDescription */
359
    put_be16(pb, version); /* Version */
360
    put_be16(pb, 0); /* Revision level */
361
    put_be32(pb, 0); /* Reserved */
362

    
363
    put_be16(pb, track->mode == MODE_MOV ? track->enc->channels : 2); /* Number of channels */
364
    /* FIXME 8 bit for 'raw ' in mov */
365
    put_be16(pb, 16); /* Reserved */
366

    
367
    put_be16(pb, vbr ? 0xfffe : 0); /* compression ID */
368
    put_be16(pb, 0); /* packet size (= 0) */
369
    put_be16(pb, track->timescale); /* Time scale */
370
    put_be16(pb, 0); /* Reserved */
371

    
372
    if(version == 1) { /* SoundDescription V1 extended info */
373
        if (vbr)
374
            track->sampleSize = 0;
375
        put_be32(pb, track->enc->frame_size); /* Samples per packet */
376
        put_be32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
377
        put_be32(pb, track->sampleSize); /* Bytes per frame */
378
        put_be32(pb, 2); /* Bytes per sample */
379
    }
380

    
381
    if(track->mode == MODE_MOV &&
382
       (track->enc->codec_id == CODEC_ID_AAC ||
383
        track->enc->codec_id == CODEC_ID_AMR_NB ||
384
        track->enc->codec_id == CODEC_ID_PCM_S24LE ||
385
        track->enc->codec_id == CODEC_ID_PCM_S32LE))
386
        mov_write_wave_tag(pb, track);
387
    else if(track->enc->codec_id == CODEC_ID_AAC)
388
        mov_write_esds_tag(pb, track);
389
    else if(track->enc->codec_id == CODEC_ID_AMR_NB)
390
        mov_write_amr_tag(pb, track);
391

    
392
    return updateSize (pb, pos);
393
}
394

    
395
static int mov_write_d263_tag(ByteIOContext *pb)
396
{
397
    put_be32(pb, 0xf); /* size */
398
    put_tag(pb, "d263");
399
    put_tag(pb, "FFMP");
400
    put_byte(pb, 0); /* decoder version */
401
    /* FIXME use AVCodecContext level/profile, when encoder will set values */
402
    put_byte(pb, 0xa); /* level */
403
    put_byte(pb, 0); /* profile */
404
    return 0xf;
405
}
406

    
407
/* TODO: No idea about these values */
408
static int mov_write_svq3_tag(ByteIOContext *pb)
409
{
410
    put_be32(pb, 0x15);
411
    put_tag(pb, "SMI ");
412
    put_tag(pb, "SEQH");
413
    put_be32(pb, 0x5);
414
    put_be32(pb, 0xe2c0211d);
415
    put_be32(pb, 0xc0000000);
416
    put_byte(pb, 0);
417
    return 0x15;
418
}
419

    
420
static uint8_t *avc_find_startcode( uint8_t *p, uint8_t *end )
421
{
422
    uint8_t *a = p + 4 - ((int)p & 3);
423

    
424
    for( end -= 3; p < a && p < end; p++ ) {
425
        if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
426
            return p;
427
    }
428

    
429
    for( end -= 3; p < end; p += 4 ) {
430
        uint32_t x = *(uint32_t*)p;
431
//      if( (x - 0x01000100) & (~x) & 0x80008000 ) // little endian
432
//      if( (x - 0x00010001) & (~x) & 0x00800080 ) // big endian
433
        if( (x - 0x01010101) & (~x) & 0x80808080 ) { // generic
434
            if( p[1] == 0 ) {
435
                if( p[0] == 0 && p[2] == 1 )
436
                    return p-1;
437
                if( p[2] == 0 && p[3] == 1 )
438
                    return p;
439
            }
440
            if( p[3] == 0 ) {
441
                if( p[2] == 0 && p[4] == 1 )
442
                    return p+1;
443
                if( p[4] == 0 && p[5] == 1 )
444
                    return p+2;
445
            }
446
        }
447
    }
448

    
449
    for( end += 3; p < end; p++ ) {
450
        if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
451
            return p;
452
    }
453

    
454
    return end + 3;
455
}
456

    
457
static void avc_parse_nal_units(uint8_t **buf, int *size)
458
{
459
    ByteIOContext pb;
460
    uint8_t *p = *buf;
461
    uint8_t *end = p + *size;
462
    uint8_t *nal_start, *nal_end;
463

    
464
    url_open_dyn_buf(&pb);
465
    nal_start = avc_find_startcode(p, end);
466
    while (nal_start < end) {
467
        while(!*(nal_start++));
468
        nal_end = avc_find_startcode(nal_start, end);
469
        put_be32(&pb, nal_end - nal_start);
470
        put_buffer(&pb, nal_start, nal_end - nal_start);
471
        nal_start = nal_end;
472
    }
473
    av_freep(buf);
474
    *size = url_close_dyn_buf(&pb, buf);
475
}
476

    
477
static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
478
{
479
    offset_t pos = url_ftell(pb);
480

    
481
    put_be32(pb, 0);
482
    put_tag(pb, "avcC");
483
    if (track->vosLen > 6) {
484
        /* check for h264 start code */
485
        if (BE_32(track->vosData) == 0x00000001) {
486
            uint8_t *buf, *end;
487
            uint32_t sps_size=0, pps_size=0;
488
            uint8_t *sps=0, *pps=0;
489

    
490
            avc_parse_nal_units(&track->vosData, &track->vosLen);
491
            buf = track->vosData;
492
            end = track->vosData + track->vosLen;
493

    
494
            /* look for sps and pps */
495
            while (buf < end) {
496
                unsigned int size;
497
                uint8_t nal_type;
498
                size = BE_32(buf);
499
                nal_type = buf[4] & 0x1f;
500
                if (nal_type == 7) { /* SPS */
501
                    sps = buf + 4;
502
                    sps_size = size;
503
                } else if (nal_type == 8) { /* PPS */
504
                    pps = buf + 4;
505
                    pps_size = size;
506
                }
507
                buf += size + 4;
508
            }
509
            assert(sps);
510
            assert(pps);
511

    
512
            put_byte(pb, 1); /* version */
513
            put_byte(pb, sps[1]); /* profile */
514
            put_byte(pb, sps[2]); /* profile compat */
515
            put_byte(pb, sps[3]); /* level */
516
            put_byte(pb, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 1 (11) */
517
            put_byte(pb, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
518

    
519
            put_be16(pb, sps_size);
520
            put_buffer(pb, sps, sps_size);
521
            put_byte(pb, 1); /* number of pps */
522
            put_be16(pb, pps_size);
523
            put_buffer(pb, pps, pps_size);
524
        } else {
525
            put_buffer(pb, track->vosData, track->vosLen);
526
        }
527
    }
528
    return updateSize(pb, pos);
529
}
530

    
531
static const CodecTag codec_movvideo_tags[] = {
532
    { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') },
533
    { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') },
534
    { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
535
    { CODEC_ID_H263, MKTAG('h', '2', '6', '3') },
536
    { CODEC_ID_H263, MKTAG('s', '2', '6', '3') },
537
    { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
538
    /* special handling in mov_find_video_codec_tag */
539
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
540
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
541
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'p', 'p') }, /* DVCPRO PAL */
542
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'n') }, /* DVCPRO50 NTSC */
543
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'p') }, /* DVCPRO50 PAL */
544
    { CODEC_ID_NONE, 0 },
545
};
546

    
547
static int mov_find_video_codec_tag(AVFormatContext *s, MOVTrack *track)
548
{
549
    int tag = track->enc->codec_tag;
550
    if (!tag) {
551
        if (track->enc->codec_id == CODEC_ID_DVVIDEO) {
552
            if (track->enc->height == 480) { /* NTSC */
553
                if (track->enc->pix_fmt == PIX_FMT_YUV422P)
554
                    tag = MKTAG('d', 'v', '5', 'n');
555
                else
556
                    tag = MKTAG('d', 'v', 'c', ' ');
557
            } else { /* assume PAL */
558
                if (track->enc->pix_fmt == PIX_FMT_YUV422P)
559
                    tag = MKTAG('d', 'v', '5', 'p');
560
                else if (track->enc->pix_fmt == PIX_FMT_YUV420P)
561
                    tag = MKTAG('d', 'v', 'c', 'p');
562
                else
563
                    tag = MKTAG('d', 'v', 'p', 'p');
564
            }
565
        } else if (track->enc->codec_id == CODEC_ID_H263) {
566
            if (track->mode == MODE_MOV)
567
                tag = MKTAG('h', '2', '6', '3');
568
            else
569
                tag = MKTAG('s', '2', '6', '3');
570
        } else {
571
            tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
572
        }
573
    }
574
    // if no mac fcc found, try with Microsoft tags
575
    if (!tag) {
576
        tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
577
        if (tag) {
578
            av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, the file may be unplayable!\n");
579
        }
580
    }
581
    assert(tag);
582
    return tag;
583
}
584

    
585
static int mov_find_audio_codec_tag(AVFormatContext *s, MOVTrack *track)
586
{
587
    int tag = track->enc->codec_tag;
588
    if (!tag) {
589
        tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
590
    }
591
    // if no mac fcc found, try with Microsoft tags
592
    if (!tag) {
593
        int ms_tag = codec_get_tag(codec_wav_tags, track->enc->codec_id);
594
        if (ms_tag) {
595
            tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
596
            av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, the file may be unplayable!\n");
597
        }
598
    }
599
    assert(tag);
600
    return tag;
601
}
602

    
603
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
604
{
605
    offset_t pos = url_ftell(pb);
606
    char compressor_name[32];
607

    
608
    put_be32(pb, 0); /* size */
609
    put_le32(pb, track->tag); // store it byteswapped
610
    put_be32(pb, 0); /* Reserved */
611
    put_be16(pb, 0); /* Reserved */
612
    put_be16(pb, 1); /* Data-reference index */
613

    
614
    put_be16(pb, 0); /* Codec stream version */
615
    put_be16(pb, 0); /* Codec stream revision (=0) */
616
    if (track->mode == MODE_MOV) {
617
        put_tag(pb, "FFMP"); /* Vendor */
618
        if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
619
            put_be32(pb, 0); /* Temporal Quality */
620
            put_be32(pb, 0x400); /* Spatial Quality = lossless*/
621
        } else {
622
            put_be32(pb, 0x200); /* Temporal Quality = normal */
623
            put_be32(pb, 0x200); /* Spatial Quality = normal */
624
        }
625
    } else {
626
        put_be32(pb, 0); /* Reserved */
627
        put_be32(pb, 0); /* Reserved */
628
        put_be32(pb, 0); /* Reserved */
629
    }
630
    put_be16(pb, track->enc->width); /* Video width */
631
    put_be16(pb, track->enc->height); /* Video height */
632
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
633
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
634
    put_be32(pb, 0); /* Data size (= 0) */
635
    put_be16(pb, 1); /* Frame count (= 1) */
636

    
637
    memset(compressor_name,0,32);
638
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
639
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
640
        strncpy(compressor_name,track->enc->codec->name,31);
641
    put_byte(pb, strlen(compressor_name));
642
    put_buffer(pb, compressor_name, 31);
643

    
644
    put_be16(pb, 0x18); /* Reserved */
645
    put_be16(pb, 0xffff); /* Reserved */
646
    if(track->enc->codec_id == CODEC_ID_MPEG4)
647
        mov_write_esds_tag(pb, track);
648
    else if(track->enc->codec_id == CODEC_ID_H263)
649
        mov_write_d263_tag(pb);
650
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
651
        mov_write_svq3_tag(pb);
652
    else if(track->enc->codec_id == CODEC_ID_H264)
653
        mov_write_avcc_tag(pb, track);
654

    
655
    return updateSize (pb, pos);
656
}
657

    
658
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack* track)
659
{
660
    offset_t pos = url_ftell(pb);
661
    put_be32(pb, 0); /* size */
662
    put_tag(pb, "stsd");
663
    put_be32(pb, 0); /* version & flags */
664
    put_be32(pb, 1); /* entry count */
665
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
666
        mov_write_video_tag(pb, track);
667
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
668
        mov_write_audio_tag(pb, track);
669
    return updateSize(pb, pos);
670
}
671

    
672
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack* track)
673
{
674
    Time2Sample *ctts_entries;
675
    uint32_t entries = 0;
676
    uint32_t atom_size;
677
    int i;
678

    
679
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
680
    ctts_entries[0].count = 1;
681
    ctts_entries[0].duration = track->cluster[0].cts;
682
    for (i=1; i<track->entry; i++) {
683
        if (track->cluster[i].cts == ctts_entries[entries].duration) {
684
            ctts_entries[entries].count++; /* compress */
685
        } else {
686
            entries++;
687
            ctts_entries[entries].duration = track->cluster[i].cts;
688
            ctts_entries[entries].count = 1;
689
        }
690
    }
691
    entries++; /* last one */
692
    atom_size = 16 + (entries * 8);
693
    put_be32(pb, atom_size); /* size */
694
    put_tag(pb, "ctts");
695
    put_be32(pb, 0); /* version & flags */
696
    put_be32(pb, entries); /* entry count */
697
    for (i=0; i<entries; i++) {
698
        put_be32(pb, ctts_entries[i].count);
699
        put_be32(pb, ctts_entries[i].duration);
700
    }
701
    av_free(ctts_entries);
702
    return atom_size;
703
}
704

    
705
/* TODO: */
706
/* Time to sample atom */
707
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack* track)
708
{
709
    put_be32(pb, 0x18); /* size */
710
    put_tag(pb, "stts");
711
    put_be32(pb, 0); /* version & flags */
712
    put_be32(pb, 1); /* entry count */
713

    
714
    put_be32(pb, track->sampleCount); /* sample count */
715
    put_be32(pb, track->sampleDuration); /* sample duration */
716
    return 0x18;
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

    
1202
static size_t ascii_to_wc (ByteIOContext *pb, char *b, size_t n)
1203
{
1204
    size_t i;
1205
    unsigned char c;
1206
    for (i = 0; i < n - 1; i++) {
1207
        c = b[i];
1208
        if (! (0x20 <= c && c <= 0x7f ))
1209
            c = 0x3f;  /* '?' */
1210
        put_be16(pb, c);
1211
    }
1212
    put_be16(pb, 0x00);
1213
    return 2*n;
1214
}
1215

    
1216
static uint16_t language_code (const char *str)
1217
{
1218
    return ((((str[0]-0x60) & 0x1F)<<10) + (((str[1]-0x60) & 0x1F)<<5) + ((str[2]-0x60) & 0x1F));
1219
}
1220

    
1221
static int mov_write_uuidusmt_tag (ByteIOContext *pb, AVFormatContext *s)
1222
{
1223
    size_t len, size;
1224
    offset_t pos, curpos;
1225

    
1226
    size = 0;
1227
    if (s->title[0]) {
1228
        pos = url_ftell(pb);
1229
        put_be32(pb, 0); /* size placeholder*/
1230
        put_tag(pb, "uuid");
1231
        put_tag(pb, "USMT");
1232
        put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1233
        put_be32(pb, 0xbb88695c );
1234
        put_be32(pb, 0xfac9c740 );
1235
        size += 24;
1236

    
1237
        put_be32(pb, 0); /* size placeholder*/
1238
        put_tag(pb, "MTDT");
1239
        put_be16(pb, 4);
1240
        size += 10;
1241

    
1242
        // ?
1243
        put_be16(pb, 0x0C);                 /* size */
1244
        put_be32(pb, 0x0B);                 /* type */
1245
        put_be16(pb, language_code("und")); /* language */
1246
        put_be16(pb, 0x0);                  /* ? */
1247
        put_be16(pb, 0x021C);               /* data */
1248
        size += 12;
1249

    
1250
        // Encoder
1251
        len = strlen(LIBAVCODEC_IDENT)+1;
1252
        put_be16(pb, len*2+10);             /* size */
1253
        put_be32(pb, 0x04);                 /* type */
1254
        put_be16(pb, language_code("eng")); /* language */
1255
        put_be16(pb, 0x01);                 /* ? */
1256
        ascii_to_wc(pb, LIBAVCODEC_IDENT, len);
1257
        size += len*2+10;
1258

    
1259
        // Title
1260
        len = strlen(s->title)+1;
1261
        put_be16(pb, len*2+10);             /* size */
1262
        put_be32(pb, 0x01);                 /* type */
1263
        put_be16(pb, language_code("eng")); /* language */
1264
        put_be16(pb, 0x01);                 /* ? */
1265
        ascii_to_wc (pb, s->title, len);
1266
        size += len*2+10;
1267

    
1268
        // Date
1269
//        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);
1270
        len = strlen("2006/04/01 11:11:11")+1;
1271
        put_be16(pb, len*2+10);    /* size */
1272
        put_be32(pb, 0x03);        /* type */
1273
        put_be16(pb, language_code("und")); /* language */
1274
        put_be16(pb, 0x01);        /* ? */
1275
        ascii_to_wc (pb, "2006/04/01 11:11:11", len);
1276
        size += len*2+10;
1277

    
1278
        // size
1279
        curpos = url_ftell(pb);
1280
        url_fseek(pb, pos, SEEK_SET);
1281
        put_be32(pb, size);
1282
        url_fseek(pb, pos+24, SEEK_SET);
1283
        put_be32(pb, size-24);
1284
        url_fseek(pb, curpos, SEEK_SET);
1285
    }
1286

    
1287
    return size;
1288
}
1289

    
1290
static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1291
                              AVFormatContext *s)
1292
{
1293
    int i;
1294
    offset_t pos = url_ftell(pb);
1295
    put_be32(pb, 0); /* size placeholder*/
1296
    put_tag(pb, "moov");
1297
    mov->timescale = globalTimescale;
1298

    
1299
    for (i=0; i<mov->nb_streams; i++) {
1300
        if(mov->tracks[i].entry <= 0) continue;
1301

    
1302
        if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {
1303
            mov->tracks[i].timescale = mov->tracks[i].enc->time_base.den;
1304
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->time_base.num;
1305
        } else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {
1306
            mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;
1307
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;
1308
        }
1309

    
1310
        mov->tracks[i].trackDuration =
1311
            (int64_t)mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;
1312
        mov->tracks[i].time = mov->time;
1313
        mov->tracks[i].trackID = i+1;
1314
    }
1315

    
1316
    mov_write_mvhd_tag(pb, mov);
1317
    //mov_write_iods_tag(pb, mov);
1318
    for (i=0; i<mov->nb_streams; i++) {
1319
        if(mov->tracks[i].entry > 0) {
1320
            mov_write_trak_tag(pb, &(mov->tracks[i]));
1321
        }
1322
    }
1323

    
1324
    if (mov->mode == MODE_PSP)
1325
        mov_write_uuidusmt_tag(pb, s);
1326
    else
1327
    mov_write_udta_tag(pb, mov, s);
1328

    
1329
    return updateSize(pb, pos);
1330
}
1331

    
1332
static int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1333
{
1334
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1335
    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1336

    
1337
    mov->mdat_pos = url_ftell(pb);
1338
    put_be32(pb, 0); /* size placeholder*/
1339
    put_tag(pb, "mdat");
1340
    return 0;
1341
}
1342

    
1343
/* TODO: This needs to be more general */
1344
static void mov_write_ftyp_tag (ByteIOContext *pb, AVFormatContext *s)
1345
{
1346
    MOVContext *mov = s->priv_data;
1347

    
1348
    put_be32(pb, 0x14 ); /* size */
1349
    put_tag(pb, "ftyp");
1350

    
1351
    if ( mov->mode == MODE_3GP )
1352
        put_tag(pb, "3gp4");
1353
    else if ( mov->mode == MODE_3G2 )
1354
        put_tag(pb, "3g2a");
1355
    else if ( mov->mode == MODE_PSP )
1356
        put_tag(pb, "MSNV");
1357
    else if ( mov->mode == MODE_MP4 )
1358
        put_tag(pb, "isom");
1359
    else
1360
        put_tag(pb, "qt  ");
1361

    
1362
    put_be32(pb, 0x200 );
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, "mp41");
1372
    else
1373
        put_tag(pb, "qt  ");
1374
}
1375

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

    
1385
    put_be32(pb, 0x94 ); /* size */
1386
    put_tag(pb, "uuid");
1387
    put_tag(pb, "PROF");
1388

    
1389
    put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1390
    put_be32(pb, 0xbb88695c );
1391
    put_be32(pb, 0xfac9c740 );
1392

    
1393
    put_be32(pb, 0x0 );  /* ? */
1394
    put_be32(pb, 0x3 );  /* 3 sections ? */
1395

    
1396
    put_be32(pb, 0x14 ); /* size */
1397
    put_tag(pb, "FPRF");
1398
    put_be32(pb, 0x0 );  /* ? */
1399
    put_be32(pb, 0x0 );  /* ? */
1400
    put_be32(pb, 0x0 );  /* ? */
1401

    
1402
    put_be32(pb, 0x2c );  /* size */
1403
    put_tag(pb, "APRF");   /* audio */
1404
    put_be32(pb, 0x0 );
1405
    put_be32(pb, 0x2 );   /* TrackID */
1406
    put_tag(pb, "mp4a");
1407
    put_be32(pb, 0x20f );
1408
    put_be32(pb, 0x0 );
1409
    put_be32(pb, audio_kbitrate);
1410
    put_be32(pb, audio_kbitrate);
1411
    put_be32(pb, AudioRate );
1412
    put_be32(pb, AudioCodec->channels );
1413

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

    
1437
static int mov_write_header(AVFormatContext *s)
1438
{
1439
    ByteIOContext *pb = &s->pb;
1440
    MOVContext *mov = s->priv_data;
1441
    int i;
1442

    
1443
    /* Default mode == MP4 */
1444
    mov->mode = MODE_MP4;
1445

    
1446
    if (s->oformat != NULL) {
1447
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1448
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3G2;
1449
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1450
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1451

    
1452
        mov_write_ftyp_tag(pb,s);
1453
        if ( mov->mode == MODE_PSP ) {
1454
            if ( s->nb_streams != 2 ) {
1455
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1456
                return -1;
1457
            }
1458
            mov_write_uuidprof_tag(pb,s);
1459
        }
1460
    }
1461

    
1462
    for(i=0; i<s->nb_streams; i++){
1463
        AVStream *st= s->streams[i];
1464
        MOVTrack *track= &mov->tracks[i];
1465

    
1466
        track->enc = st->codec;
1467
        track->language = ff_mov_iso639_to_lang(st->language, mov->mode != MODE_MOV);
1468
        track->mode = mov->mode;
1469
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1470
            track->tag = mov_find_video_codec_tag(s, track);
1471
            av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1472
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO){
1473
            track->tag = mov_find_audio_codec_tag(s, track);
1474
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1475
            track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
1476
        }
1477
    }
1478

    
1479
    mov_write_mdat_tag(pb, mov);
1480
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1481
    mov->nb_streams = s->nb_streams;
1482

    
1483
    put_flush_packet(pb);
1484

    
1485
    return 0;
1486
}
1487

    
1488
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1489
{
1490
    MOVContext *mov = s->priv_data;
1491
    ByteIOContext *pb = &s->pb;
1492
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1493
    AVCodecContext *enc = trk->enc;
1494
    unsigned int samplesInChunk = 0;
1495
    int size= pkt->size;
1496

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

    
1500
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1501
        /* We must find out how many AMR blocks there are in one packet */
1502
        static uint16_t packed_size[16] =
1503
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1504
        int len = 0;
1505

    
1506
        while (len < size && samplesInChunk < 100) {
1507
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1508
            samplesInChunk++;
1509
        }
1510
        if(samplesInChunk > 1){
1511
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, inplement a AVParser for it\n");
1512
            return -1;
1513
        }
1514
    } else if (trk->sampleSize)
1515
        samplesInChunk = size/trk->sampleSize;
1516
    else
1517
        samplesInChunk = 1;
1518

    
1519
    /* copy extradata if it exists */
1520
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1521
        trk->vosLen = enc->extradata_size;
1522
        trk->vosData = av_malloc(trk->vosLen);
1523
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1524
    }
1525

    
1526
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1527
        /* from x264 or from bytestream h264 */
1528
        /* nal reformating needed */
1529
        avc_parse_nal_units(&pkt->data, &pkt->size);
1530
        assert(pkt->size);
1531
        size = pkt->size;
1532
    }
1533

    
1534
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1535
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1536
        if (!trk->cluster)
1537
            return -1;
1538
    }
1539

    
1540
    trk->cluster[trk->entry].pos = url_ftell(pb);
1541
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1542
    trk->cluster[trk->entry].size = size;
1543
    trk->cluster[trk->entry].entries = samplesInChunk;
1544
    if(enc->codec_type == CODEC_TYPE_VIDEO) {
1545
        if (pkt->dts != pkt->pts)
1546
            trk->hasBframes = 1;
1547
        trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1548
        trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1549
        if(trk->cluster[trk->entry].key_frame)
1550
            trk->hasKeyframes++;
1551
    }
1552
    trk->entry++;
1553
    trk->sampleCount += samplesInChunk;
1554
    mov->mdat_size += size;
1555

    
1556
    put_buffer(pb, pkt->data, size);
1557

    
1558
    put_flush_packet(pb);
1559
    return 0;
1560
}
1561

    
1562
static int mov_write_trailer(AVFormatContext *s)
1563
{
1564
    MOVContext *mov = s->priv_data;
1565
    ByteIOContext *pb = &s->pb;
1566
    int res = 0;
1567
    int i;
1568

    
1569
    offset_t moov_pos = url_ftell(pb);
1570

    
1571
    /* Write size of mdat tag */
1572
    if (mov->mdat_size+8 <= UINT32_MAX) {
1573
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
1574
        put_be32(pb, mov->mdat_size+8);
1575
    } else {
1576
        /* overwrite 'wide' placeholder atom */
1577
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1578
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1579
        put_tag(pb, "mdat");
1580
        put_be64(pb, mov->mdat_size+16);
1581
    }
1582
    url_fseek(pb, moov_pos, SEEK_SET);
1583

    
1584
    mov_write_moov_tag(pb, mov, s);
1585

    
1586
    for (i=0; i<mov->nb_streams; i++) {
1587
        av_freep(&mov->tracks[i].cluster);
1588

    
1589
        if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1590

    
1591
    }
1592

    
1593
    put_flush_packet(pb);
1594

    
1595
    return res;
1596
}
1597

    
1598
#ifdef CONFIG_MOV_MUXER
1599
AVOutputFormat mov_muxer = {
1600
    "mov",
1601
    "mov format",
1602
    NULL,
1603
    "mov",
1604
    sizeof(MOVContext),
1605
    CODEC_ID_AAC,
1606
    CODEC_ID_MPEG4,
1607
    mov_write_header,
1608
    mov_write_packet,
1609
    mov_write_trailer,
1610
    .flags = AVFMT_GLOBALHEADER,
1611
};
1612
#endif
1613
#ifdef CONFIG_TGP_MUXER
1614
AVOutputFormat tgp_muxer = {
1615
    "3gp",
1616
    "3gp format",
1617
    NULL,
1618
    "3gp",
1619
    sizeof(MOVContext),
1620
    CODEC_ID_AMR_NB,
1621
    CODEC_ID_H263,
1622
    mov_write_header,
1623
    mov_write_packet,
1624
    mov_write_trailer,
1625
    .flags = AVFMT_GLOBALHEADER,
1626
};
1627
#endif
1628
#ifdef CONFIG_MP4_MUXER
1629
AVOutputFormat mp4_muxer = {
1630
    "mp4",
1631
    "mp4 format",
1632
    "application/mp4",
1633
    "mp4,m4a",
1634
    sizeof(MOVContext),
1635
    CODEC_ID_AAC,
1636
    CODEC_ID_MPEG4,
1637
    mov_write_header,
1638
    mov_write_packet,
1639
    mov_write_trailer,
1640
    .flags = AVFMT_GLOBALHEADER,
1641
};
1642
#endif
1643
#ifdef CONFIG_PSP_MUXER
1644
AVOutputFormat psp_muxer = {
1645
    "psp",
1646
    "psp mp4 format",
1647
    NULL,
1648
    "mp4,psp",
1649
    sizeof(MOVContext),
1650
    CODEC_ID_AAC,
1651
    CODEC_ID_MPEG4,
1652
    mov_write_header,
1653
    mov_write_packet,
1654
    mov_write_trailer,
1655
    .flags = AVFMT_GLOBALHEADER,
1656
};
1657
#endif
1658
#ifdef CONFIG_TG2_MUXER
1659
AVOutputFormat tg2_muxer = {
1660
    "3g2",
1661
    "3gp2 format",
1662
    NULL,
1663
    "3g2",
1664
    sizeof(MOVContext),
1665
    CODEC_ID_AMR_NB,
1666
    CODEC_ID_H263,
1667
    mov_write_header,
1668
    mov_write_packet,
1669
    mov_write_trailer,
1670
    .flags = AVFMT_GLOBALHEADER,
1671
};
1672
#endif