Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 1522767d

History | View | Annotate | Download (49.2 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
    { 0, 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
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') },
475
    { 0, 0 },
476
};
477

    
478
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
479
{
480
    offset_t pos = url_ftell(pb);
481
    char compressor_name[32];
482
    int tag;
483

    
484
    put_be32(pb, 0); /* size */
485

    
486
    tag = track->enc->codec_tag;
487
    if (!tag)
488
    tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
489
    // if no mac fcc found, try with Microsoft tags
490
    if (!tag)
491
        tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
492
    put_le32(pb, tag); // store it byteswapped
493

    
494
    put_be32(pb, 0); /* Reserved */
495
    put_be16(pb, 0); /* Reserved */
496
    put_be16(pb, 1); /* Data-reference index */
497

    
498
    put_be16(pb, 0); /* Codec stream version */
499
    put_be16(pb, 0); /* Codec stream revision (=0) */
500
    put_tag(pb, "FFMP"); /* Vendor */
501
    if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
502
        put_be32(pb, 0); /* Temporal Quality */
503
        put_be32(pb, 0x400); /* Spatial Quality = lossless*/
504
    } else {
505
        put_be32(pb, 0x200); /* Temporal Quality = normal */
506
        put_be32(pb, 0x200); /* Spatial Quality = normal */
507
    }
508
    put_be16(pb, track->enc->width); /* Video width */
509
    put_be16(pb, track->enc->height); /* Video height */
510
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
511
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
512
    put_be32(pb, 0); /* Data size (= 0) */
513
    put_be16(pb, 1); /* Frame count (= 1) */
514

    
515
    memset(compressor_name,0,32);
516
    if (track->enc->codec && track->enc->codec->name)
517
        strncpy(compressor_name,track->enc->codec->name,31);
518
    put_byte(pb, strlen(compressor_name));
519
    put_buffer(pb, compressor_name, 31);
520

    
521
    put_be16(pb, 0x18); /* Reserved */
522
    put_be16(pb, 0xffff); /* Reserved */
523
    if(track->enc->codec_id == CODEC_ID_MPEG4)
524
        mov_write_esds_tag(pb, track);
525
    else if(track->enc->codec_id == CODEC_ID_H263)
526
        mov_write_d263_tag(pb);
527
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
528
        mov_write_svq3_tag(pb);
529

    
530
    return updateSize (pb, pos);
531
}
532

    
533
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack* track)
534
{
535
    offset_t pos = url_ftell(pb);
536
    put_be32(pb, 0); /* size */
537
    put_tag(pb, "stsd");
538
    put_be32(pb, 0); /* version & flags */
539
    put_be32(pb, 1); /* entry count */
540
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
541
        mov_write_video_tag(pb, track);
542
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
543
        mov_write_audio_tag(pb, track);
544
    return updateSize(pb, pos);
545
}
546

    
547
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack* track)
548
{
549
    Time2Sample *ctts_entries;
550
    uint32_t entries = 0;
551
    uint32_t atom_size;
552
    int i;
553

    
554
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
555
    ctts_entries[0].count = 1;
556
    ctts_entries[0].duration = track->cluster[0][0].cts;
557
    for (i=1; i<track->entry; i++) {
558
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
559
        int id = i % MOV_INDEX_CLUSTER_SIZE;
560
        if (track->cluster[cl][id].cts == ctts_entries[entries].duration) {
561
            ctts_entries[entries].count++; /* compress */
562
        } else {
563
            entries++;
564
            ctts_entries[entries].duration = track->cluster[cl][id].cts;
565
            ctts_entries[entries].count = 1;
566
        }
567
    }
568
    entries++; /* last one */
569
    atom_size = 16 + (entries * 8);
570
    put_be32(pb, atom_size); /* size */
571
    put_tag(pb, "ctts");
572
    put_be32(pb, 0); /* version & flags */
573
    put_be32(pb, entries); /* entry count */
574
    for (i=0; i<entries; i++) {
575
        put_be32(pb, ctts_entries[i].count);
576
        put_be32(pb, ctts_entries[i].duration);
577
    }
578
    av_free(ctts_entries);
579
    return atom_size;
580
}
581

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

    
591
    put_be32(pb, track->sampleCount); /* sample count */
592
    put_be32(pb, track->sampleDuration); /* sample duration */
593
    return 0x18;
594
}
595

    
596
static int mov_write_dref_tag(ByteIOContext *pb)
597
{
598
    put_be32(pb, 28); /* size */
599
    put_tag(pb, "dref");
600
    put_be32(pb, 0); /* version & flags */
601
    put_be32(pb, 1); /* entry count */
602

    
603
    put_be32(pb, 0xc); /* size */
604
    put_tag(pb, "url ");
605
    put_be32(pb, 1); /* version & flags */
606

    
607
    return 28;
608
}
609

    
610
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track)
611
{
612
    offset_t pos = url_ftell(pb);
613
    put_be32(pb, 0); /* size */
614
    put_tag(pb, "stbl");
615
    mov_write_stsd_tag(pb, track);
616
    mov_write_stts_tag(pb, track);
617
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
618
        track->hasKeyframes)
619
        mov_write_stss_tag(pb, track);
620
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
621
        track->hasBframes)
622
        mov_write_ctts_tag(pb, track);
623
    mov_write_stsc_tag(pb, track);
624
    mov_write_stsz_tag(pb, track);
625
    mov_write_stco_tag(pb, track);
626
    return updateSize(pb, pos);
627
}
628

    
629
static int mov_write_dinf_tag(ByteIOContext *pb)
630
{
631
    offset_t pos = url_ftell(pb);
632
    put_be32(pb, 0); /* size */
633
    put_tag(pb, "dinf");
634
    mov_write_dref_tag(pb);
635
    return updateSize(pb, pos);
636
}
637

    
638
static int mov_write_smhd_tag(ByteIOContext *pb)
639
{
640
    put_be32(pb, 16); /* size */
641
    put_tag(pb, "smhd");
642
    put_be32(pb, 0); /* version & flags */
643
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
644
    put_be16(pb, 0); /* reserved */
645
    return 16;
646
}
647

    
648
static int mov_write_vmhd_tag(ByteIOContext *pb)
649
{
650
    put_be32(pb, 0x14); /* size (always 0x14) */
651
    put_tag(pb, "vmhd");
652
    put_be32(pb, 0x01); /* version & flags */
653
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
654
    return 0x14;
655
}
656

    
657
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack* track)
658
{
659
    char *descr, *hdlr, *hdlr_type;
660
    offset_t pos = url_ftell(pb);
661

    
662
    if (!track) { /* no media --> data handler */
663
        hdlr = "dhlr";
664
        hdlr_type = "url ";
665
        descr = "DataHandler";
666
    } else {
667
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
668
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
669
            hdlr_type = "vide";
670
            descr = "VideoHandler";
671
        } else {
672
            hdlr_type = "soun";
673
            descr = "SoundHandler";
674
        }
675
    }
676

    
677
    put_be32(pb, 0); /* size */
678
    put_tag(pb, "hdlr");
679
    put_be32(pb, 0); /* Version & flags */
680
    put_buffer(pb, hdlr, 4); /* handler */
681
    put_tag(pb, hdlr_type); /* handler type */
682
    put_be32(pb ,0); /* reserved */
683
    put_be32(pb ,0); /* reserved */
684
    put_be32(pb ,0); /* reserved */
685
    put_byte(pb, strlen(descr)); /* string counter */
686
    put_buffer(pb, descr, strlen(descr)); /* handler description */
687
    return updateSize(pb, pos);
688
}
689

    
690
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack* track)
691
{
692
    offset_t pos = url_ftell(pb);
693
    put_be32(pb, 0); /* size */
694
    put_tag(pb, "minf");
695
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
696
        mov_write_vmhd_tag(pb);
697
    else
698
        mov_write_smhd_tag(pb);
699
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
700
        mov_write_hdlr_tag(pb, NULL);
701
    mov_write_dinf_tag(pb);
702
    mov_write_stbl_tag(pb, track);
703
    return updateSize(pb, pos);
704
}
705

    
706
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack* track)
707
{
708
    put_be32(pb, 32); /* size */
709
    put_tag(pb, "mdhd");
710
    put_be32(pb, 0); /* Version & flags */
711
    put_be32(pb, track->time); /* creation time */
712
    put_be32(pb, track->time); /* modification time */
713
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
714
    put_be32(pb, track->trackDuration); /* duration */
715
    put_be16(pb, track->language); /* language */
716
    put_be16(pb, 0); /* reserved (quality) */
717
    return 32;
718
}
719

    
720
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack* track)
721
{
722
    offset_t pos = url_ftell(pb);
723
    put_be32(pb, 0); /* size */
724
    put_tag(pb, "mdia");
725
    mov_write_mdhd_tag(pb, track);
726
    mov_write_hdlr_tag(pb, track);
727
    mov_write_minf_tag(pb, track);
728
    return updateSize(pb, pos);
729
}
730

    
731
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)
732
{
733
    put_be32(pb, 0x5c); /* size (always 0x5c) */
734
    put_tag(pb, "tkhd");
735
    put_be32(pb, 0xf); /* version & flags (track enabled) */
736
    put_be32(pb, track->time); /* creation time */
737
    put_be32(pb, track->time); /* modification time */
738
    put_be32(pb, track->trackID); /* track-id */
739
    put_be32(pb, 0); /* reserved */
740
    put_be32(pb, av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP)); /* duration */
741

    
742
    put_be32(pb, 0); /* reserved */
743
    put_be32(pb, 0); /* reserved */
744
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
745
    /* Volume, only for audio */
746
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
747
        put_be16(pb, 0x0100);
748
    else
749
        put_be16(pb, 0);
750
    put_be16(pb, 0); /* reserved */
751

    
752
    /* Matrix structure */
753
    put_be32(pb, 0x00010000); /* reserved */
754
    put_be32(pb, 0x0); /* reserved */
755
    put_be32(pb, 0x0); /* reserved */
756
    put_be32(pb, 0x0); /* reserved */
757
    put_be32(pb, 0x00010000); /* reserved */
758
    put_be32(pb, 0x0); /* reserved */
759
    put_be32(pb, 0x0); /* reserved */
760
    put_be32(pb, 0x0); /* reserved */
761
    put_be32(pb, 0x40000000); /* reserved */
762

    
763
    /* Track width and height, for visual only */
764
    if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
765
        double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
766
        if( !sample_aspect_ratio ) sample_aspect_ratio = 1;
767
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
768
        put_be32(pb, track->enc->height*0x10000);
769
    }
770
    else {
771
        put_be32(pb, 0);
772
        put_be32(pb, 0);
773
    }
774
    return 0x5c;
775
}
776

    
777
// This box seems important for the psp playback ... without it the movie seems to hang
778
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
779
{
780
    put_be32(pb, 0x24); /* size  */
781
    put_tag(pb, "edts");
782
    put_be32(pb, 0x1c); /* size  */
783
    put_tag(pb, "elst");
784
    put_be32(pb, 0x0);
785
    put_be32(pb, 0x1);
786

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

    
789
    put_be32(pb, 0x0);
790
    put_be32(pb, 0x00010000);
791
    return 0x24;
792
}
793

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

    
813
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack* track)
814
{
815
    offset_t pos = url_ftell(pb);
816
    put_be32(pb, 0); /* size */
817
    put_tag(pb, "trak");
818
    mov_write_tkhd_tag(pb, track);
819
    if (track->mode == MODE_PSP)
820
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
821
    mov_write_mdia_tag(pb, track);
822
    if (track->mode == MODE_PSP)
823
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
824
    return updateSize(pb, pos);
825
}
826

    
827
#if 0
828
/* TODO: Not sorted out, but not necessary either */
829
static int mov_write_iods_tag(ByteIOContext *pb, MOVContext *mov)
830
{
831
    put_be32(pb, 0x15); /* size */
832
    put_tag(pb, "iods");
833
    put_be32(pb, 0);    /* version & flags */
834
    put_be16(pb, 0x1007);
835
    put_byte(pb, 0);
836
    put_be16(pb, 0x4fff);
837
    put_be16(pb, 0xfffe);
838
    put_be16(pb, 0x01ff);
839
    return 0x15;
840
}
841
#endif
842

    
843
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
844
{
845
    int maxTrackID = 1, i;
846
    int64_t maxTrackLenTemp, maxTrackLen = 0;
847

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

    
865
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
866
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
867
    put_be16(pb, 0); /* reserved */
868
    put_be32(pb, 0); /* reserved */
869
    put_be32(pb, 0); /* reserved */
870

    
871
    /* Matrix structure */
872
    put_be32(pb, 0x00010000); /* reserved */
873
    put_be32(pb, 0x0); /* reserved */
874
    put_be32(pb, 0x0); /* reserved */
875
    put_be32(pb, 0x0); /* reserved */
876
    put_be32(pb, 0x00010000); /* reserved */
877
    put_be32(pb, 0x0); /* reserved */
878
    put_be32(pb, 0x0); /* reserved */
879
    put_be32(pb, 0x0); /* reserved */
880
    put_be32(pb, 0x40000000); /* reserved */
881

    
882
    put_be32(pb, 0); /* reserved (preview time) */
883
    put_be32(pb, 0); /* reserved (preview duration) */
884
    put_be32(pb, 0); /* reserved (poster time) */
885
    put_be32(pb, 0); /* reserved (selection time) */
886
    put_be32(pb, 0); /* reserved (selection duration) */
887
    put_be32(pb, 0); /* reserved (current time) */
888
    put_be32(pb, maxTrackID+1); /* Next track id */
889
    return 0x6c;
890
}
891

    
892
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVContext* mov,
893
                                     AVFormatContext *s)
894
{
895
    offset_t pos = url_ftell(pb);
896
    put_be32(pb, 0); /* size */
897
    put_tag(pb, "hdlr");
898
    put_be32(pb, 0);
899
    put_be32(pb, 0);
900
    put_tag(pb, "mdir");
901
    put_tag(pb, "appl");
902
    put_be32(pb, 0);
903
    put_be32(pb, 0);
904
    put_be16(pb, 0);
905
    return updateSize(pb, pos);
906
}
907

    
908
/* helper function to write a data tag with the specified string as data */
909
static int mov_write_string_data_tag(ByteIOContext *pb, MOVContext* mov,
910
                                     AVFormatContext *s, const char *data)
911
{
912
    offset_t pos = url_ftell(pb);
913
    put_be32(pb, 0); /* size */
914
    put_tag(pb, "data");
915
    put_be32(pb, 1);
916
    put_be32(pb, 0);
917
    put_buffer(pb, data, strlen(data));
918
    return updateSize(pb, pos);
919
}
920

    
921
/* iTunes name of the song/movie */
922
static int mov_write_nam_tag(ByteIOContext *pb, MOVContext* mov,
923
                             AVFormatContext *s)
924
{
925
    int size = 0;
926
    if ( s->title[0] ) {
927
        offset_t pos = url_ftell(pb);
928
        put_be32(pb, 0); /* size */
929
        put_tag(pb, "\251nam");
930
        mov_write_string_data_tag(pb, mov, s, s->title);
931
        size = updateSize(pb, pos);
932
    }
933
    return size;
934
}
935

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

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

    
967
/* iTunes name of the album */
968
static int mov_write_alb_tag(ByteIOContext *pb, MOVContext* mov,
969
                             AVFormatContext *s)
970
{
971
    int size = 0;
972
    if ( s->album[0] ) {
973
        offset_t pos = url_ftell(pb);
974
        put_be32(pb, 0); /* size */
975
        put_tag(pb, "\251alb");
976
        mov_write_string_data_tag(pb, mov, s, s->album);
977
        size = updateSize(pb, pos);
978
    }
979
    return size;
980
}
981

    
982
/* iTunes year */
983
static int mov_write_day_tag(ByteIOContext *pb, MOVContext* mov,
984
                             AVFormatContext *s)
985
{
986
    char year[5];
987
    int size = 0;
988
    if ( s->year ) {
989
        offset_t pos = url_ftell(pb);
990
        put_be32(pb, 0); /* size */
991
        put_tag(pb, "\251day");
992
        snprintf(year, 5, "%04d", s->year);
993
        mov_write_string_data_tag(pb, mov, s, year);
994
        size = updateSize(pb, pos);
995
    }
996
    return size;
997
}
998

    
999
/* iTunes tool used to create the file */
1000
static int mov_write_too_tag(ByteIOContext *pb, MOVContext* mov,
1001
                             AVFormatContext *s)
1002
{
1003
    offset_t pos = url_ftell(pb);
1004
    put_be32(pb, 0); /* size */
1005
    put_tag(pb, "\251too");
1006
    mov_write_string_data_tag(pb, mov, s, LIBAVFORMAT_IDENT);
1007
    return updateSize(pb, pos);
1008
}
1009

    
1010
/* iTunes comment */
1011
static int mov_write_cmt_tag(ByteIOContext *pb, MOVContext* mov,
1012
                             AVFormatContext *s)
1013
{
1014
    int size = 0;
1015
    if ( s->comment[0] ) {
1016
        offset_t pos = url_ftell(pb);
1017
        put_be32(pb, 0); /* size */
1018
        put_tag(pb, "\251cmt");
1019
        mov_write_string_data_tag(pb, mov, s, s->comment);
1020
        size = updateSize(pb, pos);
1021
    }
1022
    return size;
1023
}
1024

    
1025
/* iTunes custom genre */
1026
static int mov_write_gen_tag(ByteIOContext *pb, MOVContext* mov,
1027
                             AVFormatContext *s)
1028
{
1029
    int size = 0;
1030
    if ( s->genre[0] ) {
1031
        offset_t pos = url_ftell(pb);
1032
        put_be32(pb, 0); /* size */
1033
        put_tag(pb, "\251gen");
1034
        mov_write_string_data_tag(pb, mov, s, s->genre);
1035
        size = updateSize(pb, pos);
1036
    }
1037
    return size;
1038
}
1039

    
1040
/* iTunes track number */
1041
static int mov_write_trkn_tag(ByteIOContext *pb, MOVContext* mov,
1042
                              AVFormatContext *s)
1043
{
1044
    int size = 0;
1045
    if ( s->track ) {
1046
        offset_t pos = url_ftell(pb);
1047
        put_be32(pb, 0); /* size */
1048
        put_tag(pb, "trkn");
1049
        {
1050
            offset_t pos = url_ftell(pb);
1051
            put_be32(pb, 0); /* size */
1052
            put_tag(pb, "data");
1053
            put_be32(pb, 0);        // 8 bytes empty
1054
            put_be32(pb, 0);
1055
            put_be16(pb, 0);        // empty
1056
            put_be16(pb, s->track); // track number
1057
            put_be16(pb, 0);        // total track number
1058
            put_be16(pb, 0);        // empty
1059
            updateSize(pb, pos);
1060
        }
1061
        size = updateSize(pb, pos);
1062
    }
1063
    return size;
1064
}
1065

    
1066
/* iTunes meta data list */
1067
static int mov_write_ilst_tag(ByteIOContext *pb, MOVContext* mov,
1068
                              AVFormatContext *s)
1069
{
1070
    offset_t pos = url_ftell(pb);
1071
    put_be32(pb, 0); /* size */
1072
    put_tag(pb, "ilst");
1073
    mov_write_nam_tag(pb, mov, s);
1074
    mov_write_ART_tag(pb, mov, s);
1075
    mov_write_wrt_tag(pb, mov, s);
1076
    mov_write_alb_tag(pb, mov, s);
1077
    mov_write_day_tag(pb, mov, s);
1078
    mov_write_too_tag(pb, mov, s);
1079
    mov_write_cmt_tag(pb, mov, s);
1080
    mov_write_gen_tag(pb, mov, s);
1081
    mov_write_trkn_tag(pb, mov, s);
1082
    return updateSize(pb, pos);
1083
}
1084

    
1085
/* iTunes meta data tag */
1086
static int mov_write_meta_tag(ByteIOContext *pb, MOVContext* mov,
1087
                              AVFormatContext *s)
1088
{
1089
    int size = 0;
1090

    
1091
    // only save meta tag if required
1092
    if ( s->title[0] || s->author[0] || s->album[0] || s->year ||
1093
         s->comment[0] || s->genre[0] || s->track ) {
1094
        offset_t pos = url_ftell(pb);
1095
        put_be32(pb, 0); /* size */
1096
        put_tag(pb, "meta");
1097
        put_be32(pb, 0);
1098
        mov_write_itunes_hdlr_tag(pb, mov, s);
1099
        mov_write_ilst_tag(pb, mov, s);
1100
        size = updateSize(pb, pos);
1101
    }
1102
    return size;
1103
}
1104

    
1105
static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1106
                              AVFormatContext *s)
1107
{
1108
    offset_t pos = url_ftell(pb);
1109
    int i;
1110

    
1111
    put_be32(pb, 0); /* size */
1112
    put_tag(pb, "udta");
1113

    
1114
    /* iTunes meta data */
1115
    mov_write_meta_tag(pb, mov, s);
1116

    
1117
    /* Requirements */
1118
    for (i=0; i<MAX_STREAMS; i++) {
1119
        if(mov->tracks[i].entry <= 0) continue;
1120
        if (mov->tracks[i].enc->codec_id == CODEC_ID_AAC ||
1121
            mov->tracks[i].enc->codec_id == CODEC_ID_MPEG4) {
1122
            offset_t pos = url_ftell(pb);
1123
            put_be32(pb, 0); /* size */
1124
            put_tag(pb, "\251req");
1125
            put_be16(pb, sizeof("QuickTime 6.0 or greater") - 1);
1126
            put_be16(pb, 0);
1127
            put_buffer(pb, "QuickTime 6.0 or greater",
1128
                       sizeof("QuickTime 6.0 or greater") - 1);
1129
            updateSize(pb, pos);
1130
            break;
1131
        }
1132
    }
1133

    
1134
    /* Encoder */
1135
    if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1136
    {
1137
        offset_t pos = url_ftell(pb);
1138
        put_be32(pb, 0); /* size */
1139
        put_tag(pb, "\251enc");
1140
        put_be16(pb, sizeof(LIBAVFORMAT_IDENT) - 1); /* string length */
1141
        put_be16(pb, 0);
1142
        put_buffer(pb, LIBAVFORMAT_IDENT, sizeof(LIBAVFORMAT_IDENT) - 1);
1143
        updateSize(pb, pos);
1144
    }
1145

    
1146
    if( s->title[0] )
1147
    {
1148
        offset_t pos = url_ftell(pb);
1149
        put_be32(pb, 0); /* size */
1150
        put_tag(pb, "\251nam");
1151
        put_be16(pb, strlen(s->title)); /* string length */
1152
        put_be16(pb, 0);
1153
        put_buffer(pb, s->title, strlen(s->title));
1154
        updateSize(pb, pos);
1155
    }
1156

    
1157
    if( s->author[0] )
1158
    {
1159
        offset_t pos = url_ftell(pb);
1160
        put_be32(pb, 0); /* size */
1161
        put_tag(pb, /*"\251aut"*/ "\251day" );
1162
        put_be16(pb, strlen(s->author)); /* string length */
1163
        put_be16(pb, 0);
1164
        put_buffer(pb, s->author, strlen(s->author));
1165
        updateSize(pb, pos);
1166
    }
1167

    
1168
    if( s->comment[0] )
1169
    {
1170
        offset_t pos = url_ftell(pb);
1171
        put_be32(pb, 0); /* size */
1172
        put_tag(pb, "\251des");
1173
        put_be16(pb, strlen(s->comment)); /* string length */
1174
        put_be16(pb, 0);
1175
        put_buffer(pb, s->comment, strlen(s->comment));
1176
        updateSize(pb, pos);
1177
    }
1178

    
1179
    return updateSize(pb, pos);
1180
}
1181

    
1182

    
1183
static size_t ascii_to_wc (ByteIOContext *pb, char *b, size_t n)
1184
{
1185
    size_t i;
1186
    unsigned char c;
1187
    for (i = 0; i < n - 1; i++) {
1188
        c = b[i];
1189
        if (! (0x20 <= c && c <= 0x7f ))
1190
            c = 0x3f;  /* '?' */
1191
        put_be16(pb, c);
1192
    }
1193
    put_be16(pb, 0x00);
1194
    return 2*n;
1195
}
1196

    
1197
static uint16_t language_code (char *str)
1198
{
1199
    return ((((str[0]-'a') & 0x1F)<<10) + (((str[1]-'a') & 0x1F)<<5) + ((str[2]-'a') & 0x1F));
1200
}
1201

    
1202
static int mov_write_uuidusmt_tag (ByteIOContext *pb, AVFormatContext *s)
1203
{
1204
    size_t len, size;
1205
    offset_t pos, curpos;
1206

    
1207
    size = 0;
1208
    if (s->title[0]) {
1209
        pos = url_ftell(pb);
1210
        put_be32(pb, 0); /* size placeholder*/
1211
        put_tag(pb, "uuid");
1212
        put_tag(pb, "USMT");
1213
        put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1214
        put_be32(pb, 0xbb88695c );
1215
        put_be32(pb, 0xfac9c740 );
1216
        size += 24;
1217

    
1218
        put_be32(pb, 0); /* size placeholder*/
1219
        put_tag(pb, "MTDT");
1220
        put_be16(pb, 1);
1221
        size += 10;
1222

    
1223
        // Title
1224
        len = strlen(s->title)+1;
1225
        put_be16(pb, len*2+10);             /* size */
1226
        put_be32(pb, 0x01);                 /* type */
1227
        put_be16(pb, language_code("und")); /* language */
1228
        put_be16(pb, 0x01);                 /* ? */
1229
        ascii_to_wc (pb, s->title, len);
1230
        size += len*2+10;
1231

    
1232
        // size
1233
        curpos = url_ftell(pb);
1234
        url_fseek(pb, pos, SEEK_SET);
1235
        put_be32(pb, size);
1236
        url_fseek(pb, pos+24, SEEK_SET);
1237
        put_be32(pb, size-24);
1238
        url_fseek(pb, curpos, SEEK_SET);
1239
    }
1240

    
1241
    return size;
1242
}
1243

    
1244
static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1245
                              AVFormatContext *s)
1246
{
1247
    int i;
1248
    offset_t pos = url_ftell(pb);
1249
    put_be32(pb, 0); /* size placeholder*/
1250
    put_tag(pb, "moov");
1251
    mov->timescale = globalTimescale;
1252

    
1253
    for (i=0; i<MAX_STREAMS; i++) {
1254
        if(mov->tracks[i].entry <= 0) continue;
1255

    
1256
        if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {
1257
            mov->tracks[i].timescale = mov->tracks[i].enc->time_base.den;
1258
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->time_base.num;
1259
        }
1260
        else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {
1261
            /* If AMR, track timescale = 8000, AMR_WB = 16000 */
1262
            if(mov->tracks[i].enc->codec_id == CODEC_ID_AMR_NB) {
1263
                mov->tracks[i].sampleDuration = 160;  // Bytes per chunk
1264
                mov->tracks[i].timescale = 8000;
1265
            }
1266
            else {
1267
                mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;
1268
                mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;
1269
            }
1270
        }
1271

    
1272
        mov->tracks[i].trackDuration =
1273
            mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;
1274
        mov->tracks[i].time = mov->time;
1275
        mov->tracks[i].trackID = i+1;
1276
    }
1277

    
1278
    mov_write_mvhd_tag(pb, mov);
1279
    //mov_write_iods_tag(pb, mov);
1280
    for (i=0; i<MAX_STREAMS; i++) {
1281
        if(mov->tracks[i].entry > 0) {
1282
            mov_write_trak_tag(pb, &(mov->tracks[i]));
1283
        }
1284
    }
1285

    
1286
    if (mov->mode == MODE_PSP)
1287
        mov_write_uuidusmt_tag(pb, s);
1288
    else
1289
    mov_write_udta_tag(pb, mov, s);
1290

    
1291
    return updateSize(pb, pos);
1292
}
1293

    
1294
int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1295
{
1296
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1297
    put_tag(pb, "wide");
1298

    
1299
    mov->mdat_pos = url_ftell(pb);
1300
    put_be32(pb, 0); /* size placeholder*/
1301
    put_tag(pb, "mdat");
1302
    return 0;
1303
}
1304

    
1305
/* TODO: This needs to be more general */
1306
static void mov_write_ftyp_tag (ByteIOContext *pb, AVFormatContext *s)
1307
{
1308
    MOVContext *mov = s->priv_data;
1309

    
1310
    put_be32(pb, 0x14 ); /* size */
1311
    put_tag(pb, "ftyp");
1312

    
1313
    if ( mov->mode == MODE_3GP )
1314
        put_tag(pb, "3gp4");
1315
    else if ( mov->mode == MODE_3G2 )
1316
        put_tag(pb, "3g2a");
1317
    else if ( mov->mode == MODE_PSP )
1318
        put_tag(pb, "MSNV");
1319
    else
1320
        put_tag(pb, "isom");
1321

    
1322
    put_be32(pb, 0x200 );
1323

    
1324
    if ( mov->mode == MODE_3GP )
1325
        put_tag(pb, "3gp4");
1326
    else if ( mov->mode == MODE_3G2 )
1327
        put_tag(pb, "3g2a");
1328
    else if ( mov->mode == MODE_PSP )
1329
        put_tag(pb, "MSNV");
1330
    else
1331
        put_tag(pb, "mp41");
1332
}
1333

    
1334
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1335
{
1336
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1337
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1338
    int AudioRate = AudioCodec->sample_rate;
1339
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1340

    
1341
    put_be32(pb, 0x94 ); /* size */
1342
    put_tag(pb, "uuid");
1343
    put_tag(pb, "PROF");
1344

    
1345
    put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1346
    put_be32(pb, 0xbb88695c );
1347
    put_be32(pb, 0xfac9c740 );
1348

    
1349
    put_be32(pb, 0x0 );  /* ? */
1350
    put_be32(pb, 0x3 );  /* 3 sections ? */
1351

    
1352
    put_be32(pb, 0x14 ); /* size */
1353
    put_tag(pb, "FPRF");
1354
    put_be32(pb, 0x0 );  /* ? */
1355
    put_be32(pb, 0x0 );  /* ? */
1356
    put_be32(pb, 0x0 );  /* ? */
1357

    
1358
    put_be32(pb, 0x2c );  /* size */
1359
    put_tag(pb, "APRF");   /* audio */
1360
    put_be32(pb, 0x0 );
1361
    put_be32(pb, 0x2 );   /* TrackID */
1362
    put_tag(pb, "mp4a");
1363
    put_be32(pb, 0x20f );
1364
    put_be32(pb, 0x0 );
1365
    put_be32(pb, AudioCodec->bit_rate / 1000);
1366
    put_be32(pb, AudioCodec->bit_rate / 1000);
1367
    put_be32(pb, AudioRate );
1368
    put_be32(pb, AudioCodec->channels );
1369

    
1370
    put_be32(pb, 0x34 );  /* size */
1371
    put_tag(pb, "VPRF");   /* video */
1372
    put_be32(pb, 0x0 );
1373
    put_be32(pb, 0x1 );    /* TrackID */
1374
    put_tag(pb, "mp4v");
1375
    put_be32(pb, 0x103 );
1376
    put_be32(pb, 0x0 );
1377
    put_be32(pb, VideoCodec->bit_rate / 1000);
1378
    put_be32(pb, VideoCodec->bit_rate / 1000);
1379
    put_be32(pb, FrameRate);
1380
    put_be32(pb, FrameRate);
1381
    put_be16(pb, VideoCodec->width);
1382
    put_be16(pb, VideoCodec->height);
1383
    put_be32(pb, 0x010001); /* ? */
1384
}
1385

    
1386
static int mov_write_header(AVFormatContext *s)
1387
{
1388
    ByteIOContext *pb = &s->pb;
1389
    MOVContext *mov = s->priv_data;
1390
    int i;
1391

    
1392
    /* Default mode == MP4 */
1393
    mov->mode = MODE_MP4;
1394

    
1395
    if (s->oformat != NULL) {
1396
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1397
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3G2;
1398
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1399
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1400

    
1401
        if ( mov->mode == MODE_3GP || mov->mode == MODE_3G2 ||
1402
             mov->mode == MODE_MP4 || mov->mode == MODE_PSP )
1403
            mov_write_ftyp_tag(pb,s);
1404
        if ( mov->mode == MODE_PSP ) {
1405
            if ( s->nb_streams != 2 ) {
1406
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1407
                return -1;
1408
            }
1409
            mov_write_uuidprof_tag(pb,s);
1410
        }
1411
    }
1412

    
1413
    for(i=0; i<s->nb_streams; i++){
1414
        AVCodecContext *c= s->streams[i]->codec;
1415

    
1416
        if(c->codec_type == CODEC_TYPE_VIDEO){
1417
            av_set_pts_info(s->streams[i], 64, 1, c->time_base.den);
1418
            if (!codec_get_tag(codec_movvideo_tags, c->codec_id)){
1419
                if(!codec_get_tag(codec_bmp_tags, c->codec_id))
1420
                    return -1;
1421
                else
1422
                    av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, the file may be unplayable!\n");
1423
            }
1424
        }else if(c->codec_type == CODEC_TYPE_AUDIO){
1425
            av_set_pts_info(s->streams[i], 64, 1, c->sample_rate);
1426
            if (!codec_get_tag(codec_movaudio_tags, c->codec_id)){
1427
                if(!codec_get_tag(codec_wav_tags, c->codec_id))
1428
                    return -1;
1429
                else
1430
                    av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, the file may be unplayable!\n");
1431
            }
1432
        }
1433
        mov->tracks[i].language = ff_mov_iso639_to_lang(s->streams[i]->language, mov->mode != MODE_MOV);
1434
    }
1435

    
1436
    for (i=0; i<MAX_STREAMS; i++) {
1437
        mov->tracks[i].mode = mov->mode;
1438
    }
1439

    
1440
    put_flush_packet(pb);
1441

    
1442
    return 0;
1443
}
1444

    
1445
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1446
{
1447
    MOVContext *mov = s->priv_data;
1448
    ByteIOContext *pb = &s->pb;
1449
    AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
1450
    MOVTrack* trk = &mov->tracks[pkt->stream_index];
1451
    int cl, id;
1452
    unsigned int samplesInChunk = 0;
1453
    int size= pkt->size;
1454

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

    
1458
    if (enc->codec_type == CODEC_TYPE_VIDEO ) {
1459
        samplesInChunk = 1;
1460
    }
1461
    else if (enc->codec_type == CODEC_TYPE_AUDIO ) {
1462
        if( enc->codec_id == CODEC_ID_AMR_NB) {
1463
            /* We must find out how many AMR blocks there are in one packet */
1464
            static uint16_t packed_size[16] =
1465
                {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1466
            int len = 0;
1467

    
1468
            while (len < size && samplesInChunk < 100) {
1469
                len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1470
                samplesInChunk++;
1471
            }
1472
        }
1473
        else if(enc->codec_id == CODEC_ID_PCM_ALAW) {
1474
            samplesInChunk = size/enc->channels;
1475
        }
1476
        else if(enc->codec_id == CODEC_ID_PCM_S16BE || enc->codec_id == CODEC_ID_PCM_S16LE) {
1477
            samplesInChunk = size/(2*enc->channels);
1478
        }
1479
        else {
1480
            samplesInChunk = 1;
1481
        }
1482
    }
1483

    
1484
    if ((enc->codec_id == CODEC_ID_MPEG4 || enc->codec_id == CODEC_ID_AAC)
1485
        && trk->vosLen == 0) {
1486
//        assert(enc->extradata_size);
1487

    
1488
        trk->vosLen = enc->extradata_size;
1489
        trk->vosData = av_malloc(trk->vosLen);
1490
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1491
    }
1492

    
1493
    cl = trk->entry / MOV_INDEX_CLUSTER_SIZE;
1494
    id = trk->entry % MOV_INDEX_CLUSTER_SIZE;
1495

    
1496
    if (trk->ents_allocated <= trk->entry) {
1497
        trk->cluster = av_realloc(trk->cluster, (cl+1)*sizeof(void*));
1498
        if (!trk->cluster)
1499
            return -1;
1500
        trk->cluster[cl] = av_malloc(MOV_INDEX_CLUSTER_SIZE*sizeof(MOVIentry));
1501
        if (!trk->cluster[cl])
1502
            return -1;
1503
        trk->ents_allocated += MOV_INDEX_CLUSTER_SIZE;
1504
    }
1505
    if (mov->mdat_written == 0) {
1506
        mov_write_mdat_tag(pb, mov);
1507
        mov->mdat_written = 1;
1508
        mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1509
    }
1510

    
1511
    trk->cluster[cl][id].pos = url_ftell(pb);
1512
    trk->cluster[cl][id].samplesInChunk = samplesInChunk;
1513
    trk->cluster[cl][id].size = size;
1514
    trk->cluster[cl][id].entries = samplesInChunk;
1515
    if(enc->codec_type == CODEC_TYPE_VIDEO) {
1516
        if (pkt->dts != pkt->pts)
1517
            trk->hasBframes = 1;
1518
        trk->cluster[cl][id].cts = pkt->pts - pkt->dts;
1519
        trk->cluster[cl][id].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1520
        if(trk->cluster[cl][id].key_frame)
1521
            trk->hasKeyframes = 1;
1522
    }
1523
    trk->enc = enc;
1524
    trk->entry++;
1525
    trk->sampleCount += samplesInChunk;
1526
    trk->mdat_size += size;
1527

    
1528
    put_buffer(pb, pkt->data, size);
1529

    
1530
    put_flush_packet(pb);
1531
    return 0;
1532
}
1533

    
1534
static int mov_write_trailer(AVFormatContext *s)
1535
{
1536
    MOVContext *mov = s->priv_data;
1537
    ByteIOContext *pb = &s->pb;
1538
    int res = 0;
1539
    int i;
1540
    uint64_t j;
1541

    
1542
    offset_t moov_pos = url_ftell(pb);
1543

    
1544
    /* Write size of mdat tag */
1545
    for (i=0, j=0; i<MAX_STREAMS; i++) {
1546
        if(mov->tracks[i].ents_allocated > 0) {
1547
            j += mov->tracks[i].mdat_size;
1548
        }
1549
    }
1550
    if (j+8 <= UINT32_MAX) {
1551
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
1552
        put_be32(pb, j+8);
1553
    } else {
1554
        /* overwrite 'wide' placeholder atom */
1555
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1556
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1557
        put_tag(pb, "mdat");
1558
        put_be64(pb, j+16);
1559
    }
1560
    url_fseek(pb, moov_pos, SEEK_SET);
1561

    
1562
    mov_write_moov_tag(pb, mov, s);
1563

    
1564
    for (i=0; i<MAX_STREAMS; i++) {
1565
        for (j=0; j<mov->tracks[i].ents_allocated/MOV_INDEX_CLUSTER_SIZE; j++) {
1566
            av_free(mov->tracks[i].cluster[j]);
1567
        }
1568
        av_free(mov->tracks[i].cluster);
1569
        if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1570

    
1571
        mov->tracks[i].cluster = NULL;
1572
        mov->tracks[i].ents_allocated = mov->tracks[i].entry = 0;
1573
    }
1574

    
1575
    put_flush_packet(pb);
1576

    
1577
    return res;
1578
}
1579

    
1580
static AVOutputFormat mov_oformat = {
1581
    "mov",
1582
    "mov format",
1583
    NULL,
1584
    "mov",
1585
    sizeof(MOVContext),
1586
    CODEC_ID_AAC,
1587
    CODEC_ID_MPEG4,
1588
    mov_write_header,
1589
    mov_write_packet,
1590
    mov_write_trailer,
1591
    .flags = AVFMT_GLOBALHEADER,
1592
};
1593

    
1594
static AVOutputFormat _3gp_oformat = {
1595
    "3gp",
1596
    "3gp format",
1597
    NULL,
1598
    "3gp",
1599
    sizeof(MOVContext),
1600
    CODEC_ID_AMR_NB,
1601
    CODEC_ID_H263,
1602
    mov_write_header,
1603
    mov_write_packet,
1604
    mov_write_trailer,
1605
    .flags = AVFMT_GLOBALHEADER,
1606
};
1607

    
1608
static AVOutputFormat mp4_oformat = {
1609
    "mp4",
1610
    "mp4 format",
1611
    "application/mp4",
1612
    "mp4,m4a",
1613
    sizeof(MOVContext),
1614
    CODEC_ID_AAC,
1615
    CODEC_ID_MPEG4,
1616
    mov_write_header,
1617
    mov_write_packet,
1618
    mov_write_trailer,
1619
    .flags = AVFMT_GLOBALHEADER,
1620
};
1621

    
1622
static AVOutputFormat psp_oformat = {
1623
    "psp",
1624
    "psp mp4 format",
1625
    NULL,
1626
    "mp4,psp",
1627
    sizeof(MOVContext),
1628
    CODEC_ID_AAC,
1629
    CODEC_ID_MPEG4,
1630
    mov_write_header,
1631
    mov_write_packet,
1632
    mov_write_trailer,
1633
    .flags = AVFMT_GLOBALHEADER,
1634
};
1635

    
1636
static AVOutputFormat _3g2_oformat = {
1637
    "3g2",
1638
    "3gp2 format",
1639
    NULL,
1640
    "3g2",
1641
    sizeof(MOVContext),
1642
    CODEC_ID_AMR_NB,
1643
    CODEC_ID_H263,
1644
    mov_write_header,
1645
    mov_write_packet,
1646
    mov_write_trailer,
1647
    .flags = AVFMT_GLOBALHEADER,
1648
};
1649

    
1650
int movenc_init(void)
1651
{
1652
    av_register_output_format(&mov_oformat);
1653
    av_register_output_format(&_3gp_oformat);
1654
    av_register_output_format(&mp4_oformat);
1655
    av_register_output_format(&psp_oformat);
1656
    av_register_output_format(&_3g2_oformat);
1657
    return 0;
1658
}