Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ ed90d370

History | View | Annotate | Download (51.8 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 "avi.h"
22
#include "avio.h"
23
#include "mov.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
    int         ents_allocated;
51
    long        timescale;
52
    long        time;
53
    int64_t     trackDuration;
54
    long        sampleCount;
55
    long        sampleDuration;
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
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
105
        int id = i % MOV_INDEX_CLUSTER_SIZE;
106
        if(mode64 == 1)
107
            put_be64(pb, track->cluster[cl][id].pos);
108
        else
109
            put_be32(pb, track->cluster[cl][id].pos);
110
    }
111
    return updateSize (pb, pos);
112
}
113

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

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

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

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

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

    
184
    return updateSize (pb, pos);
185
}
186

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

    
213
static int mov_write_damr_tag(ByteIOContext *pb)
214
{
215
    put_be32(pb, 0x11); /* size */
216
    put_tag(pb, "damr");
217
    put_tag(pb, "FFMP");
218
    put_byte(pb, 0);
219

    
220
    //put_be16(pb, 0x80); /* Mode set (all modes for AMR_NB) */
221
    //put_be16(pb, 0xa); /* Mode change period (no restriction) */
222
    put_be16(pb, 0x81ff); /* Mode set (all modes for AMR_NB) */
223
    put_be16(pb, 1); /* Mode change period (no restriction) */
224
    return 0x11;
225
}
226

    
227
static int mov_write_samr_tag(ByteIOContext *pb)
228
{
229
    put_be32(pb, 0x11); /* size */
230
    put_tag(pb, "samr");
231
    put_tag(pb, "FFMP");
232
    put_byte(pb, 1);
233

    
234
    put_be16(pb, 0x80); /* Mode set (all modes for AMR_NB) */
235
    put_be16(pb, 0x5); /* Mode change period (no restriction) */
236
    return 0x11;
237
}
238

    
239
static int mov_write_enda_tag(ByteIOContext *pb)
240
{
241
    put_be32(pb, 10);
242
    put_tag(pb, "enda");
243
    put_be16(pb, 1); /* little endian */
244
    return 10;
245
}
246

    
247
static unsigned int descrLength(unsigned int len)
248
{
249
    int i;
250
    for(i=1; len>>(7*i); i++);
251
    return len + 1 + i;
252
}
253

    
254
static void putDescr(ByteIOContext *pb, int tag, unsigned int size)
255
{
256
    int i= descrLength(size) - size - 2;
257
    put_byte(pb, tag);
258
    for(; i>0; i--)
259
        put_byte(pb, (size>>(7*i)) | 0x80);
260
    put_byte(pb, size & 0x7F);
261
}
262

    
263
static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track) // Basic
264
{
265
    offset_t pos = url_ftell(pb);
266
    int decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
267

    
268
    put_be32(pb, 0);               // size
269
    put_tag(pb, "esds");
270
    put_be32(pb, 0);               // Version
271

    
272
    // ES descriptor
273
    putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
274
             descrLength(1));
275
    put_be16(pb, track->trackID);
276
    put_byte(pb, 0x00);            // flags (= no flags)
277

    
278
    // DecoderConfig descriptor
279
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
280

    
281
    // Object type indication
282
    put_byte(pb, codec_get_tag(ff_mov_obj_type, track->enc->codec_id));
283

    
284
    // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
285
    // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
286
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
287
        put_byte(pb, 0x15);            // flags (= Audiostream)
288
    else
289
        put_byte(pb, 0x11);            // flags (= Visualstream)
290

    
291
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));             // Buffersize DB (24 bits)
292
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF);          // Buffersize DB
293

    
294
    put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate));     // maxbitrate  (FIXME should be max rate in any 1 sec window)
295
    if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
296
        put_be32(pb, 0);     // vbr
297
    else
298
        put_be32(pb, track->enc->rc_max_rate);     // avg bitrate
299

    
300
    if (track->vosLen)
301
    {
302
        // DecoderSpecific info descriptor
303
        putDescr(pb, 0x05, track->vosLen);
304
        put_buffer(pb, track->vosData, track->vosLen);
305
    }
306

    
307

    
308
    // SL descriptor
309
    putDescr(pb, 0x06, 1);
310
    put_byte(pb, 0x02);
311
    return updateSize (pb, pos);
312
}
313

    
314
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack* track)
315
{
316
    offset_t pos = url_ftell(pb);
317

    
318
    put_be32(pb, 0);     /* size */
319
    put_tag(pb, "wave");
320

    
321
    put_be32(pb, 12);    /* size */
322
    put_tag(pb, "frma");
323
    put_le32(pb, track->tag);
324

    
325
    if (track->enc->codec_id == CODEC_ID_AAC) {
326
        mov_write_esds_tag(pb, track);
327
    } else if (track->enc->codec_id == CODEC_ID_PCM_S24LE ||
328
               track->enc->codec_id == CODEC_ID_PCM_S32LE) {
329
        mov_write_enda_tag(pb);
330
    } else if (track->enc->codec_id == CODEC_ID_AMR_NB) {
331
        mov_write_samr_tag(pb);
332
    }
333

    
334
    put_be32(pb, 8);     /* size */
335
    put_be32(pb, 0);     /* null tag */
336

    
337
    return updateSize (pb, pos);
338
}
339

    
340
static const CodecTag codec_movaudio_tags[] = {
341
    { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') },
342
    { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') },
343
    { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') },
344
    { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') },
345
    { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') },
346
    { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
347
    { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') },
348
    { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') },
349
    { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') },
350
    { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') },
351
    { CODEC_ID_PCM_S24BE, MKTAG('i', 'n', '2', '4') },
352
    { CODEC_ID_PCM_S24LE, MKTAG('i', 'n', '2', '4') },
353
    { CODEC_ID_PCM_S32BE, MKTAG('i', 'n', '3', '2') },
354
    { CODEC_ID_PCM_S32LE, MKTAG('i', 'n', '3', '2') },
355
    { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') },
356
    { CODEC_ID_NONE, 0 },
357
};
358

    
359
static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack* track)
360
{
361
    offset_t pos = url_ftell(pb);
362
    int version = track->mode == MODE_MOV &&
363
        (track->enc->codec_id == CODEC_ID_AAC ||
364
         track->enc->codec_id == CODEC_ID_PCM_S32LE ||
365
         track->enc->codec_id == CODEC_ID_PCM_S24LE);
366

    
367
    put_be32(pb, 0); /* size */
368
    put_le32(pb, track->tag); // store it byteswapped
369
    put_be32(pb, 0); /* Reserved */
370
    put_be16(pb, 0); /* Reserved */
371
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
372

    
373
    /* SoundDescription */
374
    put_be16(pb, version); /* Version */
375
    put_be16(pb, 0); /* Revision level */
376
    put_be32(pb, 0); /* Reserved */
377

    
378
    put_be16(pb, track->enc->channels); /* Number of channels */
379
    /* TODO: Currently hard-coded to 16-bit, there doesn't seem
380
                 to be a good way to get number of bits of audio */
381
    put_be16(pb, 0x10); /* Reserved */
382

    
383
    if(track->enc->codec_id == CODEC_ID_AAC ||
384
       track->enc->codec_id == CODEC_ID_MP3 ||
385
       track->enc->codec_id == CODEC_ID_AMR_NB) {
386
        put_be16(pb, 0xfffe); /* compression ID (vbr)*/
387
    } else {
388
        put_be16(pb, 0); /* compression ID (= 0) */
389
    }
390
    put_be16(pb, 0); /* packet size (= 0) */
391
    put_be16(pb, track->timescale); /* Time scale */
392
    put_be16(pb, 0); /* Reserved */
393

    
394
    if(version == 1) {
395
        /* SoundDescription V1 extended info */
396
        put_be32(pb, track->enc->frame_size); /* Samples per packet  */
397
        put_be32(pb, track->sampleDuration); /* Bytes per frame */
398
        put_be32(pb, 8); /* Bytes per sample */
399
        put_be32(pb, 2);
400
    }
401

    
402
    if(track->mode == MODE_MOV &&
403
       (track->enc->codec_id == CODEC_ID_AAC ||
404
        track->enc->codec_id == CODEC_ID_AMR_NB ||
405
        track->enc->codec_id == CODEC_ID_PCM_S24LE ||
406
        track->enc->codec_id == CODEC_ID_PCM_S32LE))
407
        mov_write_wave_tag(pb, track);
408
    else if(track->enc->codec_id == CODEC_ID_AAC)
409
        mov_write_esds_tag(pb, track);
410
    else if(track->enc->codec_id == CODEC_ID_AMR_NB)
411
        mov_write_damr_tag(pb);
412

    
413
    return updateSize (pb, pos);
414
}
415

    
416
static int mov_write_d263_tag(ByteIOContext *pb)
417
{
418
    put_be32(pb, 0xf); /* size */
419
    put_tag(pb, "d263");
420
    put_tag(pb, "FFMP");
421
    put_be16(pb, 0x0a);
422
    put_byte(pb, 0);
423
    return 0xf;
424
}
425

    
426
/* TODO: No idea about these values */
427
static int mov_write_svq3_tag(ByteIOContext *pb)
428
{
429
    put_be32(pb, 0x15);
430
    put_tag(pb, "SMI ");
431
    put_tag(pb, "SEQH");
432
    put_be32(pb, 0x5);
433
    put_be32(pb, 0xe2c0211d);
434
    put_be32(pb, 0xc0000000);
435
    put_byte(pb, 0);
436
    return 0x15;
437
}
438

    
439
static uint8_t *avc_find_startcode( uint8_t *p, uint8_t *end )
440
{
441
    uint8_t *a = p + 4 - ((int)p & 3);
442

    
443
    for( end -= 3; p < a && p < end; p++ ) {
444
        if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
445
            return p;
446
    }
447

    
448
    for( end -= 3; p < end; p += 4 ) {
449
        uint32_t x = *(uint32_t*)p;
450
//      if( (x - 0x01000100) & (~x) & 0x80008000 ) // little endian
451
//      if( (x - 0x00010001) & (~x) & 0x00800080 ) // big endian
452
        if( (x - 0x01010101) & (~x) & 0x80808080 ) { // generic
453
            if( p[1] == 0 ) {
454
                if( p[0] == 0 && p[2] == 1 )
455
                    return p-1;
456
                if( p[2] == 0 && p[3] == 1 )
457
                    return p;
458
            }
459
            if( p[3] == 0 ) {
460
                if( p[2] == 0 && p[4] == 1 )
461
                    return p+1;
462
                if( p[4] == 0 && p[5] == 1 )
463
                    return p+2;
464
            }
465
        }
466
    }
467

    
468
    for( end += 3; p < end; p++ ) {
469
        if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
470
            return p;
471
    }
472

    
473
    return end + 3;
474
}
475

    
476
static void avc_parse_nal_units(uint8_t **buf, int *size)
477
{
478
    ByteIOContext pb;
479
    uint8_t *p = *buf;
480
    uint8_t *end = p + *size;
481
    uint8_t *nal_start, *nal_end;
482

    
483
    url_open_dyn_buf(&pb);
484
    nal_start = avc_find_startcode(p, end);
485
    while (nal_start < end) {
486
        while(!*(nal_start++));
487
        nal_end = avc_find_startcode(nal_start, end);
488
        put_be32(&pb, nal_end - nal_start);
489
        put_buffer(&pb, nal_start, nal_end - nal_start);
490
        nal_start = nal_end;
491
    }
492
    av_freep(buf);
493
    *size = url_close_dyn_buf(&pb, buf);
494
}
495

    
496
static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
497
{
498
    offset_t pos = url_ftell(pb);
499

    
500
    put_be32(pb, 0);
501
    put_tag(pb, "avcC");
502
    if (track->vosLen > 6) {
503
        /* check for h264 start code */
504
        if (BE_32(track->vosData) == 0x00000001) {
505
            uint8_t *buf, *end;
506
            uint32_t sps_size=0, pps_size=0;
507
            uint8_t *sps=0, *pps=0;
508

    
509
            avc_parse_nal_units(&track->vosData, &track->vosLen);
510
            buf = track->vosData;
511
            end = track->vosData + track->vosLen;
512

    
513
            /* look for sps and pps */
514
            while (buf < end) {
515
                unsigned int size;
516
                uint8_t nal_type;
517
                size = BE_32(buf);
518
                nal_type = buf[4] & 0x1f;
519
                if (nal_type == 7) { /* SPS */
520
                    sps = buf + 4;
521
                    sps_size = size;
522
                } else if (nal_type == 8) { /* PPS */
523
                    pps = buf + 4;
524
                    pps_size = size;
525
                }
526
                buf += size + 4;
527
            }
528
            assert(sps);
529
            assert(pps);
530

    
531
            put_byte(pb, 1); /* version */
532
            put_byte(pb, sps[1]); /* profile */
533
            put_byte(pb, sps[2]); /* profile compat */
534
            put_byte(pb, sps[3]); /* level */
535
            put_byte(pb, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 1 (11) */
536
            put_byte(pb, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
537

    
538
            put_be16(pb, sps_size);
539
            put_buffer(pb, sps, sps_size);
540
            put_byte(pb, 1); /* number of pps */
541
            put_be16(pb, pps_size);
542
            put_buffer(pb, pps, pps_size);
543
        } else {
544
            put_buffer(pb, track->vosData, track->vosLen);
545
        }
546
    }
547
    return updateSize(pb, pos);
548
}
549

    
550
static const CodecTag codec_movvideo_tags[] = {
551
    { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') },
552
    { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') },
553
    { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
554
    { CODEC_ID_H263, MKTAG('s', '2', '6', '3') },
555
    { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
556
    /* special handling in mov_find_video_codec_tag */
557
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
558
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
559
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'p', 'p') }, /* DVCPRO PAL */
560
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'n') }, /* DVCPRO50 NTSC */
561
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'p') }, /* DVCPRO50 PAL */
562
    { CODEC_ID_NONE, 0 },
563
};
564

    
565
static int mov_find_video_codec_tag(AVFormatContext *s, MOVTrack *track)
566
{
567
    int tag = track->enc->codec_tag;
568
    if (!tag) {
569
        if (track->enc->codec_id == CODEC_ID_DVVIDEO) {
570
            if (track->enc->height == 480) { /* NTSC */
571
                if (track->enc->pix_fmt == PIX_FMT_YUV422P)
572
                    tag = MKTAG('d', 'v', '5', 'n');
573
                else
574
                    tag = MKTAG('d', 'v', 'c', ' ');
575
            } else { /* assume PAL */
576
                if (track->enc->pix_fmt == PIX_FMT_YUV422P)
577
                    tag = MKTAG('d', 'v', '5', 'p');
578
                else if (track->enc->pix_fmt == PIX_FMT_YUV420P)
579
                    tag = MKTAG('d', 'v', 'c', 'p');
580
                else
581
                    tag = MKTAG('d', 'v', 'p', 'p');
582
            }
583
        } else {
584
            tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
585
        }
586
    }
587
    // if no mac fcc found, try with Microsoft tags
588
    if (!tag) {
589
        tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
590
        if (tag) {
591
            av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, the file may be unplayable!\n");
592
        }
593
    }
594
    assert(tag);
595
    return tag;
596
}
597

    
598
static int mov_find_audio_codec_tag(AVFormatContext *s, MOVTrack *track)
599
{
600
    int tag = track->enc->codec_tag;
601
    if (!tag) {
602
        tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
603
    }
604
    // if no mac fcc found, try with Microsoft tags
605
    if (!tag) {
606
        int ms_tag = codec_get_tag(codec_wav_tags, track->enc->codec_id);
607
        if (ms_tag) {
608
            tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
609
            av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, the file may be unplayable!\n");
610
        }
611
    }
612
    assert(tag);
613
    return tag;
614
}
615

    
616
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
617
{
618
    offset_t pos = url_ftell(pb);
619
    char compressor_name[32];
620

    
621
    put_be32(pb, 0); /* size */
622
    put_le32(pb, track->tag); // store it byteswapped
623
    put_be32(pb, 0); /* Reserved */
624
    put_be16(pb, 0); /* Reserved */
625
    put_be16(pb, 1); /* Data-reference index */
626

    
627
    put_be16(pb, 0); /* Codec stream version */
628
    put_be16(pb, 0); /* Codec stream revision (=0) */
629
    put_tag(pb, "FFMP"); /* Vendor */
630
    if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
631
        put_be32(pb, 0); /* Temporal Quality */
632
        put_be32(pb, 0x400); /* Spatial Quality = lossless*/
633
    } else {
634
        put_be32(pb, 0x200); /* Temporal Quality = normal */
635
        put_be32(pb, 0x200); /* Spatial Quality = normal */
636
    }
637
    put_be16(pb, track->enc->width); /* Video width */
638
    put_be16(pb, track->enc->height); /* Video height */
639
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
640
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
641
    put_be32(pb, 0); /* Data size (= 0) */
642
    put_be16(pb, 1); /* Frame count (= 1) */
643

    
644
    memset(compressor_name,0,32);
645
    if (track->enc->codec && track->enc->codec->name)
646
        strncpy(compressor_name,track->enc->codec->name,31);
647
    put_byte(pb, strlen(compressor_name));
648
    put_buffer(pb, compressor_name, 31);
649

    
650
    put_be16(pb, 0x18); /* Reserved */
651
    put_be16(pb, 0xffff); /* Reserved */
652
    if(track->enc->codec_id == CODEC_ID_MPEG4)
653
        mov_write_esds_tag(pb, track);
654
    else if(track->enc->codec_id == CODEC_ID_H263)
655
        mov_write_d263_tag(pb);
656
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
657
        mov_write_svq3_tag(pb);
658
    else if(track->enc->codec_id == CODEC_ID_H264)
659
        mov_write_avcc_tag(pb, track);
660

    
661
    return updateSize (pb, pos);
662
}
663

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

    
678
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack* track)
679
{
680
    Time2Sample *ctts_entries;
681
    uint32_t entries = 0;
682
    uint32_t atom_size;
683
    int i;
684

    
685
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
686
    ctts_entries[0].count = 1;
687
    ctts_entries[0].duration = track->cluster[0][0].cts;
688
    for (i=1; i<track->entry; i++) {
689
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
690
        int id = i % MOV_INDEX_CLUSTER_SIZE;
691
        if (track->cluster[cl][id].cts == ctts_entries[entries].duration) {
692
            ctts_entries[entries].count++; /* compress */
693
        } else {
694
            entries++;
695
            ctts_entries[entries].duration = track->cluster[cl][id].cts;
696
            ctts_entries[entries].count = 1;
697
        }
698
    }
699
    entries++; /* last one */
700
    atom_size = 16 + (entries * 8);
701
    put_be32(pb, atom_size); /* size */
702
    put_tag(pb, "ctts");
703
    put_be32(pb, 0); /* version & flags */
704
    put_be32(pb, entries); /* entry count */
705
    for (i=0; i<entries; i++) {
706
        put_be32(pb, ctts_entries[i].count);
707
        put_be32(pb, ctts_entries[i].duration);
708
    }
709
    av_free(ctts_entries);
710
    return atom_size;
711
}
712

    
713
/* TODO: */
714
/* Time to sample atom */
715
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack* track)
716
{
717
    put_be32(pb, 0x18); /* size */
718
    put_tag(pb, "stts");
719
    put_be32(pb, 0); /* version & flags */
720
    put_be32(pb, 1); /* entry count */
721

    
722
    put_be32(pb, track->sampleCount); /* sample count */
723
    put_be32(pb, track->sampleDuration); /* sample duration */
724
    return 0x18;
725
}
726

    
727
static int mov_write_dref_tag(ByteIOContext *pb)
728
{
729
    put_be32(pb, 28); /* size */
730
    put_tag(pb, "dref");
731
    put_be32(pb, 0); /* version & flags */
732
    put_be32(pb, 1); /* entry count */
733

    
734
    put_be32(pb, 0xc); /* size */
735
    put_tag(pb, "url ");
736
    put_be32(pb, 1); /* version & flags */
737

    
738
    return 28;
739
}
740

    
741
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track)
742
{
743
    offset_t pos = url_ftell(pb);
744
    put_be32(pb, 0); /* size */
745
    put_tag(pb, "stbl");
746
    mov_write_stsd_tag(pb, track);
747
    mov_write_stts_tag(pb, track);
748
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
749
        track->hasKeyframes < track->entry)
750
        mov_write_stss_tag(pb, track);
751
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
752
        track->hasBframes)
753
        mov_write_ctts_tag(pb, track);
754
    mov_write_stsc_tag(pb, track);
755
    mov_write_stsz_tag(pb, track);
756
    mov_write_stco_tag(pb, track);
757
    return updateSize(pb, pos);
758
}
759

    
760
static int mov_write_dinf_tag(ByteIOContext *pb)
761
{
762
    offset_t pos = url_ftell(pb);
763
    put_be32(pb, 0); /* size */
764
    put_tag(pb, "dinf");
765
    mov_write_dref_tag(pb);
766
    return updateSize(pb, pos);
767
}
768

    
769
static int mov_write_smhd_tag(ByteIOContext *pb)
770
{
771
    put_be32(pb, 16); /* size */
772
    put_tag(pb, "smhd");
773
    put_be32(pb, 0); /* version & flags */
774
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
775
    put_be16(pb, 0); /* reserved */
776
    return 16;
777
}
778

    
779
static int mov_write_vmhd_tag(ByteIOContext *pb)
780
{
781
    put_be32(pb, 0x14); /* size (always 0x14) */
782
    put_tag(pb, "vmhd");
783
    put_be32(pb, 0x01); /* version & flags */
784
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
785
    return 0x14;
786
}
787

    
788
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack* track)
789
{
790
    char *descr, *hdlr, *hdlr_type;
791
    offset_t pos = url_ftell(pb);
792

    
793
    if (!track) { /* no media --> data handler */
794
        hdlr = "dhlr";
795
        hdlr_type = "url ";
796
        descr = "DataHandler";
797
    } else {
798
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
799
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
800
            hdlr_type = "vide";
801
            descr = "VideoHandler";
802
        } else {
803
            hdlr_type = "soun";
804
            descr = "SoundHandler";
805
        }
806
    }
807

    
808
    put_be32(pb, 0); /* size */
809
    put_tag(pb, "hdlr");
810
    put_be32(pb, 0); /* Version & flags */
811
    put_buffer(pb, hdlr, 4); /* handler */
812
    put_tag(pb, hdlr_type); /* handler type */
813
    put_be32(pb ,0); /* reserved */
814
    put_be32(pb ,0); /* reserved */
815
    put_be32(pb ,0); /* reserved */
816
    put_byte(pb, strlen(descr)); /* string counter */
817
    put_buffer(pb, descr, strlen(descr)); /* handler description */
818
    return updateSize(pb, pos);
819
}
820

    
821
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack* track)
822
{
823
    offset_t pos = url_ftell(pb);
824
    put_be32(pb, 0); /* size */
825
    put_tag(pb, "minf");
826
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
827
        mov_write_vmhd_tag(pb);
828
    else
829
        mov_write_smhd_tag(pb);
830
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
831
        mov_write_hdlr_tag(pb, NULL);
832
    mov_write_dinf_tag(pb);
833
    mov_write_stbl_tag(pb, track);
834
    return updateSize(pb, pos);
835
}
836

    
837
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack* track)
838
{
839
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
840

    
841
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
842
    put_tag(pb, "mdhd");
843
    put_byte(pb, version);
844
    put_be24(pb, 0); /* flags */
845
    if (version == 1) {
846
        put_be64(pb, track->time);
847
        put_be64(pb, track->time);
848
    } else {
849
        put_be32(pb, track->time); /* creation time */
850
        put_be32(pb, track->time); /* modification time */
851
    }
852
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
853
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
854
    put_be16(pb, track->language); /* language */
855
    put_be16(pb, 0); /* reserved (quality) */
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
    if (track->hasBframes)
938
        put_be32(pb, track->sampleDuration); /* first pts is 1 */
939
    else
940
        put_be32(pb, 0);
941
    put_be32(pb, 0x00010000);
942
    return 0x24;
943
}
944

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

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

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

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

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

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

    
1025
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1026
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1027
    put_be16(pb, 0); /* reserved */
1028
    put_be32(pb, 0); /* reserved */
1029
    put_be32(pb, 0); /* reserved */
1030

    
1031
    /* Matrix structure */
1032
    put_be32(pb, 0x00010000); /* reserved */
1033
    put_be32(pb, 0x0); /* reserved */
1034
    put_be32(pb, 0x0); /* reserved */
1035
    put_be32(pb, 0x0); /* reserved */
1036
    put_be32(pb, 0x00010000); /* reserved */
1037
    put_be32(pb, 0x0); /* reserved */
1038
    put_be32(pb, 0x0); /* reserved */
1039
    put_be32(pb, 0x0); /* reserved */
1040
    put_be32(pb, 0x40000000); /* reserved */
1041

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

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

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

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

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

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

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

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

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

    
1176
static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1177
                              AVFormatContext *s)
1178
{
1179
    offset_t pos = url_ftell(pb);
1180
    int i;
1181

    
1182
    put_be32(pb, 0); /* size */
1183
    put_tag(pb, "udta");
1184

    
1185
    /* iTunes meta data */
1186
    mov_write_meta_tag(pb, mov, s);
1187

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

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

    
1209
    return updateSize(pb, pos);
1210
}
1211

    
1212

    
1213
static size_t ascii_to_wc (ByteIOContext *pb, char *b, size_t n)
1214
{
1215
    size_t i;
1216
    unsigned char c;
1217
    for (i = 0; i < n - 1; i++) {
1218
        c = b[i];
1219
        if (! (0x20 <= c && c <= 0x7f ))
1220
            c = 0x3f;  /* '?' */
1221
        put_be16(pb, c);
1222
    }
1223
    put_be16(pb, 0x00);
1224
    return 2*n;
1225
}
1226

    
1227
static uint16_t language_code (char *str)
1228
{
1229
    return ((((str[0]-'a') & 0x1F)<<10) + (((str[1]-'a') & 0x1F)<<5) + ((str[2]-'a') & 0x1F));
1230
}
1231

    
1232
static int mov_write_uuidusmt_tag (ByteIOContext *pb, AVFormatContext *s)
1233
{
1234
    size_t len, size;
1235
    offset_t pos, curpos;
1236

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

    
1248
        put_be32(pb, 0); /* size placeholder*/
1249
        put_tag(pb, "MTDT");
1250
        put_be16(pb, 1);
1251
        size += 10;
1252

    
1253
        // Title
1254
        len = strlen(s->title)+1;
1255
        put_be16(pb, len*2+10);             /* size */
1256
        put_be32(pb, 0x01);                 /* type */
1257
        put_be16(pb, language_code("und")); /* language */
1258
        put_be16(pb, 0x01);                 /* ? */
1259
        ascii_to_wc (pb, s->title, len);
1260
        size += len*2+10;
1261

    
1262
        // size
1263
        curpos = url_ftell(pb);
1264
        url_fseek(pb, pos, SEEK_SET);
1265
        put_be32(pb, size);
1266
        url_fseek(pb, pos+24, SEEK_SET);
1267
        put_be32(pb, size-24);
1268
        url_fseek(pb, curpos, SEEK_SET);
1269
    }
1270

    
1271
    return size;
1272
}
1273

    
1274
static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1275
                              AVFormatContext *s)
1276
{
1277
    int i;
1278
    offset_t pos = url_ftell(pb);
1279
    put_be32(pb, 0); /* size placeholder*/
1280
    put_tag(pb, "moov");
1281
    mov->timescale = globalTimescale;
1282

    
1283
    for (i=0; i<MAX_STREAMS; i++) {
1284
        if(mov->tracks[i].entry <= 0) continue;
1285

    
1286
        if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {
1287
            mov->tracks[i].timescale = mov->tracks[i].enc->time_base.den;
1288
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->time_base.num;
1289
        } else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {
1290
            mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;
1291
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;
1292
        }
1293

    
1294
        mov->tracks[i].trackDuration =
1295
            (int64_t)mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;
1296
        mov->tracks[i].time = mov->time;
1297
        mov->tracks[i].trackID = i+1;
1298
    }
1299

    
1300
    mov_write_mvhd_tag(pb, mov);
1301
    //mov_write_iods_tag(pb, mov);
1302
    for (i=0; i<MAX_STREAMS; i++) {
1303
        if(mov->tracks[i].entry > 0) {
1304
            mov_write_trak_tag(pb, &(mov->tracks[i]));
1305
        }
1306
    }
1307

    
1308
    if (mov->mode == MODE_PSP)
1309
        mov_write_uuidusmt_tag(pb, s);
1310
    else
1311
    mov_write_udta_tag(pb, mov, s);
1312

    
1313
    return updateSize(pb, pos);
1314
}
1315

    
1316
int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1317
{
1318
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1319
    put_tag(pb, "wide");
1320

    
1321
    mov->mdat_pos = url_ftell(pb);
1322
    put_be32(pb, 0); /* size placeholder*/
1323
    put_tag(pb, "mdat");
1324
    return 0;
1325
}
1326

    
1327
/* TODO: This needs to be more general */
1328
static void mov_write_ftyp_tag (ByteIOContext *pb, AVFormatContext *s)
1329
{
1330
    MOVContext *mov = s->priv_data;
1331

    
1332
    put_be32(pb, 0x14 ); /* size */
1333
    put_tag(pb, "ftyp");
1334

    
1335
    if ( mov->mode == MODE_3GP )
1336
        put_tag(pb, "3gp4");
1337
    else if ( mov->mode == MODE_3G2 )
1338
        put_tag(pb, "3g2a");
1339
    else if ( mov->mode == MODE_PSP )
1340
        put_tag(pb, "MSNV");
1341
    else if ( mov->mode == MODE_MP4 )
1342
        put_tag(pb, "isom");
1343
    else
1344
        put_tag(pb, "qt  ");
1345

    
1346
    put_be32(pb, 0x200 );
1347

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

    
1360
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1361
{
1362
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1363
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1364
    int AudioRate = AudioCodec->sample_rate;
1365
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1366
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1367
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1368

    
1369
    put_be32(pb, 0x94 ); /* size */
1370
    put_tag(pb, "uuid");
1371
    put_tag(pb, "PROF");
1372

    
1373
    put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1374
    put_be32(pb, 0xbb88695c );
1375
    put_be32(pb, 0xfac9c740 );
1376

    
1377
    put_be32(pb, 0x0 );  /* ? */
1378
    put_be32(pb, 0x3 );  /* 3 sections ? */
1379

    
1380
    put_be32(pb, 0x14 ); /* size */
1381
    put_tag(pb, "FPRF");
1382
    put_be32(pb, 0x0 );  /* ? */
1383
    put_be32(pb, 0x0 );  /* ? */
1384
    put_be32(pb, 0x0 );  /* ? */
1385

    
1386
    put_be32(pb, 0x2c );  /* size */
1387
    put_tag(pb, "APRF");   /* audio */
1388
    put_be32(pb, 0x0 );
1389
    put_be32(pb, 0x2 );   /* TrackID */
1390
    put_tag(pb, "mp4a");
1391
    put_be32(pb, 0x20f );
1392
    put_be32(pb, 0x0 );
1393
    put_be32(pb, audio_kbitrate);
1394
    put_be32(pb, audio_kbitrate);
1395
    put_be32(pb, AudioRate );
1396
    put_be32(pb, AudioCodec->channels );
1397

    
1398
    put_be32(pb, 0x34 );  /* size */
1399
    put_tag(pb, "VPRF");   /* video */
1400
    put_be32(pb, 0x0 );
1401
    put_be32(pb, 0x1 );    /* TrackID */
1402
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1403
        put_tag(pb, "avc1");
1404
        put_be16(pb, 0x014D );
1405
        put_be16(pb, 0x0015 );
1406
    } else {
1407
        put_tag(pb, "mp4v");
1408
        put_be16(pb, 0x0000 );
1409
        put_be16(pb, 0x0103 );
1410
    }
1411
    put_be32(pb, 0x0 );
1412
    put_be32(pb, video_kbitrate);
1413
    put_be32(pb, video_kbitrate);
1414
    put_be32(pb, FrameRate);
1415
    put_be32(pb, FrameRate);
1416
    put_be16(pb, VideoCodec->width);
1417
    put_be16(pb, VideoCodec->height);
1418
    put_be32(pb, 0x010001); /* ? */
1419
}
1420

    
1421
static int mov_write_header(AVFormatContext *s)
1422
{
1423
    ByteIOContext *pb = &s->pb;
1424
    MOVContext *mov = s->priv_data;
1425
    int i;
1426

    
1427
    /* Default mode == MP4 */
1428
    mov->mode = MODE_MP4;
1429

    
1430
    if (s->oformat != NULL) {
1431
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1432
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3G2;
1433
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1434
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1435

    
1436
        mov_write_ftyp_tag(pb,s);
1437
        if ( mov->mode == MODE_PSP ) {
1438
            if ( s->nb_streams != 2 ) {
1439
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1440
                return -1;
1441
            }
1442
            mov_write_uuidprof_tag(pb,s);
1443
        }
1444
    }
1445

    
1446
    for(i=0; i<s->nb_streams; i++){
1447
        AVStream *st= s->streams[i];
1448
        MOVTrack *track= &mov->tracks[i];
1449

    
1450
        track->enc = st->codec;
1451
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1452
            track->tag = mov_find_video_codec_tag(s, track);
1453
            av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1454
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO){
1455
            track->tag = mov_find_audio_codec_tag(s, track);
1456
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1457
        }
1458
        track->language = ff_mov_iso639_to_lang(st->language, mov->mode != MODE_MOV);
1459
        track->mode = mov->mode;
1460
    }
1461

    
1462
    mov_write_mdat_tag(pb, mov);
1463
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1464

    
1465
    put_flush_packet(pb);
1466

    
1467
    return 0;
1468
}
1469

    
1470
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1471
{
1472
    MOVContext *mov = s->priv_data;
1473
    ByteIOContext *pb = &s->pb;
1474
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1475
    AVCodecContext *enc = trk->enc;
1476
    int cl, id;
1477
    unsigned int samplesInChunk = 0;
1478
    int size= pkt->size;
1479

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

    
1483
    if (enc->codec_type == CODEC_TYPE_AUDIO) {
1484
        switch (enc->codec_id) {
1485
        case CODEC_ID_AMR_NB:
1486
            { /* We must find out how many AMR blocks there are in one packet */
1487
                static uint16_t packed_size[16] =
1488
                    {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1489
                int len = 0;
1490

    
1491
                while (len < size && samplesInChunk < 100) {
1492
                    len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1493
                    samplesInChunk++;
1494
                }
1495
            }
1496
            break;
1497
        case CODEC_ID_PCM_MULAW:
1498
        case CODEC_ID_PCM_ALAW:
1499
            samplesInChunk = size/enc->channels;
1500
            break;
1501
        case CODEC_ID_PCM_S16BE:
1502
        case CODEC_ID_PCM_S16LE:
1503
            samplesInChunk = size/(2*enc->channels);
1504
            break;
1505
        case CODEC_ID_PCM_S24BE:
1506
        case CODEC_ID_PCM_S24LE:
1507
            samplesInChunk = size/(3*enc->channels);
1508
            break;
1509
        case CODEC_ID_PCM_S32BE:
1510
        case CODEC_ID_PCM_S32LE:
1511
            samplesInChunk = size/(4*enc->channels);
1512
            break;
1513
        default:
1514
            samplesInChunk = 1;
1515
        }
1516
    } else {
1517
        samplesInChunk = 1;
1518
    }
1519

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

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

    
1535
    cl = trk->entry / MOV_INDEX_CLUSTER_SIZE;
1536
    id = trk->entry % MOV_INDEX_CLUSTER_SIZE;
1537

    
1538
    if (trk->ents_allocated <= trk->entry) {
1539
        trk->cluster = av_realloc(trk->cluster, (cl+1)*sizeof(void*));
1540
        if (!trk->cluster)
1541
            return -1;
1542
        trk->cluster[cl] = av_malloc(MOV_INDEX_CLUSTER_SIZE*sizeof(MOVIentry));
1543
        if (!trk->cluster[cl])
1544
            return -1;
1545
        trk->ents_allocated += MOV_INDEX_CLUSTER_SIZE;
1546
    }
1547

    
1548
    trk->cluster[cl][id].pos = url_ftell(pb);
1549
    trk->cluster[cl][id].samplesInChunk = samplesInChunk;
1550
    trk->cluster[cl][id].size = size;
1551
    trk->cluster[cl][id].entries = samplesInChunk;
1552
    if(enc->codec_type == CODEC_TYPE_VIDEO) {
1553
        if (pkt->dts != pkt->pts)
1554
            trk->hasBframes = 1;
1555
        trk->cluster[cl][id].cts = pkt->pts - pkt->dts;
1556
        trk->cluster[cl][id].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1557
        if(trk->cluster[cl][id].key_frame)
1558
            trk->hasKeyframes++;
1559
    }
1560
    trk->entry++;
1561
    trk->sampleCount += samplesInChunk;
1562
    mov->mdat_size += size;
1563

    
1564
    put_buffer(pb, pkt->data, size);
1565

    
1566
    put_flush_packet(pb);
1567
    return 0;
1568
}
1569

    
1570
static int mov_write_trailer(AVFormatContext *s)
1571
{
1572
    MOVContext *mov = s->priv_data;
1573
    ByteIOContext *pb = &s->pb;
1574
    int res = 0;
1575
    int i, j;
1576

    
1577
    offset_t moov_pos = url_ftell(pb);
1578

    
1579
    /* Write size of mdat tag */
1580
    if (mov->mdat_size+8 <= UINT32_MAX) {
1581
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
1582
        put_be32(pb, mov->mdat_size+8);
1583
    } else {
1584
        /* overwrite 'wide' placeholder atom */
1585
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1586
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1587
        put_tag(pb, "mdat");
1588
        put_be64(pb, mov->mdat_size+16);
1589
    }
1590
    url_fseek(pb, moov_pos, SEEK_SET);
1591

    
1592
    mov_write_moov_tag(pb, mov, s);
1593

    
1594
    for (i=0; i<MAX_STREAMS; i++) {
1595
        for (j=0; j<mov->tracks[i].ents_allocated/MOV_INDEX_CLUSTER_SIZE; j++) {
1596
            av_free(mov->tracks[i].cluster[j]);
1597
        }
1598
        av_free(mov->tracks[i].cluster);
1599
        if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1600

    
1601
        mov->tracks[i].cluster = NULL;
1602
        mov->tracks[i].ents_allocated = mov->tracks[i].entry = 0;
1603
    }
1604

    
1605
    put_flush_packet(pb);
1606

    
1607
    return res;
1608
}
1609

    
1610
static AVOutputFormat mov_oformat = {
1611
    "mov",
1612
    "mov format",
1613
    NULL,
1614
    "mov",
1615
    sizeof(MOVContext),
1616
    CODEC_ID_AAC,
1617
    CODEC_ID_MPEG4,
1618
    mov_write_header,
1619
    mov_write_packet,
1620
    mov_write_trailer,
1621
    .flags = AVFMT_GLOBALHEADER,
1622
};
1623

    
1624
static AVOutputFormat _3gp_oformat = {
1625
    "3gp",
1626
    "3gp format",
1627
    NULL,
1628
    "3gp",
1629
    sizeof(MOVContext),
1630
    CODEC_ID_AMR_NB,
1631
    CODEC_ID_H263,
1632
    mov_write_header,
1633
    mov_write_packet,
1634
    mov_write_trailer,
1635
    .flags = AVFMT_GLOBALHEADER,
1636
};
1637

    
1638
static AVOutputFormat mp4_oformat = {
1639
    "mp4",
1640
    "mp4 format",
1641
    "application/mp4",
1642
    "mp4,m4a",
1643
    sizeof(MOVContext),
1644
    CODEC_ID_AAC,
1645
    CODEC_ID_MPEG4,
1646
    mov_write_header,
1647
    mov_write_packet,
1648
    mov_write_trailer,
1649
    .flags = AVFMT_GLOBALHEADER,
1650
};
1651

    
1652
static AVOutputFormat psp_oformat = {
1653
    "psp",
1654
    "psp mp4 format",
1655
    NULL,
1656
    "mp4,psp",
1657
    sizeof(MOVContext),
1658
    CODEC_ID_AAC,
1659
    CODEC_ID_MPEG4,
1660
    mov_write_header,
1661
    mov_write_packet,
1662
    mov_write_trailer,
1663
    .flags = AVFMT_GLOBALHEADER,
1664
};
1665

    
1666
static AVOutputFormat _3g2_oformat = {
1667
    "3g2",
1668
    "3gp2 format",
1669
    NULL,
1670
    "3g2",
1671
    sizeof(MOVContext),
1672
    CODEC_ID_AMR_NB,
1673
    CODEC_ID_H263,
1674
    mov_write_header,
1675
    mov_write_packet,
1676
    mov_write_trailer,
1677
    .flags = AVFMT_GLOBALHEADER,
1678
};
1679

    
1680
int movenc_init(void)
1681
{
1682
    av_register_output_format(&mov_oformat);
1683
    av_register_output_format(&_3gp_oformat);
1684
    av_register_output_format(&mp4_oformat);
1685
    av_register_output_format(&psp_oformat);
1686
    av_register_output_format(&_3g2_oformat);
1687
    return 0;
1688
}