Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 5997ed78

History | View | Annotate | Download (51.5 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_be16(pb, 0x0a);
401
    put_byte(pb, 0);
402
    return 0xf;
403
}
404

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

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

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

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

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

    
452
    return end + 3;
453
}
454

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

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

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

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

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

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

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

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

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

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

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

    
595
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
596
{
597
    offset_t pos = url_ftell(pb);
598
    char compressor_name[32];
599

    
600
    put_be32(pb, 0); /* size */
601
    put_le32(pb, track->tag); // store it byteswapped
602
    put_be32(pb, 0); /* Reserved */
603
    put_be16(pb, 0); /* Reserved */
604
    put_be16(pb, 1); /* Data-reference index */
605

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

    
629
    memset(compressor_name,0,32);
630
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
631
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
632
        strncpy(compressor_name,track->enc->codec->name,31);
633
    put_byte(pb, strlen(compressor_name));
634
    put_buffer(pb, compressor_name, 31);
635

    
636
    put_be16(pb, 0x18); /* Reserved */
637
    put_be16(pb, 0xffff); /* Reserved */
638
    if(track->enc->codec_id == CODEC_ID_MPEG4)
639
        mov_write_esds_tag(pb, track);
640
    else if(track->enc->codec_id == CODEC_ID_H263)
641
        mov_write_d263_tag(pb);
642
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
643
        mov_write_svq3_tag(pb);
644
    else if(track->enc->codec_id == CODEC_ID_H264)
645
        mov_write_avcc_tag(pb, track);
646

    
647
    return updateSize (pb, pos);
648
}
649

    
650
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack* track)
651
{
652
    offset_t pos = url_ftell(pb);
653
    put_be32(pb, 0); /* size */
654
    put_tag(pb, "stsd");
655
    put_be32(pb, 0); /* version & flags */
656
    put_be32(pb, 1); /* entry count */
657
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
658
        mov_write_video_tag(pb, track);
659
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
660
        mov_write_audio_tag(pb, track);
661
    return updateSize(pb, pos);
662
}
663

    
664
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack* track)
665
{
666
    Time2Sample *ctts_entries;
667
    uint32_t entries = 0;
668
    uint32_t atom_size;
669
    int i;
670

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

    
697
/* TODO: */
698
/* Time to sample atom */
699
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack* track)
700
{
701
    put_be32(pb, 0x18); /* size */
702
    put_tag(pb, "stts");
703
    put_be32(pb, 0); /* version & flags */
704
    put_be32(pb, 1); /* entry count */
705

    
706
    put_be32(pb, track->sampleCount); /* sample count */
707
    put_be32(pb, track->sampleDuration); /* sample duration */
708
    return 0x18;
709
}
710

    
711
static int mov_write_dref_tag(ByteIOContext *pb)
712
{
713
    put_be32(pb, 28); /* size */
714
    put_tag(pb, "dref");
715
    put_be32(pb, 0); /* version & flags */
716
    put_be32(pb, 1); /* entry count */
717

    
718
    put_be32(pb, 0xc); /* size */
719
    put_tag(pb, "url ");
720
    put_be32(pb, 1); /* version & flags */
721

    
722
    return 28;
723
}
724

    
725
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track)
726
{
727
    offset_t pos = url_ftell(pb);
728
    put_be32(pb, 0); /* size */
729
    put_tag(pb, "stbl");
730
    mov_write_stsd_tag(pb, track);
731
    mov_write_stts_tag(pb, track);
732
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
733
        track->hasKeyframes < track->entry)
734
        mov_write_stss_tag(pb, track);
735
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
736
        track->hasBframes)
737
        mov_write_ctts_tag(pb, track);
738
    mov_write_stsc_tag(pb, track);
739
    mov_write_stsz_tag(pb, track);
740
    mov_write_stco_tag(pb, track);
741
    return updateSize(pb, pos);
742
}
743

    
744
static int mov_write_dinf_tag(ByteIOContext *pb)
745
{
746
    offset_t pos = url_ftell(pb);
747
    put_be32(pb, 0); /* size */
748
    put_tag(pb, "dinf");
749
    mov_write_dref_tag(pb);
750
    return updateSize(pb, pos);
751
}
752

    
753
static int mov_write_smhd_tag(ByteIOContext *pb)
754
{
755
    put_be32(pb, 16); /* size */
756
    put_tag(pb, "smhd");
757
    put_be32(pb, 0); /* version & flags */
758
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
759
    put_be16(pb, 0); /* reserved */
760
    return 16;
761
}
762

    
763
static int mov_write_vmhd_tag(ByteIOContext *pb)
764
{
765
    put_be32(pb, 0x14); /* size (always 0x14) */
766
    put_tag(pb, "vmhd");
767
    put_be32(pb, 0x01); /* version & flags */
768
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
769
    return 0x14;
770
}
771

    
772
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack* track)
773
{
774
    const char *descr, *hdlr, *hdlr_type;
775
    offset_t pos = url_ftell(pb);
776

    
777
    if (!track) { /* no media --> data handler */
778
        hdlr = "dhlr";
779
        hdlr_type = "url ";
780
        descr = "DataHandler";
781
    } else {
782
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
783
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
784
            hdlr_type = "vide";
785
            descr = "VideoHandler";
786
        } else {
787
            hdlr_type = "soun";
788
            descr = "SoundHandler";
789
        }
790
    }
791

    
792
    put_be32(pb, 0); /* size */
793
    put_tag(pb, "hdlr");
794
    put_be32(pb, 0); /* Version & flags */
795
    put_buffer(pb, hdlr, 4); /* handler */
796
    put_tag(pb, hdlr_type); /* handler type */
797
    put_be32(pb ,0); /* reserved */
798
    put_be32(pb ,0); /* reserved */
799
    put_be32(pb ,0); /* reserved */
800
    put_byte(pb, strlen(descr)); /* string counter */
801
    put_buffer(pb, descr, strlen(descr)); /* handler description */
802
    return updateSize(pb, pos);
803
}
804

    
805
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack* track)
806
{
807
    offset_t pos = url_ftell(pb);
808
    put_be32(pb, 0); /* size */
809
    put_tag(pb, "minf");
810
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
811
        mov_write_vmhd_tag(pb);
812
    else
813
        mov_write_smhd_tag(pb);
814
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
815
        mov_write_hdlr_tag(pb, NULL);
816
    mov_write_dinf_tag(pb);
817
    mov_write_stbl_tag(pb, track);
818
    return updateSize(pb, pos);
819
}
820

    
821
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack* track)
822
{
823
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
824

    
825
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
826
    put_tag(pb, "mdhd");
827
    put_byte(pb, version);
828
    put_be24(pb, 0); /* flags */
829
    if (version == 1) {
830
        put_be64(pb, track->time);
831
        put_be64(pb, track->time);
832
    } else {
833
        put_be32(pb, track->time); /* creation time */
834
        put_be32(pb, track->time); /* modification time */
835
    }
836
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
837
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
838
    put_be16(pb, track->language); /* language */
839
    put_be16(pb, 0); /* reserved (quality) */
840
    return 32;
841
}
842

    
843
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack* track)
844
{
845
    offset_t pos = url_ftell(pb);
846
    put_be32(pb, 0); /* size */
847
    put_tag(pb, "mdia");
848
    mov_write_mdhd_tag(pb, track);
849
    mov_write_hdlr_tag(pb, track);
850
    mov_write_minf_tag(pb, track);
851
    return updateSize(pb, pos);
852
}
853

    
854
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)
855
{
856
    int64_t duration = av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP);
857
    int version = duration < INT32_MAX ? 0 : 1;
858

    
859
    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
860
    put_tag(pb, "tkhd");
861
    put_byte(pb, version);
862
    put_be24(pb, 0xf); /* flags (track enabled) */
863
    if (version == 1) {
864
        put_be64(pb, track->time);
865
        put_be64(pb, track->time);
866
    } else {
867
        put_be32(pb, track->time); /* creation time */
868
        put_be32(pb, track->time); /* modification time */
869
    }
870
    put_be32(pb, track->trackID); /* track-id */
871
    put_be32(pb, 0); /* reserved */
872
    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
873

    
874
    put_be32(pb, 0); /* reserved */
875
    put_be32(pb, 0); /* reserved */
876
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
877
    /* Volume, only for audio */
878
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
879
        put_be16(pb, 0x0100);
880
    else
881
        put_be16(pb, 0);
882
    put_be16(pb, 0); /* reserved */
883

    
884
    /* Matrix structure */
885
    put_be32(pb, 0x00010000); /* reserved */
886
    put_be32(pb, 0x0); /* reserved */
887
    put_be32(pb, 0x0); /* reserved */
888
    put_be32(pb, 0x0); /* reserved */
889
    put_be32(pb, 0x00010000); /* reserved */
890
    put_be32(pb, 0x0); /* reserved */
891
    put_be32(pb, 0x0); /* reserved */
892
    put_be32(pb, 0x0); /* reserved */
893
    put_be32(pb, 0x40000000); /* reserved */
894

    
895
    /* Track width and height, for visual only */
896
    if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
897
        double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
898
        if( !sample_aspect_ratio ) sample_aspect_ratio = 1;
899
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
900
        put_be32(pb, track->enc->height*0x10000);
901
    }
902
    else {
903
        put_be32(pb, 0);
904
        put_be32(pb, 0);
905
    }
906
    return 0x5c;
907
}
908

    
909
// This box seems important for the psp playback ... without it the movie seems to hang
910
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
911
{
912
    put_be32(pb, 0x24); /* size  */
913
    put_tag(pb, "edts");
914
    put_be32(pb, 0x1c); /* size  */
915
    put_tag(pb, "elst");
916
    put_be32(pb, 0x0);
917
    put_be32(pb, 0x1);
918

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

    
921
    if (track->hasBframes)
922
        put_be32(pb, track->sampleDuration); /* first pts is 1 */
923
    else
924
        put_be32(pb, 0);
925
    put_be32(pb, 0x00010000);
926
    return 0x24;
927
}
928

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

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

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

    
978
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
979
{
980
    int maxTrackID = 1, i;
981
    int64_t maxTrackLenTemp, maxTrackLen = 0;
982
    int version;
983

    
984
    for (i=0; i<mov->nb_streams; i++) {
985
        if(mov->tracks[i].entry > 0) {
986
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
987
            if(maxTrackLen < maxTrackLenTemp)
988
                maxTrackLen = maxTrackLenTemp;
989
            if(maxTrackID < mov->tracks[i].trackID)
990
                maxTrackID = mov->tracks[i].trackID;
991
        }
992
    }
993

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

    
1009
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1010
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1011
    put_be16(pb, 0); /* reserved */
1012
    put_be32(pb, 0); /* reserved */
1013
    put_be32(pb, 0); /* reserved */
1014

    
1015
    /* Matrix structure */
1016
    put_be32(pb, 0x00010000); /* reserved */
1017
    put_be32(pb, 0x0); /* reserved */
1018
    put_be32(pb, 0x0); /* reserved */
1019
    put_be32(pb, 0x0); /* reserved */
1020
    put_be32(pb, 0x00010000); /* reserved */
1021
    put_be32(pb, 0x0); /* reserved */
1022
    put_be32(pb, 0x0); /* reserved */
1023
    put_be32(pb, 0x0); /* reserved */
1024
    put_be32(pb, 0x40000000); /* reserved */
1025

    
1026
    put_be32(pb, 0); /* reserved (preview time) */
1027
    put_be32(pb, 0); /* reserved (preview duration) */
1028
    put_be32(pb, 0); /* reserved (poster time) */
1029
    put_be32(pb, 0); /* reserved (selection time) */
1030
    put_be32(pb, 0); /* reserved (selection duration) */
1031
    put_be32(pb, 0); /* reserved (current time) */
1032
    put_be32(pb, maxTrackID+1); /* Next track id */
1033
    return 0x6c;
1034
}
1035

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

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

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

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

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

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

    
1140
/* iTunes meta data tag */
1141
static int mov_write_meta_tag(ByteIOContext *pb, MOVContext* mov,
1142
                              AVFormatContext *s)
1143
{
1144
    int size = 0;
1145

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

    
1160
static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1161
                              AVFormatContext *s)
1162
{
1163
    offset_t pos = url_ftell(pb);
1164
    int i;
1165

    
1166
    put_be32(pb, 0); /* size */
1167
    put_tag(pb, "udta");
1168

    
1169
    /* iTunes meta data */
1170
    mov_write_meta_tag(pb, mov, s);
1171

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

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

    
1193
    return updateSize(pb, pos);
1194
}
1195

    
1196

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

    
1211
static uint16_t language_code (const char *str)
1212
{
1213
    return ((((str[0]-0x60) & 0x1F)<<10) + (((str[1]-0x60) & 0x1F)<<5) + ((str[2]-0x60) & 0x1F));
1214
}
1215

    
1216
static int mov_write_uuidusmt_tag (ByteIOContext *pb, AVFormatContext *s)
1217
{
1218
    size_t len, size;
1219
    offset_t pos, curpos;
1220

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

    
1232
        put_be32(pb, 0); /* size placeholder*/
1233
        put_tag(pb, "MTDT");
1234
        put_be16(pb, 4);
1235
        size += 10;
1236

    
1237
        // ?
1238
        put_be16(pb, 0x0C);                 /* size */
1239
        put_be32(pb, 0x0B);                 /* type */
1240
        put_be16(pb, language_code("und")); /* language */
1241
        put_be16(pb, 0x0);                  /* ? */
1242
        put_be16(pb, 0x021C);               /* data */
1243
        size += 12;
1244

    
1245
        // Encoder
1246
        len = strlen(LIBAVCODEC_IDENT)+1;
1247
        put_be16(pb, len*2+10);             /* size */
1248
        put_be32(pb, 0x04);                 /* type */
1249
        put_be16(pb, language_code("eng")); /* language */
1250
        put_be16(pb, 0x01);                 /* ? */
1251
        ascii_to_wc(pb, LIBAVCODEC_IDENT, len);
1252
        size += len*2+10;
1253

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

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

    
1273
        // size
1274
        curpos = url_ftell(pb);
1275
        url_fseek(pb, pos, SEEK_SET);
1276
        put_be32(pb, size);
1277
        url_fseek(pb, pos+24, SEEK_SET);
1278
        put_be32(pb, size-24);
1279
        url_fseek(pb, curpos, SEEK_SET);
1280
    }
1281

    
1282
    return size;
1283
}
1284

    
1285
static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1286
                              AVFormatContext *s)
1287
{
1288
    int i;
1289
    offset_t pos = url_ftell(pb);
1290
    put_be32(pb, 0); /* size placeholder*/
1291
    put_tag(pb, "moov");
1292
    mov->timescale = globalTimescale;
1293

    
1294
    for (i=0; i<mov->nb_streams; i++) {
1295
        if(mov->tracks[i].entry <= 0) continue;
1296

    
1297
        if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {
1298
            mov->tracks[i].timescale = mov->tracks[i].enc->time_base.den;
1299
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->time_base.num;
1300
        } else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {
1301
            mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;
1302
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;
1303
        }
1304

    
1305
        mov->tracks[i].trackDuration =
1306
            (int64_t)mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;
1307
        mov->tracks[i].time = mov->time;
1308
        mov->tracks[i].trackID = i+1;
1309
    }
1310

    
1311
    mov_write_mvhd_tag(pb, mov);
1312
    //mov_write_iods_tag(pb, mov);
1313
    for (i=0; i<mov->nb_streams; i++) {
1314
        if(mov->tracks[i].entry > 0) {
1315
            mov_write_trak_tag(pb, &(mov->tracks[i]));
1316
        }
1317
    }
1318

    
1319
    if (mov->mode == MODE_PSP)
1320
        mov_write_uuidusmt_tag(pb, s);
1321
    else
1322
    mov_write_udta_tag(pb, mov, s);
1323

    
1324
    return updateSize(pb, pos);
1325
}
1326

    
1327
static int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1328
{
1329
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1330
    put_tag(pb, "wide");
1331

    
1332
    mov->mdat_pos = url_ftell(pb);
1333
    put_be32(pb, 0); /* size placeholder*/
1334
    put_tag(pb, "mdat");
1335
    return 0;
1336
}
1337

    
1338
/* TODO: This needs to be more general */
1339
static void mov_write_ftyp_tag (ByteIOContext *pb, AVFormatContext *s)
1340
{
1341
    MOVContext *mov = s->priv_data;
1342

    
1343
    put_be32(pb, 0x14 ); /* size */
1344
    put_tag(pb, "ftyp");
1345

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

    
1357
    put_be32(pb, 0x200 );
1358

    
1359
    if ( mov->mode == MODE_3GP )
1360
        put_tag(pb, "3gp4");
1361
    else if ( mov->mode == MODE_3G2 )
1362
        put_tag(pb, "3g2a");
1363
    else if ( mov->mode == MODE_PSP )
1364
        put_tag(pb, "MSNV");
1365
    else if ( mov->mode == MODE_MP4 )
1366
        put_tag(pb, "mp41");
1367
    else
1368
        put_tag(pb, "qt  ");
1369
}
1370

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

    
1380
    put_be32(pb, 0x94 ); /* size */
1381
    put_tag(pb, "uuid");
1382
    put_tag(pb, "PROF");
1383

    
1384
    put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1385
    put_be32(pb, 0xbb88695c );
1386
    put_be32(pb, 0xfac9c740 );
1387

    
1388
    put_be32(pb, 0x0 );  /* ? */
1389
    put_be32(pb, 0x3 );  /* 3 sections ? */
1390

    
1391
    put_be32(pb, 0x14 ); /* size */
1392
    put_tag(pb, "FPRF");
1393
    put_be32(pb, 0x0 );  /* ? */
1394
    put_be32(pb, 0x0 );  /* ? */
1395
    put_be32(pb, 0x0 );  /* ? */
1396

    
1397
    put_be32(pb, 0x2c );  /* size */
1398
    put_tag(pb, "APRF");   /* audio */
1399
    put_be32(pb, 0x0 );
1400
    put_be32(pb, 0x2 );   /* TrackID */
1401
    put_tag(pb, "mp4a");
1402
    put_be32(pb, 0x20f );
1403
    put_be32(pb, 0x0 );
1404
    put_be32(pb, audio_kbitrate);
1405
    put_be32(pb, audio_kbitrate);
1406
    put_be32(pb, AudioRate );
1407
    put_be32(pb, AudioCodec->channels );
1408

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

    
1432
static int mov_write_header(AVFormatContext *s)
1433
{
1434
    ByteIOContext *pb = &s->pb;
1435
    MOVContext *mov = s->priv_data;
1436
    int i;
1437

    
1438
    /* Default mode == MP4 */
1439
    mov->mode = MODE_MP4;
1440

    
1441
    if (s->oformat != NULL) {
1442
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1443
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3G2;
1444
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1445
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1446

    
1447
        mov_write_ftyp_tag(pb,s);
1448
        if ( mov->mode == MODE_PSP ) {
1449
            if ( s->nb_streams != 2 ) {
1450
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1451
                return -1;
1452
            }
1453
            mov_write_uuidprof_tag(pb,s);
1454
        }
1455
    }
1456

    
1457
    for(i=0; i<s->nb_streams; i++){
1458
        AVStream *st= s->streams[i];
1459
        MOVTrack *track= &mov->tracks[i];
1460

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

    
1474
    mov_write_mdat_tag(pb, mov);
1475
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1476
    mov->nb_streams = s->nb_streams;
1477

    
1478
    put_flush_packet(pb);
1479

    
1480
    return 0;
1481
}
1482

    
1483
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1484
{
1485
    MOVContext *mov = s->priv_data;
1486
    ByteIOContext *pb = &s->pb;
1487
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1488
    AVCodecContext *enc = trk->enc;
1489
    unsigned int samplesInChunk = 0;
1490
    int size= pkt->size;
1491

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

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

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

    
1514
    /* copy extradata if it exists */
1515
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1516
        trk->vosLen = enc->extradata_size;
1517
        trk->vosData = av_malloc(trk->vosLen);
1518
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1519
    }
1520

    
1521
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1522
        /* from x264 or from bytestream h264 */
1523
        /* nal reformating needed */
1524
        avc_parse_nal_units(&pkt->data, &pkt->size);
1525
        assert(pkt->size);
1526
        size = pkt->size;
1527
    }
1528

    
1529
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1530
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1531
        if (!trk->cluster)
1532
            return -1;
1533
    }
1534

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

    
1551
    put_buffer(pb, pkt->data, size);
1552

    
1553
    put_flush_packet(pb);
1554
    return 0;
1555
}
1556

    
1557
static int mov_write_trailer(AVFormatContext *s)
1558
{
1559
    MOVContext *mov = s->priv_data;
1560
    ByteIOContext *pb = &s->pb;
1561
    int res = 0;
1562
    int i;
1563

    
1564
    offset_t moov_pos = url_ftell(pb);
1565

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

    
1579
    mov_write_moov_tag(pb, mov, s);
1580

    
1581
    for (i=0; i<mov->nb_streams; i++) {
1582
        av_freep(&mov->tracks[i].cluster);
1583

    
1584
        if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1585

    
1586
    }
1587

    
1588
    put_flush_packet(pb);
1589

    
1590
    return res;
1591
}
1592

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