Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 5509bffa

History | View | Annotate | Download (46.6 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

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

    
27
#define MOV_INDEX_CLUSTER_SIZE 16384
28
#define globalTimescale 1000
29

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

    
37
typedef struct MOVIentry {
38
    unsigned int flags, pos, size;
39
    unsigned int samplesInChunk;
40
    char         key_frame;
41
    unsigned int entries;
42
} MOVIentry;
43

    
44
typedef struct MOVIndex {
45
    int         mode;
46
    int         entry;
47
    int         mdat_size;
48
    int         ents_allocated;
49
    long        timescale;
50
    long        time;
51
    long        trackDuration;
52
    long        sampleCount;
53
    long        sampleDuration;
54
    int         hasKeyframes;
55
    int         language;
56
    int         trackID;
57
    AVCodecContext *enc;
58

    
59
    int         vosLen;
60
    uint8_t     *vosData;
61
    MOVIentry** cluster;
62
} MOVTrack;
63

    
64
typedef struct MOVContext {
65
    int     mode;
66
    long    time;
67
    int     nb_streams;
68
    int     mdat_written;
69
    offset_t mdat_pos;
70
    long    timescale;
71
    MOVTrack tracks[MAX_STREAMS];
72
} MOVContext;
73

    
74
static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track);
75

    
76
/* output language code from iso639 language name */
77
extern int ff_mov_iso639_to_lang(const char *lang, int mp4);
78

    
79
const CodecTag ff_mov_obj_type[] = {
80
    { CODEC_ID_MPEG4     ,  32 },
81
    { CODEC_ID_AAC       ,  64 },
82
    { CODEC_ID_MPEG1VIDEO, 106 },
83
    { CODEC_ID_MPEG2VIDEO,  96 },//mpeg2 profiles
84
    { CODEC_ID_MP2       , 107 },//FIXME mpeg2 mpeg audio -> 105
85
    { CODEC_ID_MP3       , 107 },//FIXME mpeg2 mpeg audio -> 105
86
    { CODEC_ID_H264      ,  33 },
87
    { CODEC_ID_H263      , 242 },
88
    { CODEC_ID_H261      , 243 },
89
    { CODEC_ID_MJPEG     , 108 },
90
    { CODEC_ID_PCM_S16LE , 224 },
91
    { CODEC_ID_VORBIS    , 225 },
92
    { CODEC_ID_AC3       , 226 },
93
    { CODEC_ID_PCM_ALAW  , 227 },
94
    { CODEC_ID_PCM_MULAW , 228 },
95
    { CODEC_ID_PCM_S16BE , 230 },
96
    { 0,0  },
97
};
98

    
99
//FIXME supprt 64bit varaint with wide placeholders
100
static int updateSize (ByteIOContext *pb, int pos)
101
{
102
    long curpos = url_ftell(pb);
103
    url_fseek(pb, pos, SEEK_SET);
104
    put_be32(pb, curpos - pos); /* rewrite size */
105
    url_fseek(pb, curpos, SEEK_SET);
106

    
107
    return curpos - pos;
108
}
109

    
110
/* Chunk offset atom */
111
static int mov_write_stco_tag(ByteIOContext *pb, MOVTrack* track)
112
{
113
    int i;
114
    int pos = url_ftell(pb);
115
    put_be32(pb, 0); /* size */
116
    put_tag(pb, "stco");
117
    put_be32(pb, 0); /* version & flags */
118
    put_be32(pb, track->entry); /* entry count */
119
    for (i=0; i<track->entry; i++) {
120
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
121
        int id = i % MOV_INDEX_CLUSTER_SIZE;
122
        put_be32(pb, track->cluster[cl][id].pos);
123
    }
124
    return updateSize (pb, pos);
125
}
126

    
127
/* Sample size atom */
128
static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack* track)
129
{
130
    int equalChunks = 1;
131
    int i, j, entries = 0, tst = -1, oldtst = -1;
132

    
133
    int pos = url_ftell(pb);
134
    put_be32(pb, 0); /* size */
135
    put_tag(pb, "stsz");
136
    put_be32(pb, 0); /* version & flags */
137

    
138
    for (i=0; i<track->entry; i++) {
139
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
140
        int id = i % MOV_INDEX_CLUSTER_SIZE;
141
        tst = track->cluster[cl][id].size/track->cluster[cl][id].entries;
142
        if(oldtst != -1 && tst != oldtst) {
143
            equalChunks = 0;
144
        }
145
        oldtst = tst;
146
        entries += track->cluster[cl][id].entries;
147
    }
148
    if (equalChunks) {
149
        int sSize = track->cluster[0][0].size/track->cluster[0][0].entries;
150
        put_be32(pb, sSize); // sample size
151
        put_be32(pb, entries); // sample count
152
    }
153
    else {
154
        put_be32(pb, 0); // sample size
155
        put_be32(pb, entries); // sample count
156
        for (i=0; i<track->entry; i++) {
157
            int cl = i / MOV_INDEX_CLUSTER_SIZE;
158
            int id = i % MOV_INDEX_CLUSTER_SIZE;
159
            for ( j=0; j<track->cluster[cl][id].entries; j++) {
160
                put_be32(pb, track->cluster[cl][id].size /
161
                         track->cluster[cl][id].entries);
162
            }
163
        }
164
    }
165
    return updateSize (pb, pos);
166
}
167

    
168
/* Sample to chunk atom */
169
static int mov_write_stsc_tag(ByteIOContext *pb, MOVTrack* track)
170
{
171
    int index = 0, oldval = -1, i, entryPos, curpos;
172

    
173
    int pos = url_ftell(pb);
174
    put_be32(pb, 0); /* size */
175
    put_tag(pb, "stsc");
176
    put_be32(pb, 0); // version & flags
177
    entryPos = url_ftell(pb);
178
    put_be32(pb, track->entry); // entry count
179
    for (i=0; i<track->entry; i++) {
180
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
181
        int id = i % MOV_INDEX_CLUSTER_SIZE;
182
        if(oldval != track->cluster[cl][id].samplesInChunk)
183
        {
184
            put_be32(pb, i+1); // first chunk
185
            put_be32(pb, track->cluster[cl][id].samplesInChunk); // samples per chunk
186
            put_be32(pb, 0x1); // sample description index
187
            oldval = track->cluster[cl][id].samplesInChunk;
188
            index++;
189
        }
190
    }
191
    curpos = url_ftell(pb);
192
    url_fseek(pb, entryPos, SEEK_SET);
193
    put_be32(pb, index); // rewrite size
194
    url_fseek(pb, curpos, SEEK_SET);
195

    
196
    return updateSize (pb, pos);
197
}
198

    
199
/* Sync sample atom */
200
static int mov_write_stss_tag(ByteIOContext *pb, MOVTrack* track)
201
{
202
    long curpos;
203
    int i, index = 0, entryPos;
204
    int pos = url_ftell(pb);
205
    put_be32(pb, 0); // size
206
    put_tag(pb, "stss");
207
    put_be32(pb, 0); // version & flags
208
    entryPos = url_ftell(pb);
209
    put_be32(pb, track->entry); // entry count
210
    for (i=0; i<track->entry; i++) {
211
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
212
        int id = i % MOV_INDEX_CLUSTER_SIZE;
213
        if(track->cluster[cl][id].key_frame == 1) {
214
            put_be32(pb, i+1);
215
            index++;
216
        }
217
    }
218
    curpos = url_ftell(pb);
219
    url_fseek(pb, entryPos, SEEK_SET);
220
    put_be32(pb, index); // rewrite size
221
    url_fseek(pb, curpos, SEEK_SET);
222
    return updateSize (pb, pos);
223
}
224

    
225
static int mov_write_damr_tag(ByteIOContext *pb)
226
{
227
    put_be32(pb, 0x11); /* size */
228
    put_tag(pb, "damr");
229
    put_tag(pb, "FFMP");
230
    put_byte(pb, 0);
231

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

    
239
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack* track)
240
{
241
    int pos = url_ftell(pb);
242

    
243
    put_be32(pb, 0);     /* size */
244
    put_tag(pb, "wave");
245

    
246
    put_be32(pb, 12);    /* size */
247
    put_tag(pb, "frma");
248
    put_tag(pb, "mp4a");
249

    
250
    put_be32(pb, 12);    /* size */
251
    put_tag(pb, "mp4a");
252
    put_be32(pb, 0);
253

    
254
    mov_write_esds_tag(pb, track);
255

    
256
    put_be32(pb, 12);    /* size */
257
    put_tag(pb, "srcq");
258
    put_be32(pb, 0x40);
259

    
260
    put_be32(pb, 8);     /* size */
261
    put_be32(pb, 0);     /* null tag */
262

    
263
    return updateSize (pb, pos);
264
}
265

    
266
static const CodecTag codec_movaudio_tags[] = {
267
    { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') },
268
    { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') },
269
    { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') },
270
    { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') },
271
    { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') },
272
    { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
273
    { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') },
274
    { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') },
275
    { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') },
276
    { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') },
277
    { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') },
278
    { 0, 0 },
279
};
280

    
281
static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack* track)
282
{
283
    int pos = url_ftell(pb);
284
    int tag;
285

    
286
    put_be32(pb, 0); /* size */
287

    
288
    tag = track->enc->codec_tag;
289
    if (!tag)
290
    tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
291
    // if no mac fcc found, try with Microsoft tags
292
    if (!tag)
293
    {
294
        int tmp = codec_get_tag(codec_wav_tags, track->enc->codec_id);
295
        tag = MKTAG('m', 's', ((tmp >> 8) & 0xff), (tmp & 0xff));
296
    }
297
    put_le32(pb, tag); // store it byteswapped
298

    
299
    put_be32(pb, 0); /* Reserved */
300
    put_be16(pb, 0); /* Reserved */
301
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
302

    
303
    /* SoundDescription */
304
    if(track->mode == MODE_MOV && track->enc->codec_id == CODEC_ID_AAC)
305
        put_be16(pb, 1); /* Version 1 */
306
    else
307
        put_be16(pb, 0); /* Version 0 */
308
    put_be16(pb, 0); /* Revision level */
309
    put_be32(pb, 0); /* Reserved */
310

    
311
    put_be16(pb, track->enc->channels); /* Number of channels */
312
    /* TODO: Currently hard-coded to 16-bit, there doesn't seem
313
                 to be a good way to get number of bits of audio */
314
    put_be16(pb, 0x10); /* Reserved */
315

    
316
    if(track->enc->codec_id == CODEC_ID_AAC ||
317
       track->enc->codec_id == CODEC_ID_MP3)
318
    {
319
        put_be16(pb, 0xfffe); /* compression ID (vbr)*/
320
    }
321
    else
322
    {
323
        put_be16(pb, 0); /* compression ID (= 0) */
324
    }
325
    put_be16(pb, 0); /* packet size (= 0) */
326
    put_be16(pb, track->timescale); /* Time scale */
327
    put_be16(pb, 0); /* Reserved */
328

    
329
    if(track->mode == MODE_MOV && track->enc->codec_id == CODEC_ID_AAC)
330
    {
331
        /* SoundDescription V1 extended info */
332
        put_be32(pb, track->enc->frame_size); /* Samples per packet  */
333
        put_be32(pb, 1536); /* Bytes per packet */
334
        put_be32(pb, 2); /* Bytes per frame */
335
        put_be32(pb, 2); /* Bytes per sample */
336
    }
337

    
338
    if(track->enc->codec_id == CODEC_ID_AAC) {
339
        if( track->mode == MODE_MOV ) mov_write_wave_tag(pb, track);
340
        else mov_write_esds_tag(pb, track);
341
    }
342
    if(track->enc->codec_id == CODEC_ID_AMR_NB)
343
        mov_write_damr_tag(pb);
344
    return updateSize (pb, pos);
345
}
346

    
347
static int mov_write_d263_tag(ByteIOContext *pb)
348
{
349
    put_be32(pb, 0xf); /* size */
350
    put_tag(pb, "d263");
351
    put_tag(pb, "FFMP");
352
    put_be16(pb, 0x0a);
353
    put_byte(pb, 0);
354
    return 0xf;
355
}
356

    
357
/* TODO: No idea about these values */
358
static int mov_write_svq3_tag(ByteIOContext *pb)
359
{
360
    put_be32(pb, 0x15);
361
    put_tag(pb, "SMI ");
362
    put_tag(pb, "SEQH");
363
    put_be32(pb, 0x5);
364
    put_be32(pb, 0xe2c0211d);
365
    put_be32(pb, 0xc0000000);
366
    put_byte(pb, 0);
367
    return 0x15;
368
}
369

    
370
static unsigned int descrLength(unsigned int len)
371
{
372
    if (len < 0x00000080)
373
        return 2 + len;
374
    else if (len < 0x00004000)
375
        return 3 + len;
376
    else if(len < 0x00200000)
377
        return 4 + len;
378
    else
379
        return 5 + len;
380
}
381

    
382
static void putDescr(ByteIOContext *pb, int tag, int size)
383
{
384
    uint32_t len;
385
    uint8_t  vals[4];
386

    
387
    len = size;
388
    vals[3] = (uint8_t)(len & 0x7f);
389
    len >>= 7;
390
    vals[2] = (uint8_t)((len & 0x7f) | 0x80);
391
    len >>= 7;
392
    vals[1] = (uint8_t)((len & 0x7f) | 0x80);
393
    len >>= 7;
394
    vals[0] = (uint8_t)((len & 0x7f) | 0x80);
395

    
396
    put_byte(pb, tag); // DescriptorTag
397

    
398
    if (size < 0x00000080)
399
    {
400
        put_byte(pb, vals[3]);
401
    }
402
    else if (size < 0x00004000)
403
    {
404
        put_byte(pb, vals[2]);
405
        put_byte(pb, vals[3]);
406
    }
407
    else if (size < 0x00200000)
408
    {
409
        put_byte(pb, vals[1]);
410
        put_byte(pb, vals[2]);
411
        put_byte(pb, vals[3]);
412
    }
413
    else if (size < 0x10000000)
414
    {
415
        put_byte(pb, vals[0]);
416
        put_byte(pb, vals[1]);
417
        put_byte(pb, vals[2]);
418
        put_byte(pb, vals[3]);
419
    }
420
}
421

    
422
static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track) // Basic
423
{
424
    int decoderSpecificInfoLen;
425
    int pos = url_ftell(pb);
426
    void *vosDataBackup=track->vosData;
427
    int vosLenBackup=track->vosLen;
428

    
429
    // we should be able to have these passed in, via vosData, then we wouldn't need to attack this routine at all
430
    static const char PSPAACData[]={0x13,0x10};
431
    static const char PSPMP4Data[]={0x00,0x00,0x01,0xB0,0x03,0x00,0x00,0x01,0xB5,0x09,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x20,0x00,0x84,0x5D,0x4C,0x28,0x50,0x20,0xF0,0xA3,0x1F };
432

    
433

    
434
    if (track->mode == MODE_PSP)  // fails on psp if this is not here
435
    {
436
        if (track->enc->codec_id == CODEC_ID_AAC)
437
        {
438
            track->vosLen = 2;
439
            track->vosData = (uint8_t *) PSPAACData;
440
        }
441

    
442
        if (track->enc->codec_id == CODEC_ID_MPEG4)
443
        {
444
            track->vosLen = 28;
445
            track->vosData = (uint8_t *) PSPMP4Data;
446
        }
447
    }
448

    
449
    decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
450

    
451
    put_be32(pb, 0);               // size
452
    put_tag(pb, "esds");
453
    put_be32(pb, 0);               // Version
454

    
455
    // ES descriptor
456
    putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
457
             descrLength(1));
458
    put_be16(pb, track->trackID);
459
    put_byte(pb, 0x00);            // flags (= no flags)
460

    
461
    // DecoderConfig descriptor
462
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
463

    
464
    // Object type indication
465
    put_byte(pb, codec_get_tag(ff_mov_obj_type, track->enc->codec_id));
466

    
467
    // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
468
    // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
469
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
470
        put_byte(pb, 0x15);            // flags (= Audiostream)
471
    else
472
        put_byte(pb, 0x11);            // flags (= Visualstream)
473

    
474
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));             // Buffersize DB (24 bits)
475
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF);          // Buffersize DB
476

    
477
    put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate));     // maxbitrate  (FIXME should be max rate in any 1 sec window)
478
    if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
479
        put_be32(pb, 0);     // vbr
480
    else
481
        put_be32(pb, track->enc->rc_max_rate);     // avg bitrate
482

    
483
    if (track->vosLen)
484
    {
485
        // DecoderSpecific info descriptor
486
        putDescr(pb, 0x05, track->vosLen);
487
        put_buffer(pb, track->vosData, track->vosLen);
488
    }
489

    
490
    track->vosData = vosDataBackup;
491
    track->vosLen = vosLenBackup;
492

    
493
    // SL descriptor
494
    putDescr(pb, 0x06, 1);
495
    put_byte(pb, 0x02);
496
    return updateSize (pb, pos);
497
}
498

    
499
static const CodecTag codec_movvideo_tags[] = {
500
    { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') },
501
    { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') },
502
    { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
503
    { CODEC_ID_H263, MKTAG('s', '2', '6', '3') },
504
    { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
505
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') },
506
    { 0, 0 },
507
};
508

    
509
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
510
{
511
    int pos = url_ftell(pb);
512
    char compressor_name[32];
513
    int tag;
514

    
515
    put_be32(pb, 0); /* size */
516

    
517
    tag = track->enc->codec_tag;
518
    if (!tag)
519
    tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
520
    // if no mac fcc found, try with Microsoft tags
521
    if (!tag)
522
        tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
523
    put_le32(pb, tag); // store it byteswapped
524

    
525
    put_be32(pb, 0); /* Reserved */
526
    put_be16(pb, 0); /* Reserved */
527
    put_be16(pb, 1); /* Data-reference index */
528

    
529
    put_be16(pb, 0); /* Codec stream version */
530
    put_be16(pb, 0); /* Codec stream revision (=0) */
531
    put_tag(pb, "FFMP"); /* Vendor */
532
    if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
533
        put_be32(pb, 0); /* Temporal Quality */
534
        put_be32(pb, 0x400); /* Spatial Quality = lossless*/
535
    } else {
536
        put_be32(pb, 0x200); /* Temporal Quality = normal */
537
        put_be32(pb, 0x200); /* Spatial Quality = normal */
538
    }
539
    put_be16(pb, track->enc->width); /* Video width */
540
    put_be16(pb, track->enc->height); /* Video height */
541
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
542
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
543
    put_be32(pb, 0); /* Data size (= 0) */
544
    put_be16(pb, 1); /* Frame count (= 1) */
545

    
546
    memset(compressor_name,0,32);
547
    if (track->enc->codec && track->enc->codec->name)
548
        strncpy(compressor_name,track->enc->codec->name,31);
549
    put_byte(pb, strlen(compressor_name));
550
    put_buffer(pb, compressor_name, 31);
551

    
552
    put_be16(pb, 0x18); /* Reserved */
553
    put_be16(pb, 0xffff); /* Reserved */
554
    if(track->enc->codec_id == CODEC_ID_MPEG4)
555
        mov_write_esds_tag(pb, track);
556
    else if(track->enc->codec_id == CODEC_ID_H263)
557
        mov_write_d263_tag(pb);
558
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
559
        mov_write_svq3_tag(pb);
560

    
561
    return updateSize (pb, pos);
562
}
563

    
564
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack* track)
565
{
566
    int pos = url_ftell(pb);
567
    put_be32(pb, 0); /* size */
568
    put_tag(pb, "stsd");
569
    put_be32(pb, 0); /* version & flags */
570
    put_be32(pb, 1); /* entry count */
571
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
572
        mov_write_video_tag(pb, track);
573
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
574
        mov_write_audio_tag(pb, track);
575
    return updateSize(pb, pos);
576
}
577

    
578
/* TODO: */
579
/* Time to sample atom */
580
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack* track)
581
{
582
    put_be32(pb, 0x18); /* size */
583
    put_tag(pb, "stts");
584
    put_be32(pb, 0); /* version & flags */
585
    put_be32(pb, 1); /* entry count */
586

    
587
    put_be32(pb, track->sampleCount); /* sample count */
588
    put_be32(pb, track->sampleDuration); /* sample duration */
589
    return 0x18;
590
}
591

    
592
static int mov_write_dref_tag(ByteIOContext *pb)
593
{
594
    put_be32(pb, 28); /* size */
595
    put_tag(pb, "dref");
596
    put_be32(pb, 0); /* version & flags */
597
    put_be32(pb, 1); /* entry count */
598

    
599
    put_be32(pb, 0xc); /* size */
600
    put_tag(pb, "url ");
601
    put_be32(pb, 1); /* version & flags */
602

    
603
    return 28;
604
}
605

    
606
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track)
607
{
608
    int pos = url_ftell(pb);
609
    put_be32(pb, 0); /* size */
610
    put_tag(pb, "stbl");
611
    mov_write_stsd_tag(pb, track);
612
    mov_write_stts_tag(pb, track);
613
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
614
        track->hasKeyframes)
615
        mov_write_stss_tag(pb, track);
616
    mov_write_stsc_tag(pb, track);
617
    mov_write_stsz_tag(pb, track);
618
    mov_write_stco_tag(pb, track);
619
    return updateSize(pb, pos);
620
}
621

    
622
static int mov_write_dinf_tag(ByteIOContext *pb)
623
{
624
    int pos = url_ftell(pb);
625
    put_be32(pb, 0); /* size */
626
    put_tag(pb, "dinf");
627
    mov_write_dref_tag(pb);
628
    return updateSize(pb, pos);
629
}
630

    
631
static int mov_write_smhd_tag(ByteIOContext *pb)
632
{
633
    put_be32(pb, 16); /* size */
634
    put_tag(pb, "smhd");
635
    put_be32(pb, 0); /* version & flags */
636
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
637
    put_be16(pb, 0); /* reserved */
638
    return 16;
639
}
640

    
641
static int mov_write_vmhd_tag(ByteIOContext *pb)
642
{
643
    put_be32(pb, 0x14); /* size (always 0x14) */
644
    put_tag(pb, "vmhd");
645
    put_be32(pb, 0x01); /* version & flags */
646
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
647
    return 0x14;
648
}
649

    
650
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack* track)
651
{
652
    char *descr, *hdlr, *hdlr_type;
653
    int pos = url_ftell(pb);
654

    
655
    if (!track) { /* no media --> data handler */
656
        hdlr = "dhlr";
657
        hdlr_type = "url ";
658
        descr = "DataHandler";
659
    } else {
660
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
661
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
662
            hdlr_type = "vide";
663
            descr = "VideoHandler";
664
        } else {
665
            hdlr_type = "soun";
666
            descr = "SoundHandler";
667
        }
668
    }
669

    
670
    put_be32(pb, 0); /* size */
671
    put_tag(pb, "hdlr");
672
    put_be32(pb, 0); /* Version & flags */
673
    put_buffer(pb, hdlr, 4); /* handler */
674
    put_tag(pb, hdlr_type); /* handler type */
675
    put_be32(pb ,0); /* reserved */
676
    put_be32(pb ,0); /* reserved */
677
    put_be32(pb ,0); /* reserved */
678
    put_byte(pb, strlen(descr)); /* string counter */
679
    put_buffer(pb, descr, strlen(descr)); /* handler description */
680
    return updateSize(pb, pos);
681
}
682

    
683
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack* track)
684
{
685
    int pos = url_ftell(pb);
686
    put_be32(pb, 0); /* size */
687
    put_tag(pb, "minf");
688
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
689
        mov_write_vmhd_tag(pb);
690
    else
691
        mov_write_smhd_tag(pb);
692
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
693
        mov_write_hdlr_tag(pb, NULL);
694
    mov_write_dinf_tag(pb);
695
    mov_write_stbl_tag(pb, track);
696
    return updateSize(pb, pos);
697
}
698

    
699
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack* track)
700
{
701
    put_be32(pb, 32); /* size */
702
    put_tag(pb, "mdhd");
703
    put_be32(pb, 0); /* Version & flags */
704
    put_be32(pb, track->time); /* creation time */
705
    put_be32(pb, track->time); /* modification time */
706
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
707
    put_be32(pb, track->trackDuration); /* duration */
708
    put_be16(pb, track->language); /* language */
709
    put_be16(pb, 0); /* reserved (quality) */
710
    return 32;
711
}
712

    
713
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack* track)
714
{
715
    int pos = url_ftell(pb);
716
    put_be32(pb, 0); /* size */
717
    put_tag(pb, "mdia");
718
    mov_write_mdhd_tag(pb, track);
719
    mov_write_hdlr_tag(pb, track);
720
    mov_write_minf_tag(pb, track);
721
    return updateSize(pb, pos);
722
}
723

    
724
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)
725
{
726
    put_be32(pb, 0x5c); /* size (always 0x5c) */
727
    put_tag(pb, "tkhd");
728
    put_be32(pb, 0xf); /* version & flags (track enabled) */
729
    put_be32(pb, track->time); /* creation time */
730
    put_be32(pb, track->time); /* modification time */
731
    put_be32(pb, track->trackID); /* track-id */
732
    put_be32(pb, 0); /* reserved */
733
    put_be32(pb, av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP)); /* duration */
734

    
735
    put_be32(pb, 0); /* reserved */
736
    put_be32(pb, 0); /* reserved */
737
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
738
    /* Volume, only for audio */
739
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
740
        put_be16(pb, 0x0100);
741
    else
742
        put_be16(pb, 0);
743
    put_be16(pb, 0); /* reserved */
744

    
745
    /* Matrix structure */
746
    put_be32(pb, 0x00010000); /* reserved */
747
    put_be32(pb, 0x0); /* reserved */
748
    put_be32(pb, 0x0); /* reserved */
749
    put_be32(pb, 0x0); /* reserved */
750
    put_be32(pb, 0x00010000); /* reserved */
751
    put_be32(pb, 0x0); /* reserved */
752
    put_be32(pb, 0x0); /* reserved */
753
    put_be32(pb, 0x0); /* reserved */
754
    put_be32(pb, 0x40000000); /* reserved */
755

    
756
    /* Track width and height, for visual only */
757
    if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
758
        double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
759
        if( !sample_aspect_ratio ) sample_aspect_ratio = 1;
760
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
761
        put_be32(pb, track->enc->height*0x10000);
762
    }
763
    else {
764
        put_be32(pb, 0);
765
        put_be32(pb, 0);
766
    }
767
    return 0x5c;
768
}
769

    
770
// This box seems important for the psp playback ... without it the movie seems to hang
771
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
772
{
773
    put_be32(pb, 0x24); /* size  */
774
    put_tag(pb, "edts");
775
    put_be32(pb, 0x1c); /* size  */
776
    put_tag(pb, "elst");
777
    put_be32(pb, 0x0);
778
    put_be32(pb, 0x1);
779

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

    
782
    put_be32(pb, 0x0);
783
    put_be32(pb, 0x00010000);
784
    return 0x24;
785
}
786

    
787
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
788
static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
789
{
790
    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
791
    put_tag(pb, "uuid");
792
    put_tag(pb, "USMT");
793
    put_be32(pb, 0x21d24fce);
794
    put_be32(pb, 0xbb88695c);
795
    put_be32(pb, 0xfac9c740);
796
    put_be32(pb, 0x1c);     // another size here!
797
    put_tag(pb, "MTDT");
798
    put_be32(pb, 0x00010012);
799
    put_be32(pb, 0x0a);
800
    put_be32(pb, 0x55c40000);
801
    put_be32(pb, 0x1);
802
    put_be32(pb, 0x0);
803
    return 0x34;
804
}
805

    
806
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack* track)
807
{
808
    int pos = url_ftell(pb);
809
    put_be32(pb, 0); /* size */
810
    put_tag(pb, "trak");
811
    mov_write_tkhd_tag(pb, track);
812
    if (track->mode == MODE_PSP)
813
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
814
    mov_write_mdia_tag(pb, track);
815
    if (track->mode == MODE_PSP)
816
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
817
    return updateSize(pb, pos);
818
}
819

    
820
#if 0
821
/* TODO: Not sorted out, but not necessary either */
822
static int mov_write_iods_tag(ByteIOContext *pb, MOVContext *mov)
823
{
824
    put_be32(pb, 0x15); /* size */
825
    put_tag(pb, "iods");
826
    put_be32(pb, 0);    /* version & flags */
827
    put_be16(pb, 0x1007);
828
    put_byte(pb, 0);
829
    put_be16(pb, 0x4fff);
830
    put_be16(pb, 0xfffe);
831
    put_be16(pb, 0x01ff);
832
    return 0x15;
833
}
834
#endif
835

    
836
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
837
{
838
    int maxTrackID = 1, maxTrackLen = 0, i;
839
    int64_t maxTrackLenTemp;
840

    
841
    put_be32(pb, 0x6c); /* size (always 0x6c) */
842
    put_tag(pb, "mvhd");
843
    put_be32(pb, 0); /* version & flags */
844
    put_be32(pb, mov->time); /* creation time */
845
    put_be32(pb, mov->time); /* modification time */
846
    put_be32(pb, mov->timescale); /* timescale */
847
    for (i=0; i<MAX_STREAMS; i++) {
848
        if(mov->tracks[i].entry > 0) {
849
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
850
            if(maxTrackLen < maxTrackLenTemp)
851
                maxTrackLen = maxTrackLenTemp;
852
            if(maxTrackID < mov->tracks[i].trackID)
853
                maxTrackID = mov->tracks[i].trackID;
854
        }
855
    }
856
    put_be32(pb, maxTrackLen); /* duration of longest track */
857

    
858
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
859
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
860
    put_be16(pb, 0); /* reserved */
861
    put_be32(pb, 0); /* reserved */
862
    put_be32(pb, 0); /* reserved */
863

    
864
    /* Matrix structure */
865
    put_be32(pb, 0x00010000); /* reserved */
866
    put_be32(pb, 0x0); /* reserved */
867
    put_be32(pb, 0x0); /* reserved */
868
    put_be32(pb, 0x0); /* reserved */
869
    put_be32(pb, 0x00010000); /* reserved */
870
    put_be32(pb, 0x0); /* reserved */
871
    put_be32(pb, 0x0); /* reserved */
872
    put_be32(pb, 0x0); /* reserved */
873
    put_be32(pb, 0x40000000); /* reserved */
874

    
875
    put_be32(pb, 0); /* reserved (preview time) */
876
    put_be32(pb, 0); /* reserved (preview duration) */
877
    put_be32(pb, 0); /* reserved (poster time) */
878
    put_be32(pb, 0); /* reserved (selection time) */
879
    put_be32(pb, 0); /* reserved (selection duration) */
880
    put_be32(pb, 0); /* reserved (current time) */
881
    put_be32(pb, maxTrackID+1); /* Next track id */
882
    return 0x6c;
883
}
884

    
885
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVContext* mov,
886
                                     AVFormatContext *s)
887
{
888
    int pos = url_ftell(pb);
889
    put_be32(pb, 0); /* size */
890
    put_tag(pb, "hdlr");
891
    put_be32(pb, 0);
892
    put_be32(pb, 0);
893
    put_tag(pb, "mdir");
894
    put_tag(pb, "appl");
895
    put_be32(pb, 0);
896
    put_be32(pb, 0);
897
    put_be16(pb, 0);
898
    return updateSize(pb, pos);
899
}
900

    
901
/* helper function to write a data tag with the specified string as data */
902
static int mov_write_string_data_tag(ByteIOContext *pb, MOVContext* mov,
903
                                     AVFormatContext *s, const char *data)
904
{
905
    int pos = url_ftell(pb);
906
    put_be32(pb, 0); /* size */
907
    put_tag(pb, "data");
908
    put_be32(pb, 1);
909
    put_be32(pb, 0);
910
    put_buffer(pb, data, strlen(data));
911
    return updateSize(pb, pos);
912
}
913

    
914
/* iTunes name of the song/movie */
915
static int mov_write_nam_tag(ByteIOContext *pb, MOVContext* mov,
916
                             AVFormatContext *s)
917
{
918
    int size = 0;
919
    if ( s->title[0] ) {
920
        int pos = url_ftell(pb);
921
        put_be32(pb, 0); /* size */
922
        put_tag(pb, "\251nam");
923
        mov_write_string_data_tag(pb, mov, s, s->title);
924
        size = updateSize(pb, pos);
925
    }
926
    return size;
927
}
928

    
929
/* iTunes name of the artist/performer */
930
static int mov_write_ART_tag(ByteIOContext *pb, MOVContext* mov,
931
                             AVFormatContext *s)
932
{
933
    int size = 0;
934
    if ( s->author[0] ) {
935
        int pos = url_ftell(pb);
936
        put_be32(pb, 0); /* size */
937
        put_tag(pb, "\251ART");
938
        // we use the author here as this is the only thing that we have...
939
        mov_write_string_data_tag(pb, mov, s, s->author);
940
        size = updateSize(pb, pos);
941
    }
942
    return size;
943
}
944

    
945
/* iTunes name of the writer */
946
static int mov_write_wrt_tag(ByteIOContext *pb, MOVContext* mov,
947
                             AVFormatContext *s)
948
{
949
    int size = 0;
950
    if ( s->author[0] ) {
951
        int pos = url_ftell(pb);
952
        put_be32(pb, 0); /* size */
953
        put_tag(pb, "\251wrt");
954
        mov_write_string_data_tag(pb, mov, s, s->author);
955
        size = updateSize(pb, pos);
956
    }
957
    return size;
958
}
959

    
960
/* iTunes name of the album */
961
static int mov_write_alb_tag(ByteIOContext *pb, MOVContext* mov,
962
                             AVFormatContext *s)
963
{
964
    int size = 0;
965
    if ( s->album[0] ) {
966
        int pos = url_ftell(pb);
967
        put_be32(pb, 0); /* size */
968
        put_tag(pb, "\251alb");
969
        mov_write_string_data_tag(pb, mov, s, s->album);
970
        size = updateSize(pb, pos);
971
    }
972
    return size;
973
}
974

    
975
/* iTunes year */
976
static int mov_write_day_tag(ByteIOContext *pb, MOVContext* mov,
977
                             AVFormatContext *s)
978
{
979
    char year[5];
980
    int size = 0;
981
    if ( s->year ) {
982
        int pos = url_ftell(pb);
983
        put_be32(pb, 0); /* size */
984
        put_tag(pb, "\251day");
985
        snprintf(year, 5, "%04d", s->year);
986
        mov_write_string_data_tag(pb, mov, s, year);
987
        size = updateSize(pb, pos);
988
    }
989
    return size;
990
}
991

    
992
/* iTunes tool used to create the file */
993
static int mov_write_too_tag(ByteIOContext *pb, MOVContext* mov,
994
                             AVFormatContext *s)
995
{
996
    int pos = url_ftell(pb);
997
    put_be32(pb, 0); /* size */
998
    put_tag(pb, "\251too");
999
    mov_write_string_data_tag(pb, mov, s, LIBAVFORMAT_IDENT);
1000
    return updateSize(pb, pos);
1001
}
1002

    
1003
/* iTunes comment */
1004
static int mov_write_cmt_tag(ByteIOContext *pb, MOVContext* mov,
1005
                             AVFormatContext *s)
1006
{
1007
    int size = 0;
1008
    if ( s->comment[0] ) {
1009
        int pos = url_ftell(pb);
1010
        put_be32(pb, 0); /* size */
1011
        put_tag(pb, "\251cmt");
1012
        mov_write_string_data_tag(pb, mov, s, s->comment);
1013
        size = updateSize(pb, pos);
1014
    }
1015
    return size;
1016
}
1017

    
1018
/* iTunes custom genre */
1019
static int mov_write_gen_tag(ByteIOContext *pb, MOVContext* mov,
1020
                             AVFormatContext *s)
1021
{
1022
    int size = 0;
1023
    if ( s->genre[0] ) {
1024
        int pos = url_ftell(pb);
1025
        put_be32(pb, 0); /* size */
1026
        put_tag(pb, "\251gen");
1027
        mov_write_string_data_tag(pb, mov, s, s->genre);
1028
        size = updateSize(pb, pos);
1029
    }
1030
    return size;
1031
}
1032

    
1033
/* iTunes track number */
1034
static int mov_write_trkn_tag(ByteIOContext *pb, MOVContext* mov,
1035
                              AVFormatContext *s)
1036
{
1037
    int size = 0;
1038
    if ( s->track ) {
1039
        int pos = url_ftell(pb);
1040
        put_be32(pb, 0); /* size */
1041
        put_tag(pb, "trkn");
1042
        {
1043
            int pos = url_ftell(pb);
1044
            put_be32(pb, 0); /* size */
1045
            put_tag(pb, "data");
1046
            put_be32(pb, 0);        // 8 bytes empty
1047
            put_be32(pb, 0);
1048
            put_be16(pb, 0);        // empty
1049
            put_be16(pb, s->track); // track number
1050
            put_be16(pb, 0);        // total track number
1051
            put_be16(pb, 0);        // empty
1052
            updateSize(pb, pos);
1053
        }
1054
        size = updateSize(pb, pos);
1055
    }
1056
    return size;
1057
}
1058

    
1059
/* iTunes meta data list */
1060
static int mov_write_ilst_tag(ByteIOContext *pb, MOVContext* mov,
1061
                              AVFormatContext *s)
1062
{
1063
    int pos = url_ftell(pb);
1064
    put_be32(pb, 0); /* size */
1065
    put_tag(pb, "ilst");
1066
    mov_write_nam_tag(pb, mov, s);
1067
    mov_write_ART_tag(pb, mov, s);
1068
    mov_write_wrt_tag(pb, mov, s);
1069
    mov_write_alb_tag(pb, mov, s);
1070
    mov_write_day_tag(pb, mov, s);
1071
    mov_write_too_tag(pb, mov, s);
1072
    mov_write_cmt_tag(pb, mov, s);
1073
    mov_write_gen_tag(pb, mov, s);
1074
    mov_write_trkn_tag(pb, mov, s);
1075
    return updateSize(pb, pos);
1076
}
1077

    
1078
/* iTunes meta data tag */
1079
static int mov_write_meta_tag(ByteIOContext *pb, MOVContext* mov,
1080
                              AVFormatContext *s)
1081
{
1082
    int size = 0;
1083

    
1084
    // only save meta tag if required
1085
    if ( s->title[0] || s->author[0] || s->album[0] || s->year ||
1086
         s->comment[0] || s->genre[0] || s->track ) {
1087
        int pos = url_ftell(pb);
1088
        put_be32(pb, 0); /* size */
1089
        put_tag(pb, "meta");
1090
        put_be32(pb, 0);
1091
        mov_write_itunes_hdlr_tag(pb, mov, s);
1092
        mov_write_ilst_tag(pb, mov, s);
1093
        size = updateSize(pb, pos);
1094
    }
1095
    return size;
1096
}
1097

    
1098
static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1099
                              AVFormatContext *s)
1100
{
1101
    int pos = url_ftell(pb);
1102
    int i;
1103

    
1104
    put_be32(pb, 0); /* size */
1105
    put_tag(pb, "udta");
1106

    
1107
    /* iTunes meta data */
1108
    mov_write_meta_tag(pb, mov, s);
1109

    
1110
    /* Requirements */
1111
    for (i=0; i<MAX_STREAMS; i++) {
1112
        if(mov->tracks[i].entry <= 0) continue;
1113
        if (mov->tracks[i].enc->codec_id == CODEC_ID_AAC ||
1114
            mov->tracks[i].enc->codec_id == CODEC_ID_MPEG4) {
1115
            int pos = url_ftell(pb);
1116
            put_be32(pb, 0); /* size */
1117
            put_tag(pb, "\251req");
1118
            put_be16(pb, sizeof("QuickTime 6.0 or greater") - 1);
1119
            put_be16(pb, 0);
1120
            put_buffer(pb, "QuickTime 6.0 or greater",
1121
                       sizeof("QuickTime 6.0 or greater") - 1);
1122
            updateSize(pb, pos);
1123
            break;
1124
        }
1125
    }
1126

    
1127
    /* Encoder */
1128
    if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1129
    {
1130
        int pos = url_ftell(pb);
1131
        put_be32(pb, 0); /* size */
1132
        put_tag(pb, "\251enc");
1133
        put_be16(pb, sizeof(LIBAVFORMAT_IDENT) - 1); /* string length */
1134
        put_be16(pb, 0);
1135
        put_buffer(pb, LIBAVFORMAT_IDENT, sizeof(LIBAVFORMAT_IDENT) - 1);
1136
        updateSize(pb, pos);
1137
    }
1138

    
1139
    if( s->title[0] )
1140
    {
1141
        int pos = url_ftell(pb);
1142
        put_be32(pb, 0); /* size */
1143
        put_tag(pb, "\251nam");
1144
        put_be16(pb, strlen(s->title)); /* string length */
1145
        put_be16(pb, 0);
1146
        put_buffer(pb, s->title, strlen(s->title));
1147
        updateSize(pb, pos);
1148
    }
1149

    
1150
    if( s->author[0] )
1151
    {
1152
        int pos = url_ftell(pb);
1153
        put_be32(pb, 0); /* size */
1154
        put_tag(pb, /*"\251aut"*/ "\251day" );
1155
        put_be16(pb, strlen(s->author)); /* string length */
1156
        put_be16(pb, 0);
1157
        put_buffer(pb, s->author, strlen(s->author));
1158
        updateSize(pb, pos);
1159
    }
1160

    
1161
    if( s->comment[0] )
1162
    {
1163
        int pos = url_ftell(pb);
1164
        put_be32(pb, 0); /* size */
1165
        put_tag(pb, "\251des");
1166
        put_be16(pb, strlen(s->comment)); /* string length */
1167
        put_be16(pb, 0);
1168
        put_buffer(pb, s->comment, strlen(s->comment));
1169
        updateSize(pb, pos);
1170
    }
1171

    
1172
    return updateSize(pb, pos);
1173
}
1174

    
1175
static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1176
                              AVFormatContext *s)
1177
{
1178
    int pos, i;
1179
    pos = url_ftell(pb);
1180
    put_be32(pb, 0); /* size placeholder*/
1181
    put_tag(pb, "moov");
1182
    mov->timescale = globalTimescale;
1183

    
1184
    for (i=0; i<MAX_STREAMS; i++) {
1185
        if(mov->tracks[i].entry <= 0) continue;
1186

    
1187
        if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {
1188
            mov->tracks[i].timescale = mov->tracks[i].enc->time_base.den;
1189
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->time_base.num;
1190
        }
1191
        else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {
1192
            /* If AMR, track timescale = 8000, AMR_WB = 16000 */
1193
            if(mov->tracks[i].enc->codec_id == CODEC_ID_AMR_NB) {
1194
                mov->tracks[i].sampleDuration = 160;  // Bytes per chunk
1195
                mov->tracks[i].timescale = 8000;
1196
            }
1197
            else {
1198
                mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;
1199
                mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;
1200
            }
1201
        }
1202

    
1203
        mov->tracks[i].trackDuration =
1204
            mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;
1205
        mov->tracks[i].time = mov->time;
1206
        mov->tracks[i].trackID = i+1;
1207
    }
1208

    
1209
    mov_write_mvhd_tag(pb, mov);
1210
    //mov_write_iods_tag(pb, mov);
1211
    for (i=0; i<MAX_STREAMS; i++) {
1212
        if(mov->tracks[i].entry > 0) {
1213
            mov_write_trak_tag(pb, &(mov->tracks[i]));
1214
        }
1215
    }
1216

    
1217
    mov_write_udta_tag(pb, mov, s);
1218

    
1219
    return updateSize(pb, pos);
1220
}
1221

    
1222
int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1223
{
1224
    mov->mdat_pos = url_ftell(pb);
1225
    put_be32(pb, 0); /* size placeholder*/
1226
    put_tag(pb, "mdat");
1227
    return 0;
1228
}
1229

    
1230
/* TODO: This needs to be more general */
1231
int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
1232
{
1233
    MOVContext *mov = s->priv_data;
1234

    
1235
    put_be32(pb, 0x14 ); /* size */
1236
    put_tag(pb, "ftyp");
1237

    
1238
    if ( mov->mode == MODE_3GP )
1239
        put_tag(pb, "3gp4");
1240
    else if ( mov->mode == MODE_3G2 )
1241
        put_tag(pb, "3g2a");
1242
    else if ( mov->mode == MODE_PSP )
1243
        put_tag(pb, "MSNV");
1244
    else
1245
        put_tag(pb, "isom");
1246

    
1247
    put_be32(pb, 0x200 );
1248

    
1249
    if ( mov->mode == MODE_3GP )
1250
        put_tag(pb, "3gp4");
1251
    else if ( mov->mode == MODE_3G2 )
1252
        put_tag(pb, "3g2a");
1253
    else if ( mov->mode == MODE_PSP )
1254
        put_tag(pb, "MSNV");
1255
    else
1256
        put_tag(pb, "mp41");
1257

    
1258
    return 0x14;
1259
}
1260

    
1261
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1262
{
1263
    int AudioRate = s->streams[1]->codec->sample_rate;
1264
    int FrameRate = ((s->streams[0]->codec->time_base.den) * (0x10000))/ (s->streams[0]->codec->time_base.num);
1265

    
1266
    //printf("audiorate = %d\n",AudioRate);
1267
    //printf("framerate = %d / %d = 0x%x\n",s->streams[0]->codec->time_base.den,s->streams[0]->codec->time_base.num,FrameRate);
1268

    
1269
    put_be32(pb, 0x94 ); /* size */
1270
    put_tag(pb, "uuid");
1271
    put_tag(pb, "PROF");
1272

    
1273
    put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1274
    put_be32(pb, 0xbb88695c );
1275
    put_be32(pb, 0xfac9c740 );
1276

    
1277
    put_be32(pb, 0x0 );  /* ? */
1278
    put_be32(pb, 0x3 );  /* 3 sections ? */
1279

    
1280
    put_be32(pb, 0x14 ); /* size */
1281
    put_tag(pb, "FPRF");
1282
    put_be32(pb, 0x0 );  /* ? */
1283
    put_be32(pb, 0x0 );  /* ? */
1284
    put_be32(pb, 0x0 );  /* ? */
1285

    
1286
    put_be32(pb, 0x2c );  /* size */
1287
    put_tag(pb, "APRF");   /* audio */
1288
    put_be32(pb, 0x0 );
1289
    put_be32(pb, 0x2 );
1290
    put_tag(pb, "mp4a");
1291
    put_be32(pb, 0x20f );
1292
    put_be32(pb, 0x0 );
1293
    put_be32(pb, 0x40 );
1294
    put_be32(pb, 0x40 );
1295
    put_be32(pb, AudioRate ); //24000   ... audio rate?
1296
    put_be32(pb, 0x2 );
1297

    
1298
    put_be32(pb, 0x34 );  /* size */
1299
    put_tag(pb, "VPRF");   /* video */
1300
    put_be32(pb, 0x0 );
1301
    put_be32(pb, 0x1 );
1302
    put_tag(pb, "mp4v");
1303
    put_be32(pb, 0x103 );
1304
    put_be32(pb, 0x0 );
1305
    put_be32(pb, 0xc0 );
1306
    put_be32(pb, 0xc0 );
1307
    put_be32(pb, FrameRate);  // was 0xefc29
1308
    put_be32(pb, FrameRate );  // was 0xefc29
1309
    put_be16(pb, s->streams[0]->codec->width);
1310
    put_be16(pb, s->streams[0]->codec->height);
1311
    put_be32(pb, 0x010001 );
1312
}
1313

    
1314
static int mov_write_header(AVFormatContext *s)
1315
{
1316
    ByteIOContext *pb = &s->pb;
1317
    MOVContext *mov = s->priv_data;
1318
    int i;
1319

    
1320
    for(i=0; i<s->nb_streams; i++){
1321
        AVCodecContext *c= s->streams[i]->codec;
1322

    
1323
        if      (c->codec_type == CODEC_TYPE_VIDEO){
1324
            if (!codec_get_tag(codec_movvideo_tags, c->codec_id)){
1325
                if(!codec_get_tag(codec_bmp_tags, c->codec_id))
1326
                    return -1;
1327
                else
1328
                    av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, the file may be unplayable!\n");
1329
            }
1330
        }else if(c->codec_type == CODEC_TYPE_AUDIO){
1331
            if (!codec_get_tag(codec_movaudio_tags, c->codec_id)){
1332
                if(!codec_get_tag(codec_wav_tags, c->codec_id))
1333
                    return -1;
1334
                else
1335
                    av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, the file may be unplayable!\n");
1336
            }
1337
        }
1338
        /* don't know yet if mp4 or not */
1339
        mov->tracks[i].language = ff_mov_iso639_to_lang(s->streams[i]->language, 1);
1340
    }
1341

    
1342
    /* Default mode == MP4 */
1343
    mov->mode = MODE_MP4;
1344

    
1345
    if (s->oformat != NULL) {
1346
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1347
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3G2;
1348
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1349
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1350

    
1351
        if ( mov->mode == MODE_3GP || mov->mode == MODE_3G2 ||
1352
             mov->mode == MODE_MP4 || mov->mode == MODE_PSP )
1353
            mov_write_ftyp_tag(pb,s);
1354
        if ( mov->mode == MODE_PSP ) {
1355
            if ( s->nb_streams != 2 ) {
1356
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1357
                return -1;
1358
            }
1359
            mov_write_uuidprof_tag(pb,s);
1360
        }
1361
    }
1362

    
1363
    for (i=0; i<MAX_STREAMS; i++) {
1364
        mov->tracks[i].mode = mov->mode;
1365
    }
1366

    
1367
    put_flush_packet(pb);
1368

    
1369
    return 0;
1370
}
1371

    
1372
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1373
{
1374
    MOVContext *mov = s->priv_data;
1375
    ByteIOContext *pb = &s->pb;
1376
    AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
1377
    MOVTrack* trk = &mov->tracks[pkt->stream_index];
1378
    int cl, id;
1379
    unsigned int samplesInChunk = 0;
1380
    int size= pkt->size;
1381

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

    
1385
    if (enc->codec_type == CODEC_TYPE_VIDEO ) {
1386
        samplesInChunk = 1;
1387
    }
1388
    else if (enc->codec_type == CODEC_TYPE_AUDIO ) {
1389
        if( enc->codec_id == CODEC_ID_AMR_NB) {
1390
            /* We must find out how many AMR blocks there are in one packet */
1391
            static uint16_t packed_size[16] =
1392
                {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1393
            int len = 0;
1394

    
1395
            while (len < size && samplesInChunk < 100) {
1396
                len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1397
                samplesInChunk++;
1398
            }
1399
        }
1400
        else if(enc->codec_id == CODEC_ID_PCM_ALAW) {
1401
            samplesInChunk = size/enc->channels;
1402
        }
1403
        else if(enc->codec_id == CODEC_ID_PCM_S16BE || enc->codec_id == CODEC_ID_PCM_S16LE) {
1404
            samplesInChunk = size/(2*enc->channels);
1405
        }
1406
        else {
1407
            samplesInChunk = 1;
1408
        }
1409
    }
1410

    
1411
    if ((enc->codec_id == CODEC_ID_MPEG4 || enc->codec_id == CODEC_ID_AAC)
1412
        && trk->vosLen == 0) {
1413
//        assert(enc->extradata_size);
1414

    
1415
        trk->vosLen = enc->extradata_size;
1416
        trk->vosData = av_malloc(trk->vosLen);
1417
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1418
    }
1419

    
1420
    cl = trk->entry / MOV_INDEX_CLUSTER_SIZE;
1421
    id = trk->entry % MOV_INDEX_CLUSTER_SIZE;
1422

    
1423
    if (trk->ents_allocated <= trk->entry) {
1424
        trk->cluster = av_realloc(trk->cluster, (cl+1)*sizeof(void*));
1425
        if (!trk->cluster)
1426
            return -1;
1427
        trk->cluster[cl] = av_malloc(MOV_INDEX_CLUSTER_SIZE*sizeof(MOVIentry));
1428
        if (!trk->cluster[cl])
1429
            return -1;
1430
        trk->ents_allocated += MOV_INDEX_CLUSTER_SIZE;
1431
    }
1432
    if (mov->mdat_written == 0) {
1433
        mov_write_mdat_tag(pb, mov);
1434
        mov->mdat_written = 1;
1435
        mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1436
    }
1437

    
1438
    trk->cluster[cl][id].pos = url_ftell(pb);
1439
    trk->cluster[cl][id].samplesInChunk = samplesInChunk;
1440
    trk->cluster[cl][id].size = size;
1441
    trk->cluster[cl][id].entries = samplesInChunk;
1442
    if(enc->codec_type == CODEC_TYPE_VIDEO) {
1443
        trk->cluster[cl][id].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1444
        if(trk->cluster[cl][id].key_frame)
1445
            trk->hasKeyframes = 1;
1446
    }
1447
    trk->enc = enc;
1448
    trk->entry++;
1449
    trk->sampleCount += samplesInChunk;
1450
    trk->mdat_size += size;
1451

    
1452
    put_buffer(pb, pkt->data, size);
1453

    
1454
    put_flush_packet(pb);
1455
    return 0;
1456
}
1457

    
1458
static int mov_write_trailer(AVFormatContext *s)
1459
{
1460
    MOVContext *mov = s->priv_data;
1461
    ByteIOContext *pb = &s->pb;
1462
    int res = 0;
1463
    int i, j;
1464

    
1465
    offset_t moov_pos = url_ftell(pb);
1466

    
1467
    /* Write size of mdat tag */
1468
    for (i=0, j=0; i<MAX_STREAMS; i++) {
1469
        if(mov->tracks[i].ents_allocated > 0) {
1470
            j += mov->tracks[i].mdat_size;
1471
        }
1472
    }
1473
    url_fseek(pb, mov->mdat_pos, SEEK_SET);
1474
    put_be32(pb, j+8);
1475
    url_fseek(pb, moov_pos, SEEK_SET);
1476

    
1477
    mov_write_moov_tag(pb, mov, s);
1478

    
1479
    for (i=0; i<MAX_STREAMS; i++) {
1480
        for (j=0; j<mov->tracks[i].ents_allocated/MOV_INDEX_CLUSTER_SIZE; j++) {
1481
            av_free(mov->tracks[i].cluster[j]);
1482
        }
1483
        av_free(mov->tracks[i].cluster);
1484
        if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1485

    
1486
        mov->tracks[i].cluster = NULL;
1487
        mov->tracks[i].ents_allocated = mov->tracks[i].entry = 0;
1488
    }
1489

    
1490
    put_flush_packet(pb);
1491

    
1492
    return res;
1493
}
1494

    
1495
static AVOutputFormat mov_oformat = {
1496
    "mov",
1497
    "mov format",
1498
    NULL,
1499
    "mov",
1500
    sizeof(MOVContext),
1501
    CODEC_ID_AAC,
1502
    CODEC_ID_MPEG4,
1503
    mov_write_header,
1504
    mov_write_packet,
1505
    mov_write_trailer,
1506
    .flags = AVFMT_GLOBALHEADER,
1507
};
1508

    
1509
static AVOutputFormat _3gp_oformat = {
1510
    "3gp",
1511
    "3gp format",
1512
    NULL,
1513
    "3gp",
1514
    sizeof(MOVContext),
1515
    CODEC_ID_AMR_NB,
1516
    CODEC_ID_H263,
1517
    mov_write_header,
1518
    mov_write_packet,
1519
    mov_write_trailer,
1520
    .flags = AVFMT_GLOBALHEADER,
1521
};
1522

    
1523
static AVOutputFormat mp4_oformat = {
1524
    "mp4",
1525
    "mp4 format",
1526
    "application/mp4",
1527
    "mp4,m4a",
1528
    sizeof(MOVContext),
1529
    CODEC_ID_AAC,
1530
    CODEC_ID_MPEG4,
1531
    mov_write_header,
1532
    mov_write_packet,
1533
    mov_write_trailer,
1534
    .flags = AVFMT_GLOBALHEADER,
1535
};
1536

    
1537
static AVOutputFormat psp_oformat = {
1538
    "psp",
1539
    "psp mp4 format",
1540
    NULL,
1541
    "mp4,psp",
1542
    sizeof(MOVContext),
1543
    CODEC_ID_AAC,
1544
    CODEC_ID_MPEG4,
1545
    mov_write_header,
1546
    mov_write_packet,
1547
    mov_write_trailer,
1548
//    .flags = AVFMT_GLOBALHEADER,
1549
};
1550

    
1551
static AVOutputFormat _3g2_oformat = {
1552
    "3g2",
1553
    "3gp2 format",
1554
    NULL,
1555
    "3g2",
1556
    sizeof(MOVContext),
1557
    CODEC_ID_AMR_NB,
1558
    CODEC_ID_H263,
1559
    mov_write_header,
1560
    mov_write_packet,
1561
    mov_write_trailer,
1562
    .flags = AVFMT_GLOBALHEADER,
1563
};
1564

    
1565
int movenc_init(void)
1566
{
1567
    av_register_output_format(&mov_oformat);
1568
    av_register_output_format(&_3gp_oformat);
1569
    av_register_output_format(&mp4_oformat);
1570
    av_register_output_format(&psp_oformat);
1571
    av_register_output_format(&_3g2_oformat);
1572
    return 0;
1573
}