Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ dcfdb046

History | View | Annotate | Download (48.3 KB)

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

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

    
27
#define MOV_INDEX_CLUSTER_SIZE 16384
28
#define globalTimescale 1000
29

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

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

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

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

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

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

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

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

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

    
108
    return curpos - pos;
109
}
110

    
111
/* Chunk offset atom */
112
static int mov_write_stco_tag(ByteIOContext *pb, MOVTrack* track)
113
{
114
    int i;
115
    int mode64 = 0; //   use 32 bit size variant if possible
116
    offset_t pos = url_ftell(pb);
117
    put_be32(pb, 0); /* size */
118
    if (pos > UINT32_MAX) {
119
        mode64 = 1;
120
        put_tag(pb, "co64");
121
    } else
122
        put_tag(pb, "stco");
123
    put_be32(pb, 0); /* version & flags */
124
    put_be32(pb, track->entry); /* entry count */
125
    for (i=0; i<track->entry; i++) {
126
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
127
        int id = i % MOV_INDEX_CLUSTER_SIZE;
128
        if(mode64 == 1)
129
            put_be64(pb, track->cluster[cl][id].pos);
130
        else
131
            put_be32(pb, track->cluster[cl][id].pos);
132
    }
133
    return updateSize (pb, pos);
134
}
135

    
136
/* Sample size atom */
137
static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack* track)
138
{
139
    int equalChunks = 1;
140
    int i, j, entries = 0, tst = -1, oldtst = -1;
141

    
142
    offset_t pos = url_ftell(pb);
143
    put_be32(pb, 0); /* size */
144
    put_tag(pb, "stsz");
145
    put_be32(pb, 0); /* version & flags */
146

    
147
    for (i=0; i<track->entry; i++) {
148
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
149
        int id = i % MOV_INDEX_CLUSTER_SIZE;
150
        tst = track->cluster[cl][id].size/track->cluster[cl][id].entries;
151
        if(oldtst != -1 && tst != oldtst) {
152
            equalChunks = 0;
153
        }
154
        oldtst = tst;
155
        entries += track->cluster[cl][id].entries;
156
    }
157
    if (equalChunks) {
158
        int sSize = track->cluster[0][0].size/track->cluster[0][0].entries;
159
        put_be32(pb, sSize); // sample size
160
        put_be32(pb, entries); // sample count
161
    }
162
    else {
163
        put_be32(pb, 0); // sample size
164
        put_be32(pb, entries); // sample count
165
        for (i=0; i<track->entry; i++) {
166
            int cl = i / MOV_INDEX_CLUSTER_SIZE;
167
            int id = i % MOV_INDEX_CLUSTER_SIZE;
168
            for ( j=0; j<track->cluster[cl][id].entries; j++) {
169
                put_be32(pb, track->cluster[cl][id].size /
170
                         track->cluster[cl][id].entries);
171
            }
172
        }
173
    }
174
    return updateSize (pb, pos);
175
}
176

    
177
/* Sample to chunk atom */
178
static int mov_write_stsc_tag(ByteIOContext *pb, MOVTrack* track)
179
{
180
    int index = 0, oldval = -1, i;
181
    offset_t entryPos, curpos;
182

    
183
    offset_t pos = url_ftell(pb);
184
    put_be32(pb, 0); /* size */
185
    put_tag(pb, "stsc");
186
    put_be32(pb, 0); // version & flags
187
    entryPos = url_ftell(pb);
188
    put_be32(pb, track->entry); // entry count
189
    for (i=0; i<track->entry; i++) {
190
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
191
        int id = i % MOV_INDEX_CLUSTER_SIZE;
192
        if(oldval != track->cluster[cl][id].samplesInChunk)
193
        {
194
            put_be32(pb, i+1); // first chunk
195
            put_be32(pb, track->cluster[cl][id].samplesInChunk); // samples per chunk
196
            put_be32(pb, 0x1); // sample description index
197
            oldval = track->cluster[cl][id].samplesInChunk;
198
            index++;
199
        }
200
    }
201
    curpos = url_ftell(pb);
202
    url_fseek(pb, entryPos, SEEK_SET);
203
    put_be32(pb, index); // rewrite size
204
    url_fseek(pb, curpos, SEEK_SET);
205

    
206
    return updateSize (pb, pos);
207
}
208

    
209
/* Sync sample atom */
210
static int mov_write_stss_tag(ByteIOContext *pb, MOVTrack* track)
211
{
212
    offset_t curpos, entryPos;
213
    int i, index = 0;
214
    offset_t pos = url_ftell(pb);
215
    put_be32(pb, 0); // size
216
    put_tag(pb, "stss");
217
    put_be32(pb, 0); // version & flags
218
    entryPos = url_ftell(pb);
219
    put_be32(pb, track->entry); // entry count
220
    for (i=0; i<track->entry; i++) {
221
        int cl = i / MOV_INDEX_CLUSTER_SIZE;
222
        int id = i % MOV_INDEX_CLUSTER_SIZE;
223
        if(track->cluster[cl][id].key_frame == 1) {
224
            put_be32(pb, i+1);
225
            index++;
226
        }
227
    }
228
    curpos = url_ftell(pb);
229
    url_fseek(pb, entryPos, SEEK_SET);
230
    put_be32(pb, index); // rewrite size
231
    url_fseek(pb, curpos, SEEK_SET);
232
    return updateSize (pb, pos);
233
}
234

    
235
static int mov_write_damr_tag(ByteIOContext *pb)
236
{
237
    put_be32(pb, 0x11); /* size */
238
    put_tag(pb, "damr");
239
    put_tag(pb, "FFMP");
240
    put_byte(pb, 0);
241

    
242
    put_be16(pb, 0x80); /* Mode set (all modes for AMR_NB) */
243
    put_be16(pb, 0xa); /* Mode change period (no restriction) */
244
    //put_be16(pb, 0x81ff); /* Mode set (all modes for AMR_NB) */
245
    //put_be16(pb, 1); /* Mode change period (no restriction) */
246
    return 0x11;
247
}
248

    
249
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack* track)
250
{
251
    offset_t pos = url_ftell(pb);
252

    
253
    put_be32(pb, 0);     /* size */
254
    put_tag(pb, "wave");
255

    
256
    put_be32(pb, 12);    /* size */
257
    put_tag(pb, "frma");
258
    put_tag(pb, "mp4a");
259

    
260
    put_be32(pb, 12);    /* size */
261
    put_tag(pb, "mp4a");
262
    put_be32(pb, 0);
263

    
264
    mov_write_esds_tag(pb, track);
265

    
266
    put_be32(pb, 12);    /* size */
267
    put_tag(pb, "srcq");
268
    put_be32(pb, 0x40);
269

    
270
    put_be32(pb, 8);     /* size */
271
    put_be32(pb, 0);     /* null tag */
272

    
273
    return updateSize (pb, pos);
274
}
275

    
276
static const CodecTag codec_movaudio_tags[] = {
277
    { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') },
278
    { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') },
279
    { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') },
280
    { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') },
281
    { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') },
282
    { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
283
    { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') },
284
    { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') },
285
    { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') },
286
    { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') },
287
    { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') },
288
    { 0, 0 },
289
};
290

    
291
static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack* track)
292
{
293
    offset_t pos = url_ftell(pb);
294
    int tag;
295

    
296
    put_be32(pb, 0); /* size */
297

    
298
    tag = track->enc->codec_tag;
299
    if (!tag)
300
    tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
301
    // if no mac fcc found, try with Microsoft tags
302
    if (!tag)
303
    {
304
        int tmp = codec_get_tag(codec_wav_tags, track->enc->codec_id);
305
        tag = MKTAG('m', 's', ((tmp >> 8) & 0xff), (tmp & 0xff));
306
    }
307
    put_le32(pb, tag); // store it byteswapped
308

    
309
    put_be32(pb, 0); /* Reserved */
310
    put_be16(pb, 0); /* Reserved */
311
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
312

    
313
    /* SoundDescription */
314
    if(track->mode == MODE_MOV && track->enc->codec_id == CODEC_ID_AAC)
315
        put_be16(pb, 1); /* Version 1 */
316
    else
317
        put_be16(pb, 0); /* Version 0 */
318
    put_be16(pb, 0); /* Revision level */
319
    put_be32(pb, 0); /* Reserved */
320

    
321
    put_be16(pb, track->enc->channels); /* Number of channels */
322
    /* TODO: Currently hard-coded to 16-bit, there doesn't seem
323
                 to be a good way to get number of bits of audio */
324
    put_be16(pb, 0x10); /* Reserved */
325

    
326
    if(track->enc->codec_id == CODEC_ID_AAC ||
327
       track->enc->codec_id == CODEC_ID_MP3)
328
    {
329
        put_be16(pb, 0xfffe); /* compression ID (vbr)*/
330
    }
331
    else
332
    {
333
        put_be16(pb, 0); /* compression ID (= 0) */
334
    }
335
    put_be16(pb, 0); /* packet size (= 0) */
336
    put_be16(pb, track->timescale); /* Time scale */
337
    put_be16(pb, 0); /* Reserved */
338

    
339
    if(track->mode == MODE_MOV && track->enc->codec_id == CODEC_ID_AAC)
340
    {
341
        /* SoundDescription V1 extended info */
342
        put_be32(pb, track->enc->frame_size); /* Samples per packet  */
343
        put_be32(pb, 1536); /* Bytes per packet */
344
        put_be32(pb, 2); /* Bytes per frame */
345
        put_be32(pb, 2); /* Bytes per sample */
346
    }
347

    
348
    if(track->enc->codec_id == CODEC_ID_AAC) {
349
        if( track->mode == MODE_MOV ) mov_write_wave_tag(pb, track);
350
        else mov_write_esds_tag(pb, track);
351
    }
352
    if(track->enc->codec_id == CODEC_ID_AMR_NB)
353
        mov_write_damr_tag(pb);
354
    return updateSize (pb, pos);
355
}
356

    
357
static int mov_write_d263_tag(ByteIOContext *pb)
358
{
359
    put_be32(pb, 0xf); /* size */
360
    put_tag(pb, "d263");
361
    put_tag(pb, "FFMP");
362
    put_be16(pb, 0x0a);
363
    put_byte(pb, 0);
364
    return 0xf;
365
}
366

    
367
/* TODO: No idea about these values */
368
static int mov_write_svq3_tag(ByteIOContext *pb)
369
{
370
    put_be32(pb, 0x15);
371
    put_tag(pb, "SMI ");
372
    put_tag(pb, "SEQH");
373
    put_be32(pb, 0x5);
374
    put_be32(pb, 0xe2c0211d);
375
    put_be32(pb, 0xc0000000);
376
    put_byte(pb, 0);
377
    return 0x15;
378
}
379

    
380
static unsigned int descrLength(unsigned int len)
381
{
382
    if (len < 0x00000080)
383
        return 2 + len;
384
    else if (len < 0x00004000)
385
        return 3 + len;
386
    else if(len < 0x00200000)
387
        return 4 + len;
388
    else
389
        return 5 + len;
390
}
391

    
392
static void putDescr(ByteIOContext *pb, int tag, int size)
393
{
394
    uint32_t len;
395
    uint8_t  vals[4];
396

    
397
    len = size;
398
    vals[3] = (uint8_t)(len & 0x7f);
399
    len >>= 7;
400
    vals[2] = (uint8_t)((len & 0x7f) | 0x80);
401
    len >>= 7;
402
    vals[1] = (uint8_t)((len & 0x7f) | 0x80);
403
    len >>= 7;
404
    vals[0] = (uint8_t)((len & 0x7f) | 0x80);
405

    
406
    put_byte(pb, tag); // DescriptorTag
407

    
408
    if (size < 0x00000080)
409
    {
410
        put_byte(pb, vals[3]);
411
    }
412
    else if (size < 0x00004000)
413
    {
414
        put_byte(pb, vals[2]);
415
        put_byte(pb, vals[3]);
416
    }
417
    else if (size < 0x00200000)
418
    {
419
        put_byte(pb, vals[1]);
420
        put_byte(pb, vals[2]);
421
        put_byte(pb, vals[3]);
422
    }
423
    else if (size < 0x10000000)
424
    {
425
        put_byte(pb, vals[0]);
426
        put_byte(pb, vals[1]);
427
        put_byte(pb, vals[2]);
428
        put_byte(pb, vals[3]);
429
    }
430
}
431

    
432
static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track) // Basic
433
{
434
    int decoderSpecificInfoLen;
435
    offset_t pos = url_ftell(pb);
436

    
437
    decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
438

    
439
    put_be32(pb, 0);               // size
440
    put_tag(pb, "esds");
441
    put_be32(pb, 0);               // Version
442

    
443
    // ES descriptor
444
    putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
445
             descrLength(1));
446
    put_be16(pb, track->trackID);
447
    put_byte(pb, 0x00);            // flags (= no flags)
448

    
449
    // DecoderConfig descriptor
450
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
451

    
452
    // Object type indication
453
    put_byte(pb, codec_get_tag(ff_mov_obj_type, track->enc->codec_id));
454

    
455
    // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
456
    // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
457
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
458
        put_byte(pb, 0x15);            // flags (= Audiostream)
459
    else
460
        put_byte(pb, 0x11);            // flags (= Visualstream)
461

    
462
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));             // Buffersize DB (24 bits)
463
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF);          // Buffersize DB
464

    
465
    put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate));     // maxbitrate  (FIXME should be max rate in any 1 sec window)
466
    if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
467
        put_be32(pb, 0);     // vbr
468
    else
469
        put_be32(pb, track->enc->rc_max_rate);     // avg bitrate
470

    
471
    if (track->vosLen)
472
    {
473
        // DecoderSpecific info descriptor
474
        putDescr(pb, 0x05, track->vosLen);
475
        put_buffer(pb, track->vosData, track->vosLen);
476
    }
477

    
478

    
479
    // SL descriptor
480
    putDescr(pb, 0x06, 1);
481
    put_byte(pb, 0x02);
482
    return updateSize (pb, pos);
483
}
484

    
485
static const CodecTag codec_movvideo_tags[] = {
486
    { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') },
487
    { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') },
488
    { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
489
    { CODEC_ID_H263, MKTAG('s', '2', '6', '3') },
490
    { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
491
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') },
492
    { 0, 0 },
493
};
494

    
495
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
496
{
497
    offset_t pos = url_ftell(pb);
498
    char compressor_name[32];
499
    int tag;
500

    
501
    put_be32(pb, 0); /* size */
502

    
503
    tag = track->enc->codec_tag;
504
    if (!tag)
505
    tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
506
    // if no mac fcc found, try with Microsoft tags
507
    if (!tag)
508
        tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
509
    put_le32(pb, tag); // store it byteswapped
510

    
511
    put_be32(pb, 0); /* Reserved */
512
    put_be16(pb, 0); /* Reserved */
513
    put_be16(pb, 1); /* Data-reference index */
514

    
515
    put_be16(pb, 0); /* Codec stream version */
516
    put_be16(pb, 0); /* Codec stream revision (=0) */
517
    put_tag(pb, "FFMP"); /* Vendor */
518
    if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
519
        put_be32(pb, 0); /* Temporal Quality */
520
        put_be32(pb, 0x400); /* Spatial Quality = lossless*/
521
    } else {
522
        put_be32(pb, 0x200); /* Temporal Quality = normal */
523
        put_be32(pb, 0x200); /* Spatial Quality = normal */
524
    }
525
    put_be16(pb, track->enc->width); /* Video width */
526
    put_be16(pb, track->enc->height); /* Video height */
527
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
528
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
529
    put_be32(pb, 0); /* Data size (= 0) */
530
    put_be16(pb, 1); /* Frame count (= 1) */
531

    
532
    memset(compressor_name,0,32);
533
    if (track->enc->codec && track->enc->codec->name)
534
        strncpy(compressor_name,track->enc->codec->name,31);
535
    put_byte(pb, strlen(compressor_name));
536
    put_buffer(pb, compressor_name, 31);
537

    
538
    put_be16(pb, 0x18); /* Reserved */
539
    put_be16(pb, 0xffff); /* Reserved */
540
    if(track->enc->codec_id == CODEC_ID_MPEG4)
541
        mov_write_esds_tag(pb, track);
542
    else if(track->enc->codec_id == CODEC_ID_H263)
543
        mov_write_d263_tag(pb);
544
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
545
        mov_write_svq3_tag(pb);
546

    
547
    return updateSize (pb, pos);
548
}
549

    
550
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack* track)
551
{
552
    offset_t pos = url_ftell(pb);
553
    put_be32(pb, 0); /* size */
554
    put_tag(pb, "stsd");
555
    put_be32(pb, 0); /* version & flags */
556
    put_be32(pb, 1); /* entry count */
557
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
558
        mov_write_video_tag(pb, track);
559
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
560
        mov_write_audio_tag(pb, track);
561
    return updateSize(pb, pos);
562
}
563

    
564
/* TODO: */
565
/* Time to sample atom */
566
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack* track)
567
{
568
    put_be32(pb, 0x18); /* size */
569
    put_tag(pb, "stts");
570
    put_be32(pb, 0); /* version & flags */
571
    put_be32(pb, 1); /* entry count */
572

    
573
    put_be32(pb, track->sampleCount); /* sample count */
574
    put_be32(pb, track->sampleDuration); /* sample duration */
575
    return 0x18;
576
}
577

    
578
static int mov_write_dref_tag(ByteIOContext *pb)
579
{
580
    put_be32(pb, 28); /* size */
581
    put_tag(pb, "dref");
582
    put_be32(pb, 0); /* version & flags */
583
    put_be32(pb, 1); /* entry count */
584

    
585
    put_be32(pb, 0xc); /* size */
586
    put_tag(pb, "url ");
587
    put_be32(pb, 1); /* version & flags */
588

    
589
    return 28;
590
}
591

    
592
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track)
593
{
594
    offset_t pos = url_ftell(pb);
595
    put_be32(pb, 0); /* size */
596
    put_tag(pb, "stbl");
597
    mov_write_stsd_tag(pb, track);
598
    mov_write_stts_tag(pb, track);
599
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
600
        track->hasKeyframes)
601
        mov_write_stss_tag(pb, track);
602
    mov_write_stsc_tag(pb, track);
603
    mov_write_stsz_tag(pb, track);
604
    mov_write_stco_tag(pb, track);
605
    return updateSize(pb, pos);
606
}
607

    
608
static int mov_write_dinf_tag(ByteIOContext *pb)
609
{
610
    offset_t pos = url_ftell(pb);
611
    put_be32(pb, 0); /* size */
612
    put_tag(pb, "dinf");
613
    mov_write_dref_tag(pb);
614
    return updateSize(pb, pos);
615
}
616

    
617
static int mov_write_smhd_tag(ByteIOContext *pb)
618
{
619
    put_be32(pb, 16); /* size */
620
    put_tag(pb, "smhd");
621
    put_be32(pb, 0); /* version & flags */
622
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
623
    put_be16(pb, 0); /* reserved */
624
    return 16;
625
}
626

    
627
static int mov_write_vmhd_tag(ByteIOContext *pb)
628
{
629
    put_be32(pb, 0x14); /* size (always 0x14) */
630
    put_tag(pb, "vmhd");
631
    put_be32(pb, 0x01); /* version & flags */
632
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
633
    return 0x14;
634
}
635

    
636
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack* track)
637
{
638
    char *descr, *hdlr, *hdlr_type;
639
    offset_t pos = url_ftell(pb);
640

    
641
    if (!track) { /* no media --> data handler */
642
        hdlr = "dhlr";
643
        hdlr_type = "url ";
644
        descr = "DataHandler";
645
    } else {
646
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
647
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
648
            hdlr_type = "vide";
649
            descr = "VideoHandler";
650
        } else {
651
            hdlr_type = "soun";
652
            descr = "SoundHandler";
653
        }
654
    }
655

    
656
    put_be32(pb, 0); /* size */
657
    put_tag(pb, "hdlr");
658
    put_be32(pb, 0); /* Version & flags */
659
    put_buffer(pb, hdlr, 4); /* handler */
660
    put_tag(pb, hdlr_type); /* handler type */
661
    put_be32(pb ,0); /* reserved */
662
    put_be32(pb ,0); /* reserved */
663
    put_be32(pb ,0); /* reserved */
664
    put_byte(pb, strlen(descr)); /* string counter */
665
    put_buffer(pb, descr, strlen(descr)); /* handler description */
666
    return updateSize(pb, pos);
667
}
668

    
669
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack* track)
670
{
671
    offset_t pos = url_ftell(pb);
672
    put_be32(pb, 0); /* size */
673
    put_tag(pb, "minf");
674
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
675
        mov_write_vmhd_tag(pb);
676
    else
677
        mov_write_smhd_tag(pb);
678
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
679
        mov_write_hdlr_tag(pb, NULL);
680
    mov_write_dinf_tag(pb);
681
    mov_write_stbl_tag(pb, track);
682
    return updateSize(pb, pos);
683
}
684

    
685
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack* track)
686
{
687
    put_be32(pb, 32); /* size */
688
    put_tag(pb, "mdhd");
689
    put_be32(pb, 0); /* Version & flags */
690
    put_be32(pb, track->time); /* creation time */
691
    put_be32(pb, track->time); /* modification time */
692
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
693
    put_be32(pb, track->trackDuration); /* duration */
694
    put_be16(pb, track->language); /* language */
695
    put_be16(pb, 0); /* reserved (quality) */
696
    return 32;
697
}
698

    
699
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack* track)
700
{
701
    offset_t pos = url_ftell(pb);
702
    put_be32(pb, 0); /* size */
703
    put_tag(pb, "mdia");
704
    mov_write_mdhd_tag(pb, track);
705
    mov_write_hdlr_tag(pb, track);
706
    mov_write_minf_tag(pb, track);
707
    return updateSize(pb, pos);
708
}
709

    
710
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)
711
{
712
    put_be32(pb, 0x5c); /* size (always 0x5c) */
713
    put_tag(pb, "tkhd");
714
    put_be32(pb, 0xf); /* version & flags (track enabled) */
715
    put_be32(pb, track->time); /* creation time */
716
    put_be32(pb, track->time); /* modification time */
717
    put_be32(pb, track->trackID); /* track-id */
718
    put_be32(pb, 0); /* reserved */
719
    put_be32(pb, av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP)); /* duration */
720

    
721
    put_be32(pb, 0); /* reserved */
722
    put_be32(pb, 0); /* reserved */
723
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
724
    /* Volume, only for audio */
725
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
726
        put_be16(pb, 0x0100);
727
    else
728
        put_be16(pb, 0);
729
    put_be16(pb, 0); /* reserved */
730

    
731
    /* Matrix structure */
732
    put_be32(pb, 0x00010000); /* reserved */
733
    put_be32(pb, 0x0); /* reserved */
734
    put_be32(pb, 0x0); /* reserved */
735
    put_be32(pb, 0x0); /* reserved */
736
    put_be32(pb, 0x00010000); /* reserved */
737
    put_be32(pb, 0x0); /* reserved */
738
    put_be32(pb, 0x0); /* reserved */
739
    put_be32(pb, 0x0); /* reserved */
740
    put_be32(pb, 0x40000000); /* reserved */
741

    
742
    /* Track width and height, for visual only */
743
    if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
744
        double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
745
        if( !sample_aspect_ratio ) sample_aspect_ratio = 1;
746
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
747
        put_be32(pb, track->enc->height*0x10000);
748
    }
749
    else {
750
        put_be32(pb, 0);
751
        put_be32(pb, 0);
752
    }
753
    return 0x5c;
754
}
755

    
756
// This box seems important for the psp playback ... without it the movie seems to hang
757
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
758
{
759
    put_be32(pb, 0x24); /* size  */
760
    put_tag(pb, "edts");
761
    put_be32(pb, 0x1c); /* size  */
762
    put_tag(pb, "elst");
763
    put_be32(pb, 0x0);
764
    put_be32(pb, 0x1);
765

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

    
768
    put_be32(pb, 0x0);
769
    put_be32(pb, 0x00010000);
770
    return 0x24;
771
}
772

    
773
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
774
static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
775
{
776
    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
777
    put_tag(pb, "uuid");
778
    put_tag(pb, "USMT");
779
    put_be32(pb, 0x21d24fce);
780
    put_be32(pb, 0xbb88695c);
781
    put_be32(pb, 0xfac9c740);
782
    put_be32(pb, 0x1c);     // another size here!
783
    put_tag(pb, "MTDT");
784
    put_be32(pb, 0x00010012);
785
    put_be32(pb, 0x0a);
786
    put_be32(pb, 0x55c40000);
787
    put_be32(pb, 0x1);
788
    put_be32(pb, 0x0);
789
    return 0x34;
790
}
791

    
792
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack* track)
793
{
794
    offset_t pos = url_ftell(pb);
795
    put_be32(pb, 0); /* size */
796
    put_tag(pb, "trak");
797
    mov_write_tkhd_tag(pb, track);
798
    if (track->mode == MODE_PSP)
799
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
800
    mov_write_mdia_tag(pb, track);
801
    if (track->mode == MODE_PSP)
802
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
803
    return updateSize(pb, pos);
804
}
805

    
806
#if 0
807
/* TODO: Not sorted out, but not necessary either */
808
static int mov_write_iods_tag(ByteIOContext *pb, MOVContext *mov)
809
{
810
    put_be32(pb, 0x15); /* size */
811
    put_tag(pb, "iods");
812
    put_be32(pb, 0);    /* version & flags */
813
    put_be16(pb, 0x1007);
814
    put_byte(pb, 0);
815
    put_be16(pb, 0x4fff);
816
    put_be16(pb, 0xfffe);
817
    put_be16(pb, 0x01ff);
818
    return 0x15;
819
}
820
#endif
821

    
822
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
823
{
824
    int maxTrackID = 1, i;
825
    int64_t maxTrackLenTemp, maxTrackLen = 0;
826

    
827
    put_be32(pb, 0x6c); /* size (always 0x6c) */
828
    put_tag(pb, "mvhd");
829
    put_be32(pb, 0); /* version & flags */
830
    put_be32(pb, mov->time); /* creation time */
831
    put_be32(pb, mov->time); /* modification time */
832
    put_be32(pb, mov->timescale); /* timescale */
833
    for (i=0; i<MAX_STREAMS; i++) {
834
        if(mov->tracks[i].entry > 0) {
835
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
836
            if(maxTrackLen < maxTrackLenTemp)
837
                maxTrackLen = maxTrackLenTemp;
838
            if(maxTrackID < mov->tracks[i].trackID)
839
                maxTrackID = mov->tracks[i].trackID;
840
        }
841
    }
842
    put_be32(pb, maxTrackLen); /* duration of longest track */
843

    
844
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
845
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
846
    put_be16(pb, 0); /* reserved */
847
    put_be32(pb, 0); /* reserved */
848
    put_be32(pb, 0); /* reserved */
849

    
850
    /* Matrix structure */
851
    put_be32(pb, 0x00010000); /* reserved */
852
    put_be32(pb, 0x0); /* reserved */
853
    put_be32(pb, 0x0); /* reserved */
854
    put_be32(pb, 0x0); /* reserved */
855
    put_be32(pb, 0x00010000); /* reserved */
856
    put_be32(pb, 0x0); /* reserved */
857
    put_be32(pb, 0x0); /* reserved */
858
    put_be32(pb, 0x0); /* reserved */
859
    put_be32(pb, 0x40000000); /* reserved */
860

    
861
    put_be32(pb, 0); /* reserved (preview time) */
862
    put_be32(pb, 0); /* reserved (preview duration) */
863
    put_be32(pb, 0); /* reserved (poster time) */
864
    put_be32(pb, 0); /* reserved (selection time) */
865
    put_be32(pb, 0); /* reserved (selection duration) */
866
    put_be32(pb, 0); /* reserved (current time) */
867
    put_be32(pb, maxTrackID+1); /* Next track id */
868
    return 0x6c;
869
}
870

    
871
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVContext* mov,
872
                                     AVFormatContext *s)
873
{
874
    offset_t pos = url_ftell(pb);
875
    put_be32(pb, 0); /* size */
876
    put_tag(pb, "hdlr");
877
    put_be32(pb, 0);
878
    put_be32(pb, 0);
879
    put_tag(pb, "mdir");
880
    put_tag(pb, "appl");
881
    put_be32(pb, 0);
882
    put_be32(pb, 0);
883
    put_be16(pb, 0);
884
    return updateSize(pb, pos);
885
}
886

    
887
/* helper function to write a data tag with the specified string as data */
888
static int mov_write_string_data_tag(ByteIOContext *pb, MOVContext* mov,
889
                                     AVFormatContext *s, const char *data)
890
{
891
    offset_t pos = url_ftell(pb);
892
    put_be32(pb, 0); /* size */
893
    put_tag(pb, "data");
894
    put_be32(pb, 1);
895
    put_be32(pb, 0);
896
    put_buffer(pb, data, strlen(data));
897
    return updateSize(pb, pos);
898
}
899

    
900
/* iTunes name of the song/movie */
901
static int mov_write_nam_tag(ByteIOContext *pb, MOVContext* mov,
902
                             AVFormatContext *s)
903
{
904
    int size = 0;
905
    if ( s->title[0] ) {
906
        offset_t pos = url_ftell(pb);
907
        put_be32(pb, 0); /* size */
908
        put_tag(pb, "\251nam");
909
        mov_write_string_data_tag(pb, mov, s, s->title);
910
        size = updateSize(pb, pos);
911
    }
912
    return size;
913
}
914

    
915
/* iTunes name of the artist/performer */
916
static int mov_write_ART_tag(ByteIOContext *pb, MOVContext* mov,
917
                             AVFormatContext *s)
918
{
919
    int size = 0;
920
    if ( s->author[0] ) {
921
        offset_t pos = url_ftell(pb);
922
        put_be32(pb, 0); /* size */
923
        put_tag(pb, "\251ART");
924
        // we use the author here as this is the only thing that we have...
925
        mov_write_string_data_tag(pb, mov, s, s->author);
926
        size = updateSize(pb, pos);
927
    }
928
    return size;
929
}
930

    
931
/* iTunes name of the writer */
932
static int mov_write_wrt_tag(ByteIOContext *pb, MOVContext* mov,
933
                             AVFormatContext *s)
934
{
935
    int size = 0;
936
    if ( s->author[0] ) {
937
        offset_t pos = url_ftell(pb);
938
        put_be32(pb, 0); /* size */
939
        put_tag(pb, "\251wrt");
940
        mov_write_string_data_tag(pb, mov, s, s->author);
941
        size = updateSize(pb, pos);
942
    }
943
    return size;
944
}
945

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

    
961
/* iTunes year */
962
static int mov_write_day_tag(ByteIOContext *pb, MOVContext* mov,
963
                             AVFormatContext *s)
964
{
965
    char year[5];
966
    int size = 0;
967
    if ( s->year ) {
968
        offset_t pos = url_ftell(pb);
969
        put_be32(pb, 0); /* size */
970
        put_tag(pb, "\251day");
971
        snprintf(year, 5, "%04d", s->year);
972
        mov_write_string_data_tag(pb, mov, s, year);
973
        size = updateSize(pb, pos);
974
    }
975
    return size;
976
}
977

    
978
/* iTunes tool used to create the file */
979
static int mov_write_too_tag(ByteIOContext *pb, MOVContext* mov,
980
                             AVFormatContext *s)
981
{
982
    offset_t pos = url_ftell(pb);
983
    put_be32(pb, 0); /* size */
984
    put_tag(pb, "\251too");
985
    mov_write_string_data_tag(pb, mov, s, LIBAVFORMAT_IDENT);
986
    return updateSize(pb, pos);
987
}
988

    
989
/* iTunes comment */
990
static int mov_write_cmt_tag(ByteIOContext *pb, MOVContext* mov,
991
                             AVFormatContext *s)
992
{
993
    int size = 0;
994
    if ( s->comment[0] ) {
995
        offset_t pos = url_ftell(pb);
996
        put_be32(pb, 0); /* size */
997
        put_tag(pb, "\251cmt");
998
        mov_write_string_data_tag(pb, mov, s, s->comment);
999
        size = updateSize(pb, pos);
1000
    }
1001
    return size;
1002
}
1003

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

    
1019
/* iTunes track number */
1020
static int mov_write_trkn_tag(ByteIOContext *pb, MOVContext* mov,
1021
                              AVFormatContext *s)
1022
{
1023
    int size = 0;
1024
    if ( s->track ) {
1025
        offset_t pos = url_ftell(pb);
1026
        put_be32(pb, 0); /* size */
1027
        put_tag(pb, "trkn");
1028
        {
1029
            offset_t pos = url_ftell(pb);
1030
            put_be32(pb, 0); /* size */
1031
            put_tag(pb, "data");
1032
            put_be32(pb, 0);        // 8 bytes empty
1033
            put_be32(pb, 0);
1034
            put_be16(pb, 0);        // empty
1035
            put_be16(pb, s->track); // track number
1036
            put_be16(pb, 0);        // total track number
1037
            put_be16(pb, 0);        // empty
1038
            updateSize(pb, pos);
1039
        }
1040
        size = updateSize(pb, pos);
1041
    }
1042
    return size;
1043
}
1044

    
1045
/* iTunes meta data list */
1046
static int mov_write_ilst_tag(ByteIOContext *pb, MOVContext* mov,
1047
                              AVFormatContext *s)
1048
{
1049
    offset_t pos = url_ftell(pb);
1050
    put_be32(pb, 0); /* size */
1051
    put_tag(pb, "ilst");
1052
    mov_write_nam_tag(pb, mov, s);
1053
    mov_write_ART_tag(pb, mov, s);
1054
    mov_write_wrt_tag(pb, mov, s);
1055
    mov_write_alb_tag(pb, mov, s);
1056
    mov_write_day_tag(pb, mov, s);
1057
    mov_write_too_tag(pb, mov, s);
1058
    mov_write_cmt_tag(pb, mov, s);
1059
    mov_write_gen_tag(pb, mov, s);
1060
    mov_write_trkn_tag(pb, mov, s);
1061
    return updateSize(pb, pos);
1062
}
1063

    
1064
/* iTunes meta data tag */
1065
static int mov_write_meta_tag(ByteIOContext *pb, MOVContext* mov,
1066
                              AVFormatContext *s)
1067
{
1068
    int size = 0;
1069

    
1070
    // only save meta tag if required
1071
    if ( s->title[0] || s->author[0] || s->album[0] || s->year ||
1072
         s->comment[0] || s->genre[0] || s->track ) {
1073
        offset_t pos = url_ftell(pb);
1074
        put_be32(pb, 0); /* size */
1075
        put_tag(pb, "meta");
1076
        put_be32(pb, 0);
1077
        mov_write_itunes_hdlr_tag(pb, mov, s);
1078
        mov_write_ilst_tag(pb, mov, s);
1079
        size = updateSize(pb, pos);
1080
    }
1081
    return size;
1082
}
1083

    
1084
static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1085
                              AVFormatContext *s)
1086
{
1087
    offset_t pos = url_ftell(pb);
1088
    int i;
1089

    
1090
    put_be32(pb, 0); /* size */
1091
    put_tag(pb, "udta");
1092

    
1093
    /* iTunes meta data */
1094
    mov_write_meta_tag(pb, mov, s);
1095

    
1096
    /* Requirements */
1097
    for (i=0; i<MAX_STREAMS; i++) {
1098
        if(mov->tracks[i].entry <= 0) continue;
1099
        if (mov->tracks[i].enc->codec_id == CODEC_ID_AAC ||
1100
            mov->tracks[i].enc->codec_id == CODEC_ID_MPEG4) {
1101
            offset_t pos = url_ftell(pb);
1102
            put_be32(pb, 0); /* size */
1103
            put_tag(pb, "\251req");
1104
            put_be16(pb, sizeof("QuickTime 6.0 or greater") - 1);
1105
            put_be16(pb, 0);
1106
            put_buffer(pb, "QuickTime 6.0 or greater",
1107
                       sizeof("QuickTime 6.0 or greater") - 1);
1108
            updateSize(pb, pos);
1109
            break;
1110
        }
1111
    }
1112

    
1113
    /* Encoder */
1114
    if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1115
    {
1116
        offset_t pos = url_ftell(pb);
1117
        put_be32(pb, 0); /* size */
1118
        put_tag(pb, "\251enc");
1119
        put_be16(pb, sizeof(LIBAVFORMAT_IDENT) - 1); /* string length */
1120
        put_be16(pb, 0);
1121
        put_buffer(pb, LIBAVFORMAT_IDENT, sizeof(LIBAVFORMAT_IDENT) - 1);
1122
        updateSize(pb, pos);
1123
    }
1124

    
1125
    if( s->title[0] )
1126
    {
1127
        offset_t pos = url_ftell(pb);
1128
        put_be32(pb, 0); /* size */
1129
        put_tag(pb, "\251nam");
1130
        put_be16(pb, strlen(s->title)); /* string length */
1131
        put_be16(pb, 0);
1132
        put_buffer(pb, s->title, strlen(s->title));
1133
        updateSize(pb, pos);
1134
    }
1135

    
1136
    if( s->author[0] )
1137
    {
1138
        offset_t pos = url_ftell(pb);
1139
        put_be32(pb, 0); /* size */
1140
        put_tag(pb, /*"\251aut"*/ "\251day" );
1141
        put_be16(pb, strlen(s->author)); /* string length */
1142
        put_be16(pb, 0);
1143
        put_buffer(pb, s->author, strlen(s->author));
1144
        updateSize(pb, pos);
1145
    }
1146

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

    
1158
    return updateSize(pb, pos);
1159
}
1160

    
1161

    
1162
static size_t ascii_to_wc (ByteIOContext *pb, char *b, size_t n)
1163
{
1164
    size_t i;
1165
    unsigned char c;
1166
    for (i = 0; i < n - 1; i++) {
1167
        c = b[i];
1168
        if (! (0x20 <= c && c <= 0x7f ))
1169
            c = 0x3f;  /* '?' */
1170
        put_be16(pb, c);
1171
    }
1172
    put_be16(pb, 0x00);
1173
    return 2*n;
1174
}
1175

    
1176
static uint16_t language_code (char *str)
1177
{
1178
    return ((((str[0]-'a') & 0x1F)<<10) + (((str[1]-'a') & 0x1F)<<5) + ((str[2]-'a') & 0x1F));
1179
}
1180

    
1181
static int mov_write_uuidusmt_tag (ByteIOContext *pb, AVFormatContext *s)
1182
{
1183
    size_t len, size;
1184
    offset_t pos, curpos;
1185

    
1186
    size = 0;
1187
    if (s->title[0]) {
1188
        pos = url_ftell(pb);
1189
        put_be32(pb, 0); /* size placeholder*/
1190
        put_tag(pb, "uuid");
1191
        put_tag(pb, "USMT");
1192
        put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1193
        put_be32(pb, 0xbb88695c );
1194
        put_be32(pb, 0xfac9c740 );
1195
        size += 24;
1196

    
1197
        put_be32(pb, 0); /* size placeholder*/
1198
        put_tag(pb, "MTDT");
1199
        put_be16(pb, 1);
1200
        size += 10;
1201

    
1202
        // Title
1203
        len = strlen(s->title)+1;
1204
        put_be16(pb, len*2+10);             /* size */
1205
        put_be32(pb, 0x01);                 /* type */
1206
        put_be16(pb, language_code("und")); /* language */
1207
        put_be16(pb, 0x01);                 /* ? */
1208
        ascii_to_wc (pb, s->title, len);
1209
        size += len*2+10;
1210

    
1211
        // size
1212
        curpos = url_ftell(pb);
1213
        url_fseek(pb, pos, SEEK_SET);
1214
        put_be32(pb, size);
1215
        url_fseek(pb, pos+24, SEEK_SET);
1216
        put_be32(pb, size-24);
1217
        url_fseek(pb, curpos, SEEK_SET);
1218
    }
1219

    
1220
    return size;
1221
}
1222

    
1223
static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1224
                              AVFormatContext *s)
1225
{
1226
    int i;
1227
    offset_t pos = url_ftell(pb);
1228
    put_be32(pb, 0); /* size placeholder*/
1229
    put_tag(pb, "moov");
1230
    mov->timescale = globalTimescale;
1231

    
1232
    for (i=0; i<MAX_STREAMS; i++) {
1233
        if(mov->tracks[i].entry <= 0) continue;
1234

    
1235
        if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {
1236
            mov->tracks[i].timescale = mov->tracks[i].enc->time_base.den;
1237
            mov->tracks[i].sampleDuration = mov->tracks[i].enc->time_base.num;
1238
        }
1239
        else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {
1240
            /* If AMR, track timescale = 8000, AMR_WB = 16000 */
1241
            if(mov->tracks[i].enc->codec_id == CODEC_ID_AMR_NB) {
1242
                mov->tracks[i].sampleDuration = 160;  // Bytes per chunk
1243
                mov->tracks[i].timescale = 8000;
1244
            }
1245
            else {
1246
                mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;
1247
                mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;
1248
            }
1249
        }
1250

    
1251
        mov->tracks[i].trackDuration =
1252
            mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;
1253
        mov->tracks[i].time = mov->time;
1254
        mov->tracks[i].trackID = i+1;
1255
    }
1256

    
1257
    mov_write_mvhd_tag(pb, mov);
1258
    //mov_write_iods_tag(pb, mov);
1259
    for (i=0; i<MAX_STREAMS; i++) {
1260
        if(mov->tracks[i].entry > 0) {
1261
            mov_write_trak_tag(pb, &(mov->tracks[i]));
1262
        }
1263
    }
1264

    
1265
    if (mov->mode == MODE_PSP)
1266
        mov_write_uuidusmt_tag(pb, s);
1267
    else
1268
    mov_write_udta_tag(pb, mov, s);
1269

    
1270
    return updateSize(pb, pos);
1271
}
1272

    
1273
int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1274
{
1275
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1276
    put_tag(pb, "wide");
1277

    
1278
    mov->mdat_pos = url_ftell(pb);
1279
    put_be32(pb, 0); /* size placeholder*/
1280
    put_tag(pb, "mdat");
1281
    return 0;
1282
}
1283

    
1284
/* TODO: This needs to be more general */
1285
static void mov_write_ftyp_tag (ByteIOContext *pb, AVFormatContext *s)
1286
{
1287
    MOVContext *mov = s->priv_data;
1288

    
1289
    put_be32(pb, 0x14 ); /* size */
1290
    put_tag(pb, "ftyp");
1291

    
1292
    if ( mov->mode == MODE_3GP )
1293
        put_tag(pb, "3gp4");
1294
    else if ( mov->mode == MODE_3G2 )
1295
        put_tag(pb, "3g2a");
1296
    else if ( mov->mode == MODE_PSP )
1297
        put_tag(pb, "MSNV");
1298
    else
1299
        put_tag(pb, "isom");
1300

    
1301
    put_be32(pb, 0x200 );
1302

    
1303
    if ( mov->mode == MODE_3GP )
1304
        put_tag(pb, "3gp4");
1305
    else if ( mov->mode == MODE_3G2 )
1306
        put_tag(pb, "3g2a");
1307
    else if ( mov->mode == MODE_PSP )
1308
        put_tag(pb, "MSNV");
1309
    else
1310
        put_tag(pb, "mp41");
1311
}
1312

    
1313
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1314
{
1315
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1316
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1317
    int AudioRate = AudioCodec->sample_rate;
1318
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1319

    
1320
    put_be32(pb, 0x94 ); /* size */
1321
    put_tag(pb, "uuid");
1322
    put_tag(pb, "PROF");
1323

    
1324
    put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1325
    put_be32(pb, 0xbb88695c );
1326
    put_be32(pb, 0xfac9c740 );
1327

    
1328
    put_be32(pb, 0x0 );  /* ? */
1329
    put_be32(pb, 0x3 );  /* 3 sections ? */
1330

    
1331
    put_be32(pb, 0x14 ); /* size */
1332
    put_tag(pb, "FPRF");
1333
    put_be32(pb, 0x0 );  /* ? */
1334
    put_be32(pb, 0x0 );  /* ? */
1335
    put_be32(pb, 0x0 );  /* ? */
1336

    
1337
    put_be32(pb, 0x2c );  /* size */
1338
    put_tag(pb, "APRF");   /* audio */
1339
    put_be32(pb, 0x0 );
1340
    put_be32(pb, 0x2 );   /* TrackID */
1341
    put_tag(pb, "mp4a");
1342
    put_be32(pb, 0x20f );
1343
    put_be32(pb, 0x0 );
1344
    put_be32(pb, AudioCodec->bit_rate / 1000);
1345
    put_be32(pb, AudioCodec->bit_rate / 1000);
1346
    put_be32(pb, AudioRate );
1347
    put_be32(pb, AudioCodec->channels );
1348

    
1349
    put_be32(pb, 0x34 );  /* size */
1350
    put_tag(pb, "VPRF");   /* video */
1351
    put_be32(pb, 0x0 );
1352
    put_be32(pb, 0x1 );    /* TrackID */
1353
    put_tag(pb, "mp4v");
1354
    put_be32(pb, 0x103 );
1355
    put_be32(pb, 0x0 );
1356
    put_be32(pb, VideoCodec->bit_rate / 1000);
1357
    put_be32(pb, VideoCodec->bit_rate / 1000);
1358
    put_be32(pb, FrameRate);
1359
    put_be32(pb, FrameRate);
1360
    put_be16(pb, VideoCodec->width);
1361
    put_be16(pb, VideoCodec->height);
1362
    put_be32(pb, 0x010001); /* ? */
1363
}
1364

    
1365
static int mov_write_header(AVFormatContext *s)
1366
{
1367
    ByteIOContext *pb = &s->pb;
1368
    MOVContext *mov = s->priv_data;
1369
    int i;
1370

    
1371
    for(i=0; i<s->nb_streams; i++){
1372
        AVCodecContext *c= s->streams[i]->codec;
1373

    
1374
        if      (c->codec_type == CODEC_TYPE_VIDEO){
1375
            if (!codec_get_tag(codec_movvideo_tags, c->codec_id)){
1376
                if(!codec_get_tag(codec_bmp_tags, c->codec_id))
1377
                    return -1;
1378
                else
1379
                    av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, the file may be unplayable!\n");
1380
            }
1381
        }else if(c->codec_type == CODEC_TYPE_AUDIO){
1382
            if (!codec_get_tag(codec_movaudio_tags, c->codec_id)){
1383
                if(!codec_get_tag(codec_wav_tags, c->codec_id))
1384
                    return -1;
1385
                else
1386
                    av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, the file may be unplayable!\n");
1387
            }
1388
        }
1389
        /* don't know yet if mp4 or not */
1390
        mov->tracks[i].language = ff_mov_iso639_to_lang(s->streams[i]->language, 1);
1391
    }
1392

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

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

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

    
1414
    for (i=0; i<MAX_STREAMS; i++) {
1415
        mov->tracks[i].mode = mov->mode;
1416
    }
1417

    
1418
    put_flush_packet(pb);
1419

    
1420
    return 0;
1421
}
1422

    
1423
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1424
{
1425
    MOVContext *mov = s->priv_data;
1426
    ByteIOContext *pb = &s->pb;
1427
    AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
1428
    MOVTrack* trk = &mov->tracks[pkt->stream_index];
1429
    int cl, id;
1430
    unsigned int samplesInChunk = 0;
1431
    int size= pkt->size;
1432

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

    
1436
    if (enc->codec_type == CODEC_TYPE_VIDEO ) {
1437
        samplesInChunk = 1;
1438
    }
1439
    else if (enc->codec_type == CODEC_TYPE_AUDIO ) {
1440
        if( enc->codec_id == CODEC_ID_AMR_NB) {
1441
            /* We must find out how many AMR blocks there are in one packet */
1442
            static uint16_t packed_size[16] =
1443
                {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1444
            int len = 0;
1445

    
1446
            while (len < size && samplesInChunk < 100) {
1447
                len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1448
                samplesInChunk++;
1449
            }
1450
        }
1451
        else if(enc->codec_id == CODEC_ID_PCM_ALAW) {
1452
            samplesInChunk = size/enc->channels;
1453
        }
1454
        else if(enc->codec_id == CODEC_ID_PCM_S16BE || enc->codec_id == CODEC_ID_PCM_S16LE) {
1455
            samplesInChunk = size/(2*enc->channels);
1456
        }
1457
        else {
1458
            samplesInChunk = 1;
1459
        }
1460
    }
1461

    
1462
    if ((enc->codec_id == CODEC_ID_MPEG4 || enc->codec_id == CODEC_ID_AAC)
1463
        && trk->vosLen == 0) {
1464
//        assert(enc->extradata_size);
1465

    
1466
        trk->vosLen = enc->extradata_size;
1467
        trk->vosData = av_malloc(trk->vosLen);
1468
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1469
    }
1470

    
1471
    cl = trk->entry / MOV_INDEX_CLUSTER_SIZE;
1472
    id = trk->entry % MOV_INDEX_CLUSTER_SIZE;
1473

    
1474
    if (trk->ents_allocated <= trk->entry) {
1475
        trk->cluster = av_realloc(trk->cluster, (cl+1)*sizeof(void*));
1476
        if (!trk->cluster)
1477
            return -1;
1478
        trk->cluster[cl] = av_malloc(MOV_INDEX_CLUSTER_SIZE*sizeof(MOVIentry));
1479
        if (!trk->cluster[cl])
1480
            return -1;
1481
        trk->ents_allocated += MOV_INDEX_CLUSTER_SIZE;
1482
    }
1483
    if (mov->mdat_written == 0) {
1484
        mov_write_mdat_tag(pb, mov);
1485
        mov->mdat_written = 1;
1486
        mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1487
    }
1488

    
1489
    trk->cluster[cl][id].pos = url_ftell(pb);
1490
    trk->cluster[cl][id].samplesInChunk = samplesInChunk;
1491
    trk->cluster[cl][id].size = size;
1492
    trk->cluster[cl][id].entries = samplesInChunk;
1493
    if(enc->codec_type == CODEC_TYPE_VIDEO) {
1494
        trk->cluster[cl][id].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1495
        if(trk->cluster[cl][id].key_frame)
1496
            trk->hasKeyframes = 1;
1497
    }
1498
    trk->enc = enc;
1499
    trk->entry++;
1500
    trk->sampleCount += samplesInChunk;
1501
    trk->mdat_size += size;
1502

    
1503
    put_buffer(pb, pkt->data, size);
1504

    
1505
    put_flush_packet(pb);
1506
    return 0;
1507
}
1508

    
1509
static int mov_write_trailer(AVFormatContext *s)
1510
{
1511
    MOVContext *mov = s->priv_data;
1512
    ByteIOContext *pb = &s->pb;
1513
    int res = 0;
1514
    int i;
1515
    uint64_t j;
1516

    
1517
    offset_t moov_pos = url_ftell(pb);
1518

    
1519
    /* Write size of mdat tag */
1520
    for (i=0, j=0; i<MAX_STREAMS; i++) {
1521
        if(mov->tracks[i].ents_allocated > 0) {
1522
            j += mov->tracks[i].mdat_size;
1523
        }
1524
    }
1525
    if (j+8 <= UINT32_MAX) {
1526
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
1527
        put_be32(pb, j+8);
1528
    } else {
1529
        /* overwrite 'wide' placeholder atom */
1530
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1531
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1532
        put_tag(pb, "mdat");
1533
        put_be64(pb, j+16);
1534
    }
1535
    url_fseek(pb, moov_pos, SEEK_SET);
1536

    
1537
    mov_write_moov_tag(pb, mov, s);
1538

    
1539
    for (i=0; i<MAX_STREAMS; i++) {
1540
        for (j=0; j<mov->tracks[i].ents_allocated/MOV_INDEX_CLUSTER_SIZE; j++) {
1541
            av_free(mov->tracks[i].cluster[j]);
1542
        }
1543
        av_free(mov->tracks[i].cluster);
1544
        if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1545

    
1546
        mov->tracks[i].cluster = NULL;
1547
        mov->tracks[i].ents_allocated = mov->tracks[i].entry = 0;
1548
    }
1549

    
1550
    put_flush_packet(pb);
1551

    
1552
    return res;
1553
}
1554

    
1555
static AVOutputFormat mov_oformat = {
1556
    "mov",
1557
    "mov format",
1558
    NULL,
1559
    "mov",
1560
    sizeof(MOVContext),
1561
    CODEC_ID_AAC,
1562
    CODEC_ID_MPEG4,
1563
    mov_write_header,
1564
    mov_write_packet,
1565
    mov_write_trailer,
1566
    .flags = AVFMT_GLOBALHEADER,
1567
};
1568

    
1569
static AVOutputFormat _3gp_oformat = {
1570
    "3gp",
1571
    "3gp format",
1572
    NULL,
1573
    "3gp",
1574
    sizeof(MOVContext),
1575
    CODEC_ID_AMR_NB,
1576
    CODEC_ID_H263,
1577
    mov_write_header,
1578
    mov_write_packet,
1579
    mov_write_trailer,
1580
    .flags = AVFMT_GLOBALHEADER,
1581
};
1582

    
1583
static AVOutputFormat mp4_oformat = {
1584
    "mp4",
1585
    "mp4 format",
1586
    "application/mp4",
1587
    "mp4,m4a",
1588
    sizeof(MOVContext),
1589
    CODEC_ID_AAC,
1590
    CODEC_ID_MPEG4,
1591
    mov_write_header,
1592
    mov_write_packet,
1593
    mov_write_trailer,
1594
    .flags = AVFMT_GLOBALHEADER,
1595
};
1596

    
1597
static AVOutputFormat psp_oformat = {
1598
    "psp",
1599
    "psp mp4 format",
1600
    NULL,
1601
    "mp4,psp",
1602
    sizeof(MOVContext),
1603
    CODEC_ID_AAC,
1604
    CODEC_ID_MPEG4,
1605
    mov_write_header,
1606
    mov_write_packet,
1607
    mov_write_trailer,
1608
    .flags = AVFMT_GLOBALHEADER,
1609
};
1610

    
1611
static AVOutputFormat _3g2_oformat = {
1612
    "3g2",
1613
    "3gp2 format",
1614
    NULL,
1615
    "3g2",
1616
    sizeof(MOVContext),
1617
    CODEC_ID_AMR_NB,
1618
    CODEC_ID_H263,
1619
    mov_write_header,
1620
    mov_write_packet,
1621
    mov_write_trailer,
1622
    .flags = AVFMT_GLOBALHEADER,
1623
};
1624

    
1625
int movenc_init(void)
1626
{
1627
    av_register_output_format(&mov_oformat);
1628
    av_register_output_format(&_3gp_oformat);
1629
    av_register_output_format(&mp4_oformat);
1630
    av_register_output_format(&psp_oformat);
1631
    av_register_output_format(&_3g2_oformat);
1632
    return 0;
1633
}