Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ c04c3282

History | View | Annotate | Download (50.4 KB)

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

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

    
28
#define MOV_INDEX_CLUSTER_SIZE 16384
29
#define globalTimescale 1000
30

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

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

    
47
typedef struct MOVIndex {
48
    int         mode;
49
    int         entry;
50
    uint64_t    mdat_size;
51
    int         ents_allocated;
52
    long        timescale;
53
    long        time;
54
    long        trackDuration;
55
    long        sampleCount;
56
    long        sampleDuration;
57
    int         hasKeyframes;
58
    int         hasBframes;
59
    int         language;
60
    int         trackID;
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
    long    time;
71
    int     nb_streams;
72
    int     mdat_written;
73
    offset_t mdat_pos;
74
    long    timescale;
75
    MOVTrack tracks[MAX_STREAMS];
76
} MOVContext;
77

    
78
static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track);
79

    
80
/* output language code from iso639 language name */
81
extern int ff_mov_iso639_to_lang(const char *lang, int mp4);
82

    
83
//FIXME supprt 64bit varaint with wide placeholders
84
static offset_t updateSize (ByteIOContext *pb, offset_t pos)
85
{
86
    offset_t curpos = url_ftell(pb);
87
    url_fseek(pb, pos, SEEK_SET);
88
    put_be32(pb, curpos - pos); /* rewrite size */
89
    url_fseek(pb, curpos, SEEK_SET);
90

    
91
    return curpos - pos;
92
}
93

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

    
119
/* Sample size atom */
120
static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack* track)
121
{
122
    int equalChunks = 1;
123
    int i, j, entries = 0, tst = -1, oldtst = -1;
124

    
125
    offset_t pos = url_ftell(pb);
126
    put_be32(pb, 0); /* size */
127
    put_tag(pb, "stsz");
128
    put_be32(pb, 0); /* version & flags */
129

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

    
160
/* Sample to chunk atom */
161
static int mov_write_stsc_tag(ByteIOContext *pb, MOVTrack* track)
162
{
163
    int index = 0, oldval = -1, i;
164
    offset_t entryPos, curpos;
165

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

    
189
    return updateSize (pb, pos);
190
}
191

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

    
218
static int mov_write_damr_tag(ByteIOContext *pb)
219
{
220
    put_be32(pb, 0x11); /* size */
221
    put_tag(pb, "damr");
222
    put_tag(pb, "FFMP");
223
    put_byte(pb, 0);
224

    
225
    put_be16(pb, 0x80); /* Mode set (all modes for AMR_NB) */
226
    put_be16(pb, 0xa); /* Mode change period (no restriction) */
227
    //put_be16(pb, 0x81ff); /* Mode set (all modes for AMR_NB) */
228
    //put_be16(pb, 1); /* Mode change period (no restriction) */
229
    return 0x11;
230
}
231

    
232
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack* track)
233
{
234
    offset_t pos = url_ftell(pb);
235

    
236
    put_be32(pb, 0);     /* size */
237
    put_tag(pb, "wave");
238

    
239
    put_be32(pb, 12);    /* size */
240
    put_tag(pb, "frma");
241
    put_tag(pb, "mp4a");
242

    
243
    put_be32(pb, 12);    /* size */
244
    put_tag(pb, "mp4a");
245
    put_be32(pb, 0);
246

    
247
    mov_write_esds_tag(pb, track);
248

    
249
    put_be32(pb, 12);    /* size */
250
    put_tag(pb, "srcq");
251
    put_be32(pb, 0x40);
252

    
253
    put_be32(pb, 8);     /* size */
254
    put_be32(pb, 0);     /* null tag */
255

    
256
    return updateSize (pb, pos);
257
}
258

    
259
static const CodecTag codec_movaudio_tags[] = {
260
    { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') },
261
    { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') },
262
    { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') },
263
    { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') },
264
    { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') },
265
    { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
266
    { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') },
267
    { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') },
268
    { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') },
269
    { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') },
270
    { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') },
271
    { CODEC_ID_NONE, 0 },
272
};
273

    
274
static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack* track)
275
{
276
    offset_t pos = url_ftell(pb);
277
    int tag;
278

    
279
    put_be32(pb, 0); /* size */
280

    
281
    tag = track->enc->codec_tag;
282
    if (!tag)
283
    tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
284
    // if no mac fcc found, try with Microsoft tags
285
    if (!tag)
286
    {
287
        int tmp = codec_get_tag(codec_wav_tags, track->enc->codec_id);
288
        tag = MKTAG('m', 's', ((tmp >> 8) & 0xff), (tmp & 0xff));
289
    }
290
    put_le32(pb, tag); // store it byteswapped
291

    
292
    put_be32(pb, 0); /* Reserved */
293
    put_be16(pb, 0); /* Reserved */
294
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
295

    
296
    /* SoundDescription */
297
    if(track->mode == MODE_MOV && track->enc->codec_id == CODEC_ID_AAC)
298
        put_be16(pb, 1); /* Version 1 */
299
    else
300
        put_be16(pb, 0); /* Version 0 */
301
    put_be16(pb, 0); /* Revision level */
302
    put_be32(pb, 0); /* Reserved */
303

    
304
    put_be16(pb, track->enc->channels); /* Number of channels */
305
    /* TODO: Currently hard-coded to 16-bit, there doesn't seem
306
                 to be a good way to get number of bits of audio */
307
    put_be16(pb, 0x10); /* Reserved */
308

    
309
    if(track->enc->codec_id == CODEC_ID_AAC ||
310
       track->enc->codec_id == CODEC_ID_MP3)
311
    {
312
        put_be16(pb, 0xfffe); /* compression ID (vbr)*/
313
    }
314
    else
315
    {
316
        put_be16(pb, 0); /* compression ID (= 0) */
317
    }
318
    put_be16(pb, 0); /* packet size (= 0) */
319
    put_be16(pb, track->timescale); /* Time scale */
320
    put_be16(pb, 0); /* Reserved */
321

    
322
    if(track->mode == MODE_MOV && track->enc->codec_id == CODEC_ID_AAC)
323
    {
324
        /* SoundDescription V1 extended info */
325
        put_be32(pb, track->enc->frame_size); /* Samples per packet  */
326
        put_be32(pb, 1536); /* Bytes per packet */
327
        put_be32(pb, 2); /* Bytes per frame */
328
        put_be32(pb, 2); /* Bytes per sample */
329
    }
330

    
331
    if(track->enc->codec_id == CODEC_ID_AAC) {
332
        if( track->mode == MODE_MOV ) mov_write_wave_tag(pb, track);
333
        else mov_write_esds_tag(pb, track);
334
    }
335
    if(track->enc->codec_id == CODEC_ID_AMR_NB)
336
        mov_write_damr_tag(pb);
337
    return updateSize (pb, pos);
338
}
339

    
340
static int mov_write_d263_tag(ByteIOContext *pb)
341
{
342
    put_be32(pb, 0xf); /* size */
343
    put_tag(pb, "d263");
344
    put_tag(pb, "FFMP");
345
    put_be16(pb, 0x0a);
346
    put_byte(pb, 0);
347
    return 0xf;
348
}
349

    
350
/* TODO: No idea about these values */
351
static int mov_write_svq3_tag(ByteIOContext *pb)
352
{
353
    put_be32(pb, 0x15);
354
    put_tag(pb, "SMI ");
355
    put_tag(pb, "SEQH");
356
    put_be32(pb, 0x5);
357
    put_be32(pb, 0xe2c0211d);
358
    put_be32(pb, 0xc0000000);
359
    put_byte(pb, 0);
360
    return 0x15;
361
}
362

    
363
static unsigned int descrLength(unsigned int len)
364
{
365
    if (len < 0x00000080)
366
        return 2 + len;
367
    else if (len < 0x00004000)
368
        return 3 + len;
369
    else if(len < 0x00200000)
370
        return 4 + len;
371
    else
372
        return 5 + len;
373
}
374

    
375
static void putDescr(ByteIOContext *pb, int tag, int size)
376
{
377
    uint32_t len;
378
    uint8_t  vals[4];
379

    
380
    len = size;
381
    vals[3] = (uint8_t)(len & 0x7f);
382
    len >>= 7;
383
    vals[2] = (uint8_t)((len & 0x7f) | 0x80);
384
    len >>= 7;
385
    vals[1] = (uint8_t)((len & 0x7f) | 0x80);
386
    len >>= 7;
387
    vals[0] = (uint8_t)((len & 0x7f) | 0x80);
388

    
389
    put_byte(pb, tag); // DescriptorTag
390

    
391
    if (size < 0x00000080)
392
    {
393
        put_byte(pb, vals[3]);
394
    }
395
    else if (size < 0x00004000)
396
    {
397
        put_byte(pb, vals[2]);
398
        put_byte(pb, vals[3]);
399
    }
400
    else if (size < 0x00200000)
401
    {
402
        put_byte(pb, vals[1]);
403
        put_byte(pb, vals[2]);
404
        put_byte(pb, vals[3]);
405
    }
406
    else if (size < 0x10000000)
407
    {
408
        put_byte(pb, vals[0]);
409
        put_byte(pb, vals[1]);
410
        put_byte(pb, vals[2]);
411
        put_byte(pb, vals[3]);
412
    }
413
}
414

    
415
static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track) // Basic
416
{
417
    int decoderSpecificInfoLen;
418
    offset_t pos = url_ftell(pb);
419

    
420
    decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
421

    
422
    put_be32(pb, 0);               // size
423
    put_tag(pb, "esds");
424
    put_be32(pb, 0);               // Version
425

    
426
    // ES descriptor
427
    putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
428
             descrLength(1));
429
    put_be16(pb, track->trackID);
430
    put_byte(pb, 0x00);            // flags (= no flags)
431

    
432
    // DecoderConfig descriptor
433
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
434

    
435
    // Object type indication
436
    put_byte(pb, codec_get_tag(ff_mov_obj_type, track->enc->codec_id));
437

    
438
    // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
439
    // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
440
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
441
        put_byte(pb, 0x15);            // flags (= Audiostream)
442
    else
443
        put_byte(pb, 0x11);            // flags (= Visualstream)
444

    
445
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));             // Buffersize DB (24 bits)
446
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF);          // Buffersize DB
447

    
448
    put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate));     // maxbitrate  (FIXME should be max rate in any 1 sec window)
449
    if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
450
        put_be32(pb, 0);     // vbr
451
    else
452
        put_be32(pb, track->enc->rc_max_rate);     // avg bitrate
453

    
454
    if (track->vosLen)
455
    {
456
        // DecoderSpecific info descriptor
457
        putDescr(pb, 0x05, track->vosLen);
458
        put_buffer(pb, track->vosData, track->vosLen);
459
    }
460

    
461

    
462
    // SL descriptor
463
    putDescr(pb, 0x06, 1);
464
    put_byte(pb, 0x02);
465
    return updateSize (pb, pos);
466
}
467

    
468
static const CodecTag codec_movvideo_tags[] = {
469
    { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') },
470
    { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') },
471
    { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
472
    { CODEC_ID_H263, MKTAG('s', '2', '6', '3') },
473
    { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
474
    /* special handling in mov_find_video_codec_tag */
475
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
476
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
477
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'p', 'p') }, /* DVCPRO PAL */
478
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'n') }, /* DVCPRO50 NTSC */
479
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'p') }, /* DVCPRO50 PAL */
480
    { CODEC_ID_NONE, 0 },
481
};
482

    
483
static int mov_find_video_codec_tag(MOVTrack* track)
484
{
485
    int tag;
486

    
487
    tag = track->enc->codec_tag;
488
    if (!tag) {
489
        if (track->enc->codec_id == CODEC_ID_DVVIDEO) {
490
            if (track->enc->height == 480) { /* NTSC */
491
                if (track->enc->pix_fmt == PIX_FMT_YUV422P)
492
                    tag = MKTAG('d', 'v', '5', 'n');
493
                else
494
                    tag = MKTAG('d', 'v', 'c', ' ');
495
            } else { /* assume PAL */
496
                if (track->enc->pix_fmt == PIX_FMT_YUV422P)
497
                    tag = MKTAG('d', 'v', '5', 'p');
498
                else if (track->enc->pix_fmt == PIX_FMT_YUV420P)
499
                    tag = MKTAG('d', 'v', 'p', 'p');
500
                else
501
                    tag = MKTAG('d', 'v', 'c', 'p');
502
            }
503
        } else {
504
            tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
505
        }
506
    }
507
    // if no mac fcc found, try with Microsoft tags
508
    if (!tag)
509
        tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
510
    assert(tag);
511
    return tag;
512
}
513

    
514
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
515
{
516
    offset_t pos = url_ftell(pb);
517
    char compressor_name[32];
518
    int tag;
519

    
520
    put_be32(pb, 0); /* size */
521

    
522
    tag = mov_find_video_codec_tag(track);
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
    offset_t 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
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack* track)
579
{
580
    Time2Sample *ctts_entries;
581
    uint32_t entries = 0;
582
    uint32_t atom_size;
583
    int i;
584

    
585
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
586
    ctts_entries[0].count = 1;
587
    ctts_entries[0].duration = track->cluster[0][0].cts;
588
    for (i=1; i<track->entry; i++) {
589
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
590
        int id = i % MOV_INDEX_CLUSTER_SIZE;
591
        if (track->cluster[cl][id].cts == ctts_entries[entries].duration) {
592
            ctts_entries[entries].count++; /* compress */
593
        } else {
594
            entries++;
595
            ctts_entries[entries].duration = track->cluster[cl][id].cts;
596
            ctts_entries[entries].count = 1;
597
        }
598
    }
599
    entries++; /* last one */
600
    atom_size = 16 + (entries * 8);
601
    put_be32(pb, atom_size); /* size */
602
    put_tag(pb, "ctts");
603
    put_be32(pb, 0); /* version & flags */
604
    put_be32(pb, entries); /* entry count */
605
    for (i=0; i<entries; i++) {
606
        put_be32(pb, ctts_entries[i].count);
607
        put_be32(pb, ctts_entries[i].duration);
608
    }
609
    av_free(ctts_entries);
610
    return atom_size;
611
}
612

    
613
/* TODO: */
614
/* Time to sample atom */
615
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack* track)
616
{
617
    put_be32(pb, 0x18); /* size */
618
    put_tag(pb, "stts");
619
    put_be32(pb, 0); /* version & flags */
620
    put_be32(pb, 1); /* entry count */
621

    
622
    put_be32(pb, track->sampleCount); /* sample count */
623
    put_be32(pb, track->sampleDuration); /* sample duration */
624
    return 0x18;
625
}
626

    
627
static int mov_write_dref_tag(ByteIOContext *pb)
628
{
629
    put_be32(pb, 28); /* size */
630
    put_tag(pb, "dref");
631
    put_be32(pb, 0); /* version & flags */
632
    put_be32(pb, 1); /* entry count */
633

    
634
    put_be32(pb, 0xc); /* size */
635
    put_tag(pb, "url ");
636
    put_be32(pb, 1); /* version & flags */
637

    
638
    return 28;
639
}
640

    
641
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track)
642
{
643
    offset_t pos = url_ftell(pb);
644
    put_be32(pb, 0); /* size */
645
    put_tag(pb, "stbl");
646
    mov_write_stsd_tag(pb, track);
647
    mov_write_stts_tag(pb, track);
648
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
649
        track->hasKeyframes)
650
        mov_write_stss_tag(pb, track);
651
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
652
        track->hasBframes)
653
        mov_write_ctts_tag(pb, track);
654
    mov_write_stsc_tag(pb, track);
655
    mov_write_stsz_tag(pb, track);
656
    mov_write_stco_tag(pb, track);
657
    return updateSize(pb, pos);
658
}
659

    
660
static int mov_write_dinf_tag(ByteIOContext *pb)
661
{
662
    offset_t pos = url_ftell(pb);
663
    put_be32(pb, 0); /* size */
664
    put_tag(pb, "dinf");
665
    mov_write_dref_tag(pb);
666
    return updateSize(pb, pos);
667
}
668

    
669
static int mov_write_smhd_tag(ByteIOContext *pb)
670
{
671
    put_be32(pb, 16); /* size */
672
    put_tag(pb, "smhd");
673
    put_be32(pb, 0); /* version & flags */
674
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
675
    put_be16(pb, 0); /* reserved */
676
    return 16;
677
}
678

    
679
static int mov_write_vmhd_tag(ByteIOContext *pb)
680
{
681
    put_be32(pb, 0x14); /* size (always 0x14) */
682
    put_tag(pb, "vmhd");
683
    put_be32(pb, 0x01); /* version & flags */
684
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
685
    return 0x14;
686
}
687

    
688
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack* track)
689
{
690
    char *descr, *hdlr, *hdlr_type;
691
    offset_t pos = url_ftell(pb);
692

    
693
    if (!track) { /* no media --> data handler */
694
        hdlr = "dhlr";
695
        hdlr_type = "url ";
696
        descr = "DataHandler";
697
    } else {
698
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
699
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
700
            hdlr_type = "vide";
701
            descr = "VideoHandler";
702
        } else {
703
            hdlr_type = "soun";
704
            descr = "SoundHandler";
705
        }
706
    }
707

    
708
    put_be32(pb, 0); /* size */
709
    put_tag(pb, "hdlr");
710
    put_be32(pb, 0); /* Version & flags */
711
    put_buffer(pb, hdlr, 4); /* handler */
712
    put_tag(pb, hdlr_type); /* handler type */
713
    put_be32(pb ,0); /* reserved */
714
    put_be32(pb ,0); /* reserved */
715
    put_be32(pb ,0); /* reserved */
716
    put_byte(pb, strlen(descr)); /* string counter */
717
    put_buffer(pb, descr, strlen(descr)); /* handler description */
718
    return updateSize(pb, pos);
719
}
720

    
721
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack* track)
722
{
723
    offset_t pos = url_ftell(pb);
724
    put_be32(pb, 0); /* size */
725
    put_tag(pb, "minf");
726
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
727
        mov_write_vmhd_tag(pb);
728
    else
729
        mov_write_smhd_tag(pb);
730
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
731
        mov_write_hdlr_tag(pb, NULL);
732
    mov_write_dinf_tag(pb);
733
    mov_write_stbl_tag(pb, track);
734
    return updateSize(pb, pos);
735
}
736

    
737
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack* track)
738
{
739
    put_be32(pb, 32); /* size */
740
    put_tag(pb, "mdhd");
741
    put_be32(pb, 0); /* Version & flags */
742
    put_be32(pb, track->time); /* creation time */
743
    put_be32(pb, track->time); /* modification time */
744
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
745
    put_be32(pb, track->trackDuration); /* duration */
746
    put_be16(pb, track->language); /* language */
747
    put_be16(pb, 0); /* reserved (quality) */
748
    return 32;
749
}
750

    
751
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack* track)
752
{
753
    offset_t pos = url_ftell(pb);
754
    put_be32(pb, 0); /* size */
755
    put_tag(pb, "mdia");
756
    mov_write_mdhd_tag(pb, track);
757
    mov_write_hdlr_tag(pb, track);
758
    mov_write_minf_tag(pb, track);
759
    return updateSize(pb, pos);
760
}
761

    
762
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)
763
{
764
    put_be32(pb, 0x5c); /* size (always 0x5c) */
765
    put_tag(pb, "tkhd");
766
    put_be32(pb, 0xf); /* version & flags (track enabled) */
767
    put_be32(pb, track->time); /* creation time */
768
    put_be32(pb, track->time); /* modification time */
769
    put_be32(pb, track->trackID); /* track-id */
770
    put_be32(pb, 0); /* reserved */
771
    put_be32(pb, av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP)); /* duration */
772

    
773
    put_be32(pb, 0); /* reserved */
774
    put_be32(pb, 0); /* reserved */
775
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
776
    /* Volume, only for audio */
777
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
778
        put_be16(pb, 0x0100);
779
    else
780
        put_be16(pb, 0);
781
    put_be16(pb, 0); /* reserved */
782

    
783
    /* Matrix structure */
784
    put_be32(pb, 0x00010000); /* reserved */
785
    put_be32(pb, 0x0); /* reserved */
786
    put_be32(pb, 0x0); /* reserved */
787
    put_be32(pb, 0x0); /* reserved */
788
    put_be32(pb, 0x00010000); /* reserved */
789
    put_be32(pb, 0x0); /* reserved */
790
    put_be32(pb, 0x0); /* reserved */
791
    put_be32(pb, 0x0); /* reserved */
792
    put_be32(pb, 0x40000000); /* reserved */
793

    
794
    /* Track width and height, for visual only */
795
    if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
796
        double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
797
        if( !sample_aspect_ratio ) sample_aspect_ratio = 1;
798
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
799
        put_be32(pb, track->enc->height*0x10000);
800
    }
801
    else {
802
        put_be32(pb, 0);
803
        put_be32(pb, 0);
804
    }
805
    return 0x5c;
806
}
807

    
808
// This box seems important for the psp playback ... without it the movie seems to hang
809
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
810
{
811
    put_be32(pb, 0x24); /* size  */
812
    put_tag(pb, "edts");
813
    put_be32(pb, 0x1c); /* size  */
814
    put_tag(pb, "elst");
815
    put_be32(pb, 0x0);
816
    put_be32(pb, 0x1);
817

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

    
820
    put_be32(pb, 0x0);
821
    put_be32(pb, 0x00010000);
822
    return 0x24;
823
}
824

    
825
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
826
static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
827
{
828
    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
829
    put_tag(pb, "uuid");
830
    put_tag(pb, "USMT");
831
    put_be32(pb, 0x21d24fce);
832
    put_be32(pb, 0xbb88695c);
833
    put_be32(pb, 0xfac9c740);
834
    put_be32(pb, 0x1c);     // another size here!
835
    put_tag(pb, "MTDT");
836
    put_be32(pb, 0x00010012);
837
    put_be32(pb, 0x0a);
838
    put_be32(pb, 0x55c40000);
839
    put_be32(pb, 0x1);
840
    put_be32(pb, 0x0);
841
    return 0x34;
842
}
843

    
844
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack* track)
845
{
846
    offset_t pos = url_ftell(pb);
847
    put_be32(pb, 0); /* size */
848
    put_tag(pb, "trak");
849
    mov_write_tkhd_tag(pb, track);
850
    if (track->mode == MODE_PSP)
851
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
852
    mov_write_mdia_tag(pb, track);
853
    if (track->mode == MODE_PSP)
854
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
855
    return updateSize(pb, pos);
856
}
857

    
858
#if 0
859
/* TODO: Not sorted out, but not necessary either */
860
static int mov_write_iods_tag(ByteIOContext *pb, MOVContext *mov)
861
{
862
    put_be32(pb, 0x15); /* size */
863
    put_tag(pb, "iods");
864
    put_be32(pb, 0);    /* version & flags */
865
    put_be16(pb, 0x1007);
866
    put_byte(pb, 0);
867
    put_be16(pb, 0x4fff);
868
    put_be16(pb, 0xfffe);
869
    put_be16(pb, 0x01ff);
870
    return 0x15;
871
}
872
#endif
873

    
874
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
875
{
876
    int maxTrackID = 1, i;
877
    int64_t maxTrackLenTemp, maxTrackLen = 0;
878

    
879
    put_be32(pb, 0x6c); /* size (always 0x6c) */
880
    put_tag(pb, "mvhd");
881
    put_be32(pb, 0); /* version & flags */
882
    put_be32(pb, mov->time); /* creation time */
883
    put_be32(pb, mov->time); /* modification time */
884
    put_be32(pb, mov->timescale); /* timescale */
885
    for (i=0; i<MAX_STREAMS; i++) {
886
        if(mov->tracks[i].entry > 0) {
887
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
888
            if(maxTrackLen < maxTrackLenTemp)
889
                maxTrackLen = maxTrackLenTemp;
890
            if(maxTrackID < mov->tracks[i].trackID)
891
                maxTrackID = mov->tracks[i].trackID;
892
        }
893
    }
894
    put_be32(pb, maxTrackLen); /* duration of longest track */
895

    
896
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
897
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
898
    put_be16(pb, 0); /* reserved */
899
    put_be32(pb, 0); /* reserved */
900
    put_be32(pb, 0); /* reserved */
901

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

    
913
    put_be32(pb, 0); /* reserved (preview time) */
914
    put_be32(pb, 0); /* reserved (preview duration) */
915
    put_be32(pb, 0); /* reserved (poster time) */
916
    put_be32(pb, 0); /* reserved (selection time) */
917
    put_be32(pb, 0); /* reserved (selection duration) */
918
    put_be32(pb, 0); /* reserved (current time) */
919
    put_be32(pb, maxTrackID+1); /* Next track id */
920
    return 0x6c;
921
}
922

    
923
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVContext* mov,
924
                                     AVFormatContext *s)
925
{
926
    offset_t pos = url_ftell(pb);
927
    put_be32(pb, 0); /* size */
928
    put_tag(pb, "hdlr");
929
    put_be32(pb, 0);
930
    put_be32(pb, 0);
931
    put_tag(pb, "mdir");
932
    put_tag(pb, "appl");
933
    put_be32(pb, 0);
934
    put_be32(pb, 0);
935
    put_be16(pb, 0);
936
    return updateSize(pb, pos);
937
}
938

    
939
/* helper function to write a data tag with the specified string as data */
940
static int mov_write_string_data_tag(ByteIOContext *pb, MOVContext* mov,
941
                                     AVFormatContext *s, const char *data)
942
{
943
    offset_t pos = url_ftell(pb);
944
    put_be32(pb, 0); /* size */
945
    put_tag(pb, "data");
946
    put_be32(pb, 1);
947
    put_be32(pb, 0);
948
    put_buffer(pb, data, strlen(data));
949
    return updateSize(pb, pos);
950
}
951

    
952
/* iTunes name of the song/movie */
953
static int mov_write_nam_tag(ByteIOContext *pb, MOVContext* mov,
954
                             AVFormatContext *s)
955
{
956
    int size = 0;
957
    if ( s->title[0] ) {
958
        offset_t pos = url_ftell(pb);
959
        put_be32(pb, 0); /* size */
960
        put_tag(pb, "\251nam");
961
        mov_write_string_data_tag(pb, mov, s, s->title);
962
        size = updateSize(pb, pos);
963
    }
964
    return size;
965
}
966

    
967
/* iTunes name of the artist/performer */
968
static int mov_write_ART_tag(ByteIOContext *pb, MOVContext* mov,
969
                             AVFormatContext *s)
970
{
971
    int size = 0;
972
    if ( s->author[0] ) {
973
        offset_t pos = url_ftell(pb);
974
        put_be32(pb, 0); /* size */
975
        put_tag(pb, "\251ART");
976
        // we use the author here as this is the only thing that we have...
977
        mov_write_string_data_tag(pb, mov, s, s->author);
978
        size = updateSize(pb, pos);
979
    }
980
    return size;
981
}
982

    
983
/* iTunes name of the writer */
984
static int mov_write_wrt_tag(ByteIOContext *pb, MOVContext* mov,
985
                             AVFormatContext *s)
986
{
987
    int size = 0;
988
    if ( s->author[0] ) {
989
        offset_t pos = url_ftell(pb);
990
        put_be32(pb, 0); /* size */
991
        put_tag(pb, "\251wrt");
992
        mov_write_string_data_tag(pb, mov, s, s->author);
993
        size = updateSize(pb, pos);
994
    }
995
    return size;
996
}
997

    
998
/* iTunes name of the album */
999
static int mov_write_alb_tag(ByteIOContext *pb, MOVContext* mov,
1000
                             AVFormatContext *s)
1001
{
1002
    int size = 0;
1003
    if ( s->album[0] ) {
1004
        offset_t pos = url_ftell(pb);
1005
        put_be32(pb, 0); /* size */
1006
        put_tag(pb, "\251alb");
1007
        mov_write_string_data_tag(pb, mov, s, s->album);
1008
        size = updateSize(pb, pos);
1009
    }
1010
    return size;
1011
}
1012

    
1013
/* iTunes year */
1014
static int mov_write_day_tag(ByteIOContext *pb, MOVContext* mov,
1015
                             AVFormatContext *s)
1016
{
1017
    char year[5];
1018
    int size = 0;
1019
    if ( s->year ) {
1020
        offset_t pos = url_ftell(pb);
1021
        put_be32(pb, 0); /* size */
1022
        put_tag(pb, "\251day");
1023
        snprintf(year, 5, "%04d", s->year);
1024
        mov_write_string_data_tag(pb, mov, s, year);
1025
        size = updateSize(pb, pos);
1026
    }
1027
    return size;
1028
}
1029

    
1030
/* iTunes tool used to create the file */
1031
static int mov_write_too_tag(ByteIOContext *pb, MOVContext* mov,
1032
                             AVFormatContext *s)
1033
{
1034
    offset_t pos = url_ftell(pb);
1035
    put_be32(pb, 0); /* size */
1036
    put_tag(pb, "\251too");
1037
    mov_write_string_data_tag(pb, mov, s, LIBAVFORMAT_IDENT);
1038
    return updateSize(pb, pos);
1039
}
1040

    
1041
/* iTunes comment */
1042
static int mov_write_cmt_tag(ByteIOContext *pb, MOVContext* mov,
1043
                             AVFormatContext *s)
1044
{
1045
    int size = 0;
1046
    if ( s->comment[0] ) {
1047
        offset_t pos = url_ftell(pb);
1048
        put_be32(pb, 0); /* size */
1049
        put_tag(pb, "\251cmt");
1050
        mov_write_string_data_tag(pb, mov, s, s->comment);
1051
        size = updateSize(pb, pos);
1052
    }
1053
    return size;
1054
}
1055

    
1056
/* iTunes custom genre */
1057
static int mov_write_gen_tag(ByteIOContext *pb, MOVContext* mov,
1058
                             AVFormatContext *s)
1059
{
1060
    int size = 0;
1061
    if ( s->genre[0] ) {
1062
        offset_t pos = url_ftell(pb);
1063
        put_be32(pb, 0); /* size */
1064
        put_tag(pb, "\251gen");
1065
        mov_write_string_data_tag(pb, mov, s, s->genre);
1066
        size = updateSize(pb, pos);
1067
    }
1068
    return size;
1069
}
1070

    
1071
/* iTunes track number */
1072
static int mov_write_trkn_tag(ByteIOContext *pb, MOVContext* mov,
1073
                              AVFormatContext *s)
1074
{
1075
    int size = 0;
1076
    if ( s->track ) {
1077
        offset_t pos = url_ftell(pb);
1078
        put_be32(pb, 0); /* size */
1079
        put_tag(pb, "trkn");
1080
        {
1081
            offset_t pos = url_ftell(pb);
1082
            put_be32(pb, 0); /* size */
1083
            put_tag(pb, "data");
1084
            put_be32(pb, 0);        // 8 bytes empty
1085
            put_be32(pb, 0);
1086
            put_be16(pb, 0);        // empty
1087
            put_be16(pb, s->track); // track number
1088
            put_be16(pb, 0);        // total track number
1089
            put_be16(pb, 0);        // empty
1090
            updateSize(pb, pos);
1091
        }
1092
        size = updateSize(pb, pos);
1093
    }
1094
    return size;
1095
}
1096

    
1097
/* iTunes meta data list */
1098
static int mov_write_ilst_tag(ByteIOContext *pb, MOVContext* mov,
1099
                              AVFormatContext *s)
1100
{
1101
    offset_t pos = url_ftell(pb);
1102
    put_be32(pb, 0); /* size */
1103
    put_tag(pb, "ilst");
1104
    mov_write_nam_tag(pb, mov, s);
1105
    mov_write_ART_tag(pb, mov, s);
1106
    mov_write_wrt_tag(pb, mov, s);
1107
    mov_write_alb_tag(pb, mov, s);
1108
    mov_write_day_tag(pb, mov, s);
1109
    mov_write_too_tag(pb, mov, s);
1110
    mov_write_cmt_tag(pb, mov, s);
1111
    mov_write_gen_tag(pb, mov, s);
1112
    mov_write_trkn_tag(pb, mov, s);
1113
    return updateSize(pb, pos);
1114
}
1115

    
1116
/* iTunes meta data tag */
1117
static int mov_write_meta_tag(ByteIOContext *pb, MOVContext* mov,
1118
                              AVFormatContext *s)
1119
{
1120
    int size = 0;
1121

    
1122
    // only save meta tag if required
1123
    if ( s->title[0] || s->author[0] || s->album[0] || s->year ||
1124
         s->comment[0] || s->genre[0] || s->track ) {
1125
        offset_t pos = url_ftell(pb);
1126
        put_be32(pb, 0); /* size */
1127
        put_tag(pb, "meta");
1128
        put_be32(pb, 0);
1129
        mov_write_itunes_hdlr_tag(pb, mov, s);
1130
        mov_write_ilst_tag(pb, mov, s);
1131
        size = updateSize(pb, pos);
1132
    }
1133
    return size;
1134
}
1135

    
1136
static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1137
                              AVFormatContext *s)
1138
{
1139
    offset_t pos = url_ftell(pb);
1140
    int i;
1141

    
1142
    put_be32(pb, 0); /* size */
1143
    put_tag(pb, "udta");
1144

    
1145
    /* iTunes meta data */
1146
    mov_write_meta_tag(pb, mov, s);
1147

    
1148
    /* Requirements */
1149
    for (i=0; i<MAX_STREAMS; i++) {
1150
        if(mov->tracks[i].entry <= 0) continue;
1151
        if (mov->tracks[i].enc->codec_id == CODEC_ID_AAC ||
1152
            mov->tracks[i].enc->codec_id == CODEC_ID_MPEG4) {
1153
            offset_t pos = url_ftell(pb);
1154
            put_be32(pb, 0); /* size */
1155
            put_tag(pb, "\251req");
1156
            put_be16(pb, sizeof("QuickTime 6.0 or greater") - 1);
1157
            put_be16(pb, 0);
1158
            put_buffer(pb, "QuickTime 6.0 or greater",
1159
                       sizeof("QuickTime 6.0 or greater") - 1);
1160
            updateSize(pb, pos);
1161
            break;
1162
        }
1163
    }
1164

    
1165
    /* Encoder */
1166
    if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1167
    {
1168
        offset_t pos = url_ftell(pb);
1169
        put_be32(pb, 0); /* size */
1170
        put_tag(pb, "\251enc");
1171
        put_be16(pb, sizeof(LIBAVFORMAT_IDENT) - 1); /* string length */
1172
        put_be16(pb, 0);
1173
        put_buffer(pb, LIBAVFORMAT_IDENT, sizeof(LIBAVFORMAT_IDENT) - 1);
1174
        updateSize(pb, pos);
1175
    }
1176

    
1177
    if( s->title[0] )
1178
    {
1179
        offset_t pos = url_ftell(pb);
1180
        put_be32(pb, 0); /* size */
1181
        put_tag(pb, "\251nam");
1182
        put_be16(pb, strlen(s->title)); /* string length */
1183
        put_be16(pb, 0);
1184
        put_buffer(pb, s->title, strlen(s->title));
1185
        updateSize(pb, pos);
1186
    }
1187

    
1188
    if( s->author[0] )
1189
    {
1190
        offset_t pos = url_ftell(pb);
1191
        put_be32(pb, 0); /* size */
1192
        put_tag(pb, /*"\251aut"*/ "\251day" );
1193
        put_be16(pb, strlen(s->author)); /* string length */
1194
        put_be16(pb, 0);
1195
        put_buffer(pb, s->author, strlen(s->author));
1196
        updateSize(pb, pos);
1197
    }
1198

    
1199
    if( s->comment[0] )
1200
    {
1201
        offset_t pos = url_ftell(pb);
1202
        put_be32(pb, 0); /* size */
1203
        put_tag(pb, "\251des");
1204
        put_be16(pb, strlen(s->comment)); /* string length */
1205
        put_be16(pb, 0);
1206
        put_buffer(pb, s->comment, strlen(s->comment));
1207
        updateSize(pb, pos);
1208
    }
1209

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

    
1213

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

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

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

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

    
1249
        put_be32(pb, 0); /* size placeholder*/
1250
        put_tag(pb, "MTDT");
1251
        put_be16(pb, 1);
1252
        size += 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("und")); /* language */
1259
        put_be16(pb, 0x01);                 /* ? */
1260
        ascii_to_wc (pb, s->title, len);
1261
        size += len*2+10;
1262

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

    
1272
    return size;
1273
}
1274

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

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

    
1287
        if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {
1288
            mov->tracks[i].timescale = mov->tracks[i].enc->time_base.den;
1289
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->time_base.num;
1290
        }
1291
        else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {
1292
            /* If AMR, track timescale = 8000, AMR_WB = 16000 */
1293
            if(mov->tracks[i].enc->codec_id == CODEC_ID_AMR_NB) {
1294
                mov->tracks[i].sampleDuration = 160;  // Bytes per chunk
1295
                mov->tracks[i].timescale = 8000;
1296
            }
1297
            else {
1298
                mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;
1299
                mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;
1300
            }
1301
        }
1302

    
1303
        mov->tracks[i].trackDuration =
1304
            mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;
1305
        mov->tracks[i].time = mov->time;
1306
        mov->tracks[i].trackID = i+1;
1307
    }
1308

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

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

    
1322
    return updateSize(pb, pos);
1323
}
1324

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

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

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

    
1341
    put_be32(pb, 0x14 ); /* size */
1342
    put_tag(pb, "ftyp");
1343

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

    
1355
    put_be32(pb, 0x200 );
1356

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

    
1369
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1370
{
1371
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1372
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1373
    int AudioRate = AudioCodec->sample_rate;
1374
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1375

    
1376
    put_be32(pb, 0x94 ); /* size */
1377
    put_tag(pb, "uuid");
1378
    put_tag(pb, "PROF");
1379

    
1380
    put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1381
    put_be32(pb, 0xbb88695c );
1382
    put_be32(pb, 0xfac9c740 );
1383

    
1384
    put_be32(pb, 0x0 );  /* ? */
1385
    put_be32(pb, 0x3 );  /* 3 sections ? */
1386

    
1387
    put_be32(pb, 0x14 ); /* size */
1388
    put_tag(pb, "FPRF");
1389
    put_be32(pb, 0x0 );  /* ? */
1390
    put_be32(pb, 0x0 );  /* ? */
1391
    put_be32(pb, 0x0 );  /* ? */
1392

    
1393
    put_be32(pb, 0x2c );  /* size */
1394
    put_tag(pb, "APRF");   /* audio */
1395
    put_be32(pb, 0x0 );
1396
    put_be32(pb, 0x2 );   /* TrackID */
1397
    put_tag(pb, "mp4a");
1398
    put_be32(pb, 0x20f );
1399
    put_be32(pb, 0x0 );
1400
    put_be32(pb, AudioCodec->bit_rate / 1000);
1401
    put_be32(pb, AudioCodec->bit_rate / 1000);
1402
    put_be32(pb, AudioRate );
1403
    put_be32(pb, AudioCodec->channels );
1404

    
1405
    put_be32(pb, 0x34 );  /* size */
1406
    put_tag(pb, "VPRF");   /* video */
1407
    put_be32(pb, 0x0 );
1408
    put_be32(pb, 0x1 );    /* TrackID */
1409
    put_tag(pb, "mp4v");
1410
    put_be32(pb, 0x103 );
1411
    put_be32(pb, 0x0 );
1412
    put_be32(pb, VideoCodec->bit_rate / 1000);
1413
    put_be32(pb, VideoCodec->bit_rate / 1000);
1414
    put_be32(pb, FrameRate);
1415
    put_be32(pb, FrameRate);
1416
    put_be16(pb, VideoCodec->width);
1417
    put_be16(pb, VideoCodec->height);
1418
    put_be32(pb, 0x010001); /* ? */
1419
}
1420

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

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

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

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

    
1446
    for(i=0; i<s->nb_streams; i++){
1447
        AVCodecContext *c= s->streams[i]->codec;
1448

    
1449
        if(c->codec_type == CODEC_TYPE_VIDEO){
1450
            av_set_pts_info(s->streams[i], 64, 1, c->time_base.den);
1451
            if (!codec_get_tag(codec_movvideo_tags, c->codec_id)){
1452
                if(!codec_get_tag(codec_bmp_tags, c->codec_id))
1453
                    return -1;
1454
                else
1455
                    av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, the file may be unplayable!\n");
1456
            }
1457
        }else if(c->codec_type == CODEC_TYPE_AUDIO){
1458
            av_set_pts_info(s->streams[i], 64, 1, c->sample_rate);
1459
            if (!codec_get_tag(codec_movaudio_tags, c->codec_id)){
1460
                if(!codec_get_tag(codec_wav_tags, c->codec_id))
1461
                    return -1;
1462
                else
1463
                    av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, the file may be unplayable!\n");
1464
            }
1465
        }
1466
        mov->tracks[i].language = ff_mov_iso639_to_lang(s->streams[i]->language, mov->mode != MODE_MOV);
1467
    }
1468

    
1469
    for (i=0; i<MAX_STREAMS; i++) {
1470
        mov->tracks[i].mode = mov->mode;
1471
    }
1472

    
1473
    put_flush_packet(pb);
1474

    
1475
    return 0;
1476
}
1477

    
1478
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1479
{
1480
    MOVContext *mov = s->priv_data;
1481
    ByteIOContext *pb = &s->pb;
1482
    AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
1483
    MOVTrack* trk = &mov->tracks[pkt->stream_index];
1484
    int cl, id;
1485
    unsigned int samplesInChunk = 0;
1486
    int size= pkt->size;
1487

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

    
1491
    if (enc->codec_type == CODEC_TYPE_VIDEO ) {
1492
        samplesInChunk = 1;
1493
    }
1494
    else if (enc->codec_type == CODEC_TYPE_AUDIO ) {
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
        }
1506
        else if(enc->codec_id == CODEC_ID_PCM_ALAW) {
1507
            samplesInChunk = size/enc->channels;
1508
        }
1509
        else if(enc->codec_id == CODEC_ID_PCM_S16BE || enc->codec_id == CODEC_ID_PCM_S16LE) {
1510
            samplesInChunk = size/(2*enc->channels);
1511
        }
1512
        else {
1513
            samplesInChunk = 1;
1514
        }
1515
    }
1516

    
1517
    if ((enc->codec_id == CODEC_ID_MPEG4 || enc->codec_id == CODEC_ID_AAC)
1518
        && trk->vosLen == 0) {
1519
//        assert(enc->extradata_size);
1520

    
1521
        trk->vosLen = enc->extradata_size;
1522
        trk->vosData = av_malloc(trk->vosLen);
1523
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1524
    }
1525

    
1526
    cl = trk->entry / MOV_INDEX_CLUSTER_SIZE;
1527
    id = trk->entry % MOV_INDEX_CLUSTER_SIZE;
1528

    
1529
    if (trk->ents_allocated <= trk->entry) {
1530
        trk->cluster = av_realloc(trk->cluster, (cl+1)*sizeof(void*));
1531
        if (!trk->cluster)
1532
            return -1;
1533
        trk->cluster[cl] = av_malloc(MOV_INDEX_CLUSTER_SIZE*sizeof(MOVIentry));
1534
        if (!trk->cluster[cl])
1535
            return -1;
1536
        trk->ents_allocated += MOV_INDEX_CLUSTER_SIZE;
1537
    }
1538
    if (mov->mdat_written == 0) {
1539
        mov_write_mdat_tag(pb, mov);
1540
        mov->mdat_written = 1;
1541
        mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1542
    }
1543

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

    
1561
    put_buffer(pb, pkt->data, size);
1562

    
1563
    put_flush_packet(pb);
1564
    return 0;
1565
}
1566

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

    
1575
    offset_t moov_pos = url_ftell(pb);
1576

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

    
1595
    mov_write_moov_tag(pb, mov, s);
1596

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

    
1604
        mov->tracks[i].cluster = NULL;
1605
        mov->tracks[i].ents_allocated = mov->tracks[i].entry = 0;
1606
    }
1607

    
1608
    put_flush_packet(pb);
1609

    
1610
    return res;
1611
}
1612

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

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

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

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

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

    
1683
int movenc_init(void)
1684
{
1685
    av_register_output_format(&mov_oformat);
1686
    av_register_output_format(&_3gp_oformat);
1687
    av_register_output_format(&mp4_oformat);
1688
    av_register_output_format(&psp_oformat);
1689
    av_register_output_format(&_3g2_oformat);
1690
    return 0;
1691
}