Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ ade5b91d

History | View | Annotate | Download (68.8 KB)

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

    
24
#include "avformat.h"
25
#include "riff.h"
26
#include "avio.h"
27
#include "isom.h"
28
#include "avc.h"
29
#include "libavcodec/get_bits.h"
30
#include "libavcodec/put_bits.h"
31

    
32
#undef NDEBUG
33
#include <assert.h>
34

    
35
#define MOV_INDEX_CLUSTER_SIZE 16384
36
#define MOV_TIMESCALE 1000
37

    
38
#define MODE_MP4  0x01
39
#define MODE_MOV  0x02
40
#define MODE_3GP  0x04
41
#define MODE_PSP  0x08 // example working PSP command line:
42
// ffmpeg -i testinput.avi  -f psp -r 14.985 -s 320x240 -b 768 -ar 24000 -ab 32 M4V00001.MP4
43
#define MODE_3G2  0x10
44
#define MODE_IPOD 0x20
45

    
46
typedef struct MOVIentry {
47
    unsigned int size;
48
    uint64_t     pos;
49
    unsigned int samplesInChunk;
50
    unsigned int entries;
51
    int          cts;
52
    int64_t      dts;
53
#define MOV_SYNC_SAMPLE         0x0001
54
#define MOV_PARTIAL_SYNC_SAMPLE 0x0002
55
    uint32_t     flags;
56
} MOVIentry;
57

    
58
typedef struct MOVIndex {
59
    int         mode;
60
    int         entry;
61
    unsigned    timescale;
62
    uint64_t    time;
63
    int64_t     trackDuration;
64
    long        sampleCount;
65
    long        sampleSize;
66
    int         hasKeyframes;
67
#define MOV_TRACK_CTTS         0x0001
68
#define MOV_TRACK_STPS         0x0002
69
    uint32_t    flags;
70
    int         language;
71
    int         trackID;
72
    int         tag; ///< stsd fourcc
73
    AVCodecContext *enc;
74

    
75
    int         vosLen;
76
    uint8_t     *vosData;
77
    MOVIentry   *cluster;
78
    int         audio_vbr;
79
    int         height; ///< active picture (w/o VBI) height for D-10/IMX
80
} MOVTrack;
81

    
82
typedef struct MOVMuxContext {
83
    int     mode;
84
    int64_t time;
85
    int     nb_streams;
86
    int64_t mdat_pos;
87
    uint64_t mdat_size;
88
    MOVTrack *tracks;
89
} MOVMuxContext;
90

    
91
//FIXME support 64 bit variant with wide placeholders
92
static int64_t updateSize(ByteIOContext *pb, int64_t pos)
93
{
94
    int64_t curpos = url_ftell(pb);
95
    url_fseek(pb, pos, SEEK_SET);
96
    put_be32(pb, curpos - pos); /* rewrite size */
97
    url_fseek(pb, curpos, SEEK_SET);
98

    
99
    return curpos - pos;
100
}
101

    
102
/* Chunk offset atom */
103
static int mov_write_stco_tag(ByteIOContext *pb, MOVTrack *track)
104
{
105
    int i;
106
    int mode64 = 0; //   use 32 bit size variant if possible
107
    int64_t pos = url_ftell(pb);
108
    put_be32(pb, 0); /* size */
109
    if (pos > UINT32_MAX) {
110
        mode64 = 1;
111
        put_tag(pb, "co64");
112
    } else
113
        put_tag(pb, "stco");
114
    put_be32(pb, 0); /* version & flags */
115
    put_be32(pb, track->entry); /* entry count */
116
    for (i=0; i<track->entry; i++) {
117
        if(mode64 == 1)
118
            put_be64(pb, track->cluster[i].pos);
119
        else
120
            put_be32(pb, track->cluster[i].pos);
121
    }
122
    return updateSize(pb, pos);
123
}
124

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

    
131
    int64_t pos = url_ftell(pb);
132
    put_be32(pb, 0); /* size */
133
    put_tag(pb, "stsz");
134
    put_be32(pb, 0); /* version & flags */
135

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

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

    
168
    int64_t pos = url_ftell(pb);
169
    put_be32(pb, 0); /* size */
170
    put_tag(pb, "stsc");
171
    put_be32(pb, 0); // version & flags
172
    entryPos = url_ftell(pb);
173
    put_be32(pb, track->entry); // entry count
174
    for (i=0; i<track->entry; i++) {
175
        if(oldval != track->cluster[i].samplesInChunk)
176
        {
177
            put_be32(pb, i+1); // first chunk
178
            put_be32(pb, track->cluster[i].samplesInChunk); // samples per chunk
179
            put_be32(pb, 0x1); // sample description index
180
            oldval = track->cluster[i].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, uint32_t flag)
194
{
195
    int64_t curpos, entryPos;
196
    int i, index = 0;
197
    int64_t pos = url_ftell(pb);
198
    put_be32(pb, 0); // size
199
    put_tag(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
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
        if (track->cluster[i].flags & flag) {
205
            put_be32(pb, i+1);
206
            index++;
207
        }
208
    }
209
    curpos = url_ftell(pb);
210
    url_fseek(pb, entryPos, SEEK_SET);
211
    put_be32(pb, index); // rewrite size
212
    url_fseek(pb, curpos, SEEK_SET);
213
    return updateSize(pb, pos);
214
}
215

    
216
static int mov_write_amr_tag(ByteIOContext *pb, MOVTrack *track)
217
{
218
    put_be32(pb, 0x11); /* size */
219
    if (track->mode == MODE_MOV) put_tag(pb, "samr");
220
    else                         put_tag(pb, "damr");
221
    put_tag(pb, "FFMP");
222
    put_byte(pb, 0); /* decoder version */
223

    
224
    put_be16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
225
    put_byte(pb, 0x00); /* Mode change period (no restriction) */
226
    put_byte(pb, 0x01); /* Frames per sample */
227
    return 0x11;
228
}
229

    
230
static int mov_write_ac3_tag(ByteIOContext *pb, MOVTrack *track)
231
{
232
    GetBitContext gbc;
233
    PutBitContext pbc;
234
    uint8_t buf[3];
235
    int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
236

    
237
    if (track->vosLen < 7)
238
        return -1;
239

    
240
    put_be32(pb, 11);
241
    put_tag(pb, "dac3");
242

    
243
    init_get_bits(&gbc, track->vosData+4, track->vosLen-4);
244
    fscod      = get_bits(&gbc, 2);
245
    frmsizecod = get_bits(&gbc, 6);
246
    bsid       = get_bits(&gbc, 5);
247
    bsmod      = get_bits(&gbc, 3);
248
    acmod      = get_bits(&gbc, 3);
249
    if (acmod == 2) {
250
        skip_bits(&gbc, 2); // dsurmod
251
    } else {
252
        if ((acmod & 1) && acmod != 1)
253
            skip_bits(&gbc, 2); // cmixlev
254
        if (acmod & 4)
255
            skip_bits(&gbc, 2); // surmixlev
256
    }
257
    lfeon = get_bits1(&gbc);
258

    
259
    init_put_bits(&pbc, buf, sizeof(buf));
260
    put_bits(&pbc, 2, fscod);
261
    put_bits(&pbc, 5, bsid);
262
    put_bits(&pbc, 3, bsmod);
263
    put_bits(&pbc, 3, acmod);
264
    put_bits(&pbc, 1, lfeon);
265
    put_bits(&pbc, 5, frmsizecod>>1); // bit_rate_code
266
    put_bits(&pbc, 5, 0); // reserved
267

    
268
    flush_put_bits(&pbc);
269
    put_buffer(pb, buf, sizeof(buf));
270

    
271
    return 11;
272
}
273

    
274
/**
275
 * This function writes extradata "as is".
276
 * Extradata must be formated like a valid atom (with size and tag)
277
 */
278
static int mov_write_extradata_tag(ByteIOContext *pb, MOVTrack *track)
279
{
280
    put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
281
    return track->enc->extradata_size;
282
}
283

    
284
static int mov_write_enda_tag(ByteIOContext *pb)
285
{
286
    put_be32(pb, 10);
287
    put_tag(pb, "enda");
288
    put_be16(pb, 1); /* little endian */
289
    return 10;
290
}
291

    
292
static unsigned int descrLength(unsigned int len)
293
{
294
    int i;
295
    for(i=1; len>>(7*i); i++);
296
    return len + 1 + i;
297
}
298

    
299
static void putDescr(ByteIOContext *pb, int tag, unsigned int size)
300
{
301
    int i= descrLength(size) - size - 2;
302
    put_byte(pb, tag);
303
    for(; i>0; i--)
304
        put_byte(pb, (size>>(7*i)) | 0x80);
305
    put_byte(pb, size & 0x7F);
306
}
307

    
308
static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack *track) // Basic
309
{
310
    int64_t pos = url_ftell(pb);
311
    int decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
312

    
313
    put_be32(pb, 0); // size
314
    put_tag(pb, "esds");
315
    put_be32(pb, 0); // Version
316

    
317
    // ES descriptor
318
    putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
319
             descrLength(1));
320
    put_be16(pb, track->trackID);
321
    put_byte(pb, 0x00); // flags (= no flags)
322

    
323
    // DecoderConfig descriptor
324
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
325

    
326
    // Object type indication
327
    if ((track->enc->codec_id == CODEC_ID_MP2 ||
328
         track->enc->codec_id == CODEC_ID_MP3) &&
329
        track->enc->sample_rate > 24000)
330
        put_byte(pb, 0x6B); // 11172-3
331
    else
332
        put_byte(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
333

    
334
    // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
335
    // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
336
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
337
        put_byte(pb, 0x15); // flags (= Audiostream)
338
    else
339
        put_byte(pb, 0x11); // flags (= Visualstream)
340

    
341
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));    // Buffersize DB (24 bits)
342
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
343

    
344
    put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
345
    if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
346
        put_be32(pb, 0); // vbr
347
    else
348
        put_be32(pb, track->enc->rc_max_rate); // avg bitrate
349

    
350
    if (track->vosLen) {
351
        // DecoderSpecific info descriptor
352
        putDescr(pb, 0x05, track->vosLen);
353
        put_buffer(pb, track->vosData, track->vosLen);
354
    }
355

    
356
    // SL descriptor
357
    putDescr(pb, 0x06, 1);
358
    put_byte(pb, 0x02);
359
    return updateSize(pb, pos);
360
}
361

    
362
static int mov_pcm_le_gt16(enum CodecID codec_id)
363
{
364
    return codec_id == CODEC_ID_PCM_S24LE ||
365
           codec_id == CODEC_ID_PCM_S32LE ||
366
           codec_id == CODEC_ID_PCM_F32LE ||
367
           codec_id == CODEC_ID_PCM_F64LE;
368
}
369

    
370
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack *track)
371
{
372
    int64_t pos = url_ftell(pb);
373

    
374
    put_be32(pb, 0);     /* size */
375
    put_tag(pb, "wave");
376

    
377
    put_be32(pb, 12);    /* size */
378
    put_tag(pb, "frma");
379
    put_le32(pb, track->tag);
380

    
381
    if (track->enc->codec_id == CODEC_ID_AAC) {
382
        /* useless atom needed by mplayer, ipod, not needed by quicktime */
383
        put_be32(pb, 12); /* size */
384
        put_tag(pb, "mp4a");
385
        put_be32(pb, 0);
386
        mov_write_esds_tag(pb, track);
387
    } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
388
        mov_write_enda_tag(pb);
389
    } else if (track->enc->codec_id == CODEC_ID_AMR_NB) {
390
        mov_write_amr_tag(pb, track);
391
    } else if (track->enc->codec_id == CODEC_ID_AC3) {
392
        mov_write_ac3_tag(pb, track);
393
    } else if (track->enc->codec_id == CODEC_ID_ALAC) {
394
        mov_write_extradata_tag(pb, track);
395
    }
396

    
397
    put_be32(pb, 8);     /* size */
398
    put_be32(pb, 0);     /* null tag */
399

    
400
    return updateSize(pb, pos);
401
}
402

    
403
static int mov_write_glbl_tag(ByteIOContext *pb, MOVTrack *track)
404
{
405
    put_be32(pb, track->vosLen+8);
406
    put_tag(pb, "glbl");
407
    put_buffer(pb, track->vosData, track->vosLen);
408
    return 8+track->vosLen;
409
}
410

    
411
/**
412
 * Compute flags for 'lpcm' tag.
413
 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
414
 */
415
static int mov_get_lpcm_flags(enum CodecID codec_id)
416
{
417
    switch (codec_id) {
418
    case CODEC_ID_PCM_F32BE:
419
    case CODEC_ID_PCM_F64BE:
420
        return 11;
421
    case CODEC_ID_PCM_F32LE:
422
    case CODEC_ID_PCM_F64LE:
423
        return 9;
424
    case CODEC_ID_PCM_U8:
425
        return 10;
426
    case CODEC_ID_PCM_S16BE:
427
    case CODEC_ID_PCM_S24BE:
428
    case CODEC_ID_PCM_S32BE:
429
        return 14;
430
    case CODEC_ID_PCM_S8:
431
    case CODEC_ID_PCM_S16LE:
432
    case CODEC_ID_PCM_S24LE:
433
    case CODEC_ID_PCM_S32LE:
434
        return 12;
435
    default:
436
        return 0;
437
    }
438
}
439

    
440
static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack *track)
441
{
442
    int64_t pos = url_ftell(pb);
443
    int version = 0;
444
    uint32_t tag = track->tag;
445

    
446
    if (track->mode == MODE_MOV) {
447
        if (track->timescale > UINT16_MAX) {
448
            if (mov_get_lpcm_flags(track->enc->codec_id))
449
                tag = AV_RL32("lpcm");
450
            version = 2;
451
        } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id)) {
452
            version = 1;
453
        }
454
    }
455

    
456
    put_be32(pb, 0); /* size */
457
    put_le32(pb, tag); // store it byteswapped
458
    put_be32(pb, 0); /* Reserved */
459
    put_be16(pb, 0); /* Reserved */
460
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
461

    
462
    /* SoundDescription */
463
    put_be16(pb, version); /* Version */
464
    put_be16(pb, 0); /* Revision level */
465
    put_be32(pb, 0); /* Reserved */
466

    
467
    if (version == 2) {
468
        put_be16(pb, 3);
469
        put_be16(pb, 16);
470
        put_be16(pb, 0xfffe);
471
        put_be16(pb, 0);
472
        put_be32(pb, 0x00010000);
473
        put_be32(pb, 72);
474
        put_be64(pb, av_dbl2int(track->timescale));
475
        put_be32(pb, track->enc->channels);
476
        put_be32(pb, 0x7F000000);
477
        put_be32(pb, av_get_bits_per_sample(track->enc->codec_id));
478
        put_be32(pb, mov_get_lpcm_flags(track->enc->codec_id));
479
        put_be32(pb, track->sampleSize);
480
        put_be32(pb, track->enc->frame_size);
481
    } else {
482
        if (track->mode == MODE_MOV) {
483
            put_be16(pb, track->enc->channels);
484
            if (track->enc->codec_id == CODEC_ID_PCM_U8 ||
485
                track->enc->codec_id == CODEC_ID_PCM_S8)
486
                put_be16(pb, 8); /* bits per sample */
487
            else
488
                put_be16(pb, 16);
489
            put_be16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
490
        } else { /* reserved for mp4/3gp */
491
            put_be16(pb, 2);
492
            put_be16(pb, 16);
493
            put_be16(pb, 0);
494
        }
495

    
496
        put_be16(pb, 0); /* packet size (= 0) */
497
        put_be16(pb, track->timescale); /* Time scale */
498
        put_be16(pb, 0); /* Reserved */
499
    }
500

    
501
    if(version == 1) { /* SoundDescription V1 extended info */
502
        put_be32(pb, track->enc->frame_size); /* Samples per packet */
503
        put_be32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
504
        put_be32(pb, track->sampleSize); /* Bytes per frame */
505
        put_be32(pb, 2); /* Bytes per sample */
506
    }
507

    
508
    if(track->mode == MODE_MOV &&
509
       (track->enc->codec_id == CODEC_ID_AAC ||
510
        track->enc->codec_id == CODEC_ID_AC3 ||
511
        track->enc->codec_id == CODEC_ID_AMR_NB ||
512
        track->enc->codec_id == CODEC_ID_ALAC ||
513
        mov_pcm_le_gt16(track->enc->codec_id)))
514
        mov_write_wave_tag(pb, track);
515
    else if(track->tag == MKTAG('m','p','4','a'))
516
        mov_write_esds_tag(pb, track);
517
    else if(track->enc->codec_id == CODEC_ID_AMR_NB)
518
        mov_write_amr_tag(pb, track);
519
    else if(track->enc->codec_id == CODEC_ID_AC3)
520
        mov_write_ac3_tag(pb, track);
521
    else if(track->enc->codec_id == CODEC_ID_ALAC)
522
        mov_write_extradata_tag(pb, track);
523
    else if(track->vosLen > 0)
524
        mov_write_glbl_tag(pb, track);
525

    
526
    return updateSize(pb, pos);
527
}
528

    
529
static int mov_write_d263_tag(ByteIOContext *pb)
530
{
531
    put_be32(pb, 0xf); /* size */
532
    put_tag(pb, "d263");
533
    put_tag(pb, "FFMP");
534
    put_byte(pb, 0); /* decoder version */
535
    /* FIXME use AVCodecContext level/profile, when encoder will set values */
536
    put_byte(pb, 0xa); /* level */
537
    put_byte(pb, 0); /* profile */
538
    return 0xf;
539
}
540

    
541
/* TODO: No idea about these values */
542
static int mov_write_svq3_tag(ByteIOContext *pb)
543
{
544
    put_be32(pb, 0x15);
545
    put_tag(pb, "SMI ");
546
    put_tag(pb, "SEQH");
547
    put_be32(pb, 0x5);
548
    put_be32(pb, 0xe2c0211d);
549
    put_be32(pb, 0xc0000000);
550
    put_byte(pb, 0);
551
    return 0x15;
552
}
553

    
554
static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
555
{
556
    int64_t pos = url_ftell(pb);
557

    
558
    put_be32(pb, 0);
559
    put_tag(pb, "avcC");
560
    ff_isom_write_avcc(pb, track->vosData, track->vosLen);
561
    return updateSize(pb, pos);
562
}
563

    
564
/* also used by all avid codecs (dv, imx, meridien) and their variants */
565
static int mov_write_avid_tag(ByteIOContext *pb, MOVTrack *track)
566
{
567
    int i;
568
    put_be32(pb, 24); /* size */
569
    put_tag(pb, "ACLR");
570
    put_tag(pb, "ACLR");
571
    put_tag(pb, "0001");
572
    put_be32(pb, 1); /* yuv 1 / rgb 2 ? */
573
    put_be32(pb, 0); /* unknown */
574

    
575
    put_be32(pb, 24); /* size */
576
    put_tag(pb, "APRG");
577
    put_tag(pb, "APRG");
578
    put_tag(pb, "0001");
579
    put_be32(pb, 1); /* unknown */
580
    put_be32(pb, 0); /* unknown */
581

    
582
    put_be32(pb, 120); /* size */
583
    put_tag(pb, "ARES");
584
    put_tag(pb, "ARES");
585
    put_tag(pb, "0001");
586
    put_be32(pb, AV_RB32(track->vosData + 0x28)); /* dnxhd cid, some id ? */
587
    put_be32(pb, track->enc->width);
588
    /* values below are based on samples created with quicktime and avid codecs */
589
    if (track->vosData[5] & 2) { // interlaced
590
        put_be32(pb, track->enc->height/2);
591
        put_be32(pb, 2); /* unknown */
592
        put_be32(pb, 0); /* unknown */
593
        put_be32(pb, 4); /* unknown */
594
    } else {
595
        put_be32(pb, track->enc->height);
596
        put_be32(pb, 1); /* unknown */
597
        put_be32(pb, 0); /* unknown */
598
        if (track->enc->height == 1080)
599
            put_be32(pb, 5); /* unknown */
600
        else
601
            put_be32(pb, 6); /* unknown */
602
    }
603
    /* padding */
604
    for (i = 0; i < 10; i++)
605
        put_be64(pb, 0);
606

    
607
    /* extra padding for stsd needed */
608
    put_be32(pb, 0);
609
    return 0;
610
}
611

    
612
static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
613
{
614
    int tag = track->enc->codec_tag;
615

    
616
    if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
617
        return 0;
618

    
619
    if      (track->enc->codec_id == CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
620
    else if (track->enc->codec_id == CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
621
    else if (track->enc->codec_id == CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
622
    else if (track->enc->codec_id == CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
623
    else if (track->enc->codec_type == CODEC_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
624
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
625

    
626
    return tag;
627
}
628

    
629
static const AVCodecTag codec_ipod_tags[] = {
630
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
631
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
632
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
633
    { CODEC_ID_ALAC,   MKTAG('a','l','a','c') },
634
    { CODEC_ID_AC3,    MKTAG('a','c','-','3') },
635
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
636
    { CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
637
    { CODEC_ID_NONE, 0 },
638
};
639

    
640
static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
641
{
642
    int tag = track->enc->codec_tag;
643

    
644
    // keep original tag for subs, ipod supports both formats
645
    if (!(track->enc->codec_type == CODEC_TYPE_SUBTITLE &&
646
        (tag == MKTAG('t','x','3','g') ||
647
         tag == MKTAG('t','e','x','t'))))
648
        tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
649

    
650
    if (!av_match_ext(s->filename, "m4a") && !av_match_ext(s->filename, "m4v"))
651
        av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
652
               "Quicktime/Ipod might not play the file\n");
653

    
654
    return tag;
655
}
656

    
657
static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
658
{
659
    int tag;
660

    
661
    if (track->enc->height == 480) /* NTSC */
662
        if  (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
663
        else                                         tag = MKTAG('d','v','c',' ');
664
    else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
665
    else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
666
    else                                             tag = MKTAG('d','v','p','p');
667

    
668
    return tag;
669
}
670

    
671
static const struct {
672
    enum PixelFormat pix_fmt;
673
    uint32_t tag;
674
    unsigned bps;
675
} mov_pix_fmt_tags[] = {
676
    { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
677
    { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
678
    { PIX_FMT_BGR555,  MKTAG('r','a','w',' '), 16 },
679
    { PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
680
    { PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
681
    { PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
682
    { PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
683
    { PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
684
    { PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
685
    { PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
686
    { PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
687
};
688

    
689
static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
690
{
691
    int tag = track->enc->codec_tag;
692
    int i;
693

    
694
    for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
695
        if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
696
            tag = mov_pix_fmt_tags[i].tag;
697
            track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
698
            break;
699
        }
700
    }
701

    
702
    return tag;
703
}
704

    
705
static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
706
{
707
    int tag = track->enc->codec_tag;
708

    
709
    if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
710
                 (tag == MKTAG('d','v','c','p') ||
711
                  track->enc->codec_id == CODEC_ID_RAWVIDEO ||
712
                  av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
713
        if (track->enc->codec_id == CODEC_ID_DVVIDEO)
714
            tag = mov_get_dv_codec_tag(s, track);
715
        else if (track->enc->codec_id == CODEC_ID_RAWVIDEO)
716
            tag = mov_get_rawvideo_codec_tag(s, track);
717
        else if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
718
            tag = ff_codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
719
            if (!tag) { // if no mac fcc found, try with Microsoft tags
720
                tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
721
                if (tag)
722
                    av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, "
723
                           "the file may be unplayable!\n");
724
            }
725
        } else if (track->enc->codec_type == CODEC_TYPE_AUDIO) {
726
            tag = ff_codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
727
            if (!tag) { // if no mac fcc found, try with Microsoft tags
728
                int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
729
                if (ms_tag) {
730
                    tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
731
                    av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, "
732
                           "the file may be unplayable!\n");
733
                }
734
            }
735
        } else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE)
736
            tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
737
    }
738

    
739
    return tag;
740
}
741

    
742
static const AVCodecTag codec_3gp_tags[] = {
743
    { CODEC_ID_H263,   MKTAG('s','2','6','3') },
744
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
745
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
746
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
747
    { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
748
    { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
749
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
750
    { CODEC_ID_NONE, 0 },
751
};
752

    
753
static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
754
{
755
    int tag = track->enc->codec_tag;
756

    
757
    if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
758
        tag = mp4_get_codec_tag(s, track);
759
    else if (track->mode == MODE_IPOD)
760
        tag = ipod_get_codec_tag(s, track);
761
    else if (track->mode & MODE_3GP)
762
        tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
763
    else
764
        tag = mov_get_codec_tag(s, track);
765

    
766
    return tag;
767
}
768

    
769
/** Write uuid atom.
770
 * Needed to make file play in iPods running newest firmware
771
 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
772
 */
773
static int mov_write_uuid_tag_ipod(ByteIOContext *pb)
774
{
775
    put_be32(pb, 28);
776
    put_tag(pb, "uuid");
777
    put_be32(pb, 0x6b6840f2);
778
    put_be32(pb, 0x5f244fc5);
779
    put_be32(pb, 0xba39a51b);
780
    put_be32(pb, 0xcf0323f3);
781
    put_be32(pb, 0x0);
782
    return 28;
783
}
784

    
785
static int mov_write_subtitle_tag(ByteIOContext *pb, MOVTrack *track)
786
{
787
    int64_t pos = url_ftell(pb);
788
    put_be32(pb, 0);    /* size */
789
    put_le32(pb, track->tag); // store it byteswapped
790
    put_be32(pb, 0);    /* Reserved */
791
    put_be16(pb, 0);    /* Reserved */
792
    put_be16(pb, 1);    /* Data-reference index */
793

    
794
    if (track->enc->extradata_size)
795
        put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
796

    
797
    return updateSize(pb, pos);
798
}
799

    
800
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack *track)
801
{
802
    int64_t pos = url_ftell(pb);
803
    char compressor_name[32];
804

    
805
    put_be32(pb, 0); /* size */
806
    put_le32(pb, track->tag); // store it byteswapped
807
    put_be32(pb, 0); /* Reserved */
808
    put_be16(pb, 0); /* Reserved */
809
    put_be16(pb, 1); /* Data-reference index */
810

    
811
    put_be16(pb, 0); /* Codec stream version */
812
    put_be16(pb, 0); /* Codec stream revision (=0) */
813
    if (track->mode == MODE_MOV) {
814
        put_tag(pb, "FFMP"); /* Vendor */
815
        if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
816
            put_be32(pb, 0); /* Temporal Quality */
817
            put_be32(pb, 0x400); /* Spatial Quality = lossless*/
818
        } else {
819
            put_be32(pb, 0x200); /* Temporal Quality = normal */
820
            put_be32(pb, 0x200); /* Spatial Quality = normal */
821
        }
822
    } else {
823
        put_be32(pb, 0); /* Reserved */
824
        put_be32(pb, 0); /* Reserved */
825
        put_be32(pb, 0); /* Reserved */
826
    }
827
    put_be16(pb, track->enc->width); /* Video width */
828
    put_be16(pb, track->height); /* Video height */
829
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
830
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
831
    put_be32(pb, 0); /* Data size (= 0) */
832
    put_be16(pb, 1); /* Frame count (= 1) */
833

    
834
    memset(compressor_name,0,32);
835
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
836
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
837
        strncpy(compressor_name,track->enc->codec->name,31);
838
    put_byte(pb, strlen(compressor_name));
839
    put_buffer(pb, compressor_name, 31);
840

    
841
    if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
842
        put_be16(pb, track->enc->bits_per_coded_sample);
843
    else
844
        put_be16(pb, 0x18); /* Reserved */
845
    put_be16(pb, 0xffff); /* Reserved */
846
    if(track->tag == MKTAG('m','p','4','v'))
847
        mov_write_esds_tag(pb, track);
848
    else if(track->enc->codec_id == CODEC_ID_H263)
849
        mov_write_d263_tag(pb);
850
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
851
        mov_write_svq3_tag(pb);
852
    else if(track->enc->codec_id == CODEC_ID_DNXHD)
853
        mov_write_avid_tag(pb, track);
854
    else if(track->enc->codec_id == CODEC_ID_H264) {
855
        mov_write_avcc_tag(pb, track);
856
        if(track->mode == MODE_IPOD)
857
            mov_write_uuid_tag_ipod(pb);
858
    } else if(track->vosLen > 0)
859
        mov_write_glbl_tag(pb, track);
860

    
861
    return updateSize(pb, pos);
862
}
863

    
864
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack *track)
865
{
866
    int64_t pos = url_ftell(pb);
867
    put_be32(pb, 0); /* size */
868
    put_tag(pb, "stsd");
869
    put_be32(pb, 0); /* version & flags */
870
    put_be32(pb, 1); /* entry count */
871
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
872
        mov_write_video_tag(pb, track);
873
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
874
        mov_write_audio_tag(pb, track);
875
    else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE)
876
        mov_write_subtitle_tag(pb, track);
877
    return updateSize(pb, pos);
878
}
879

    
880
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack *track)
881
{
882
    MOVStts *ctts_entries;
883
    uint32_t entries = 0;
884
    uint32_t atom_size;
885
    int i;
886

    
887
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
888
    ctts_entries[0].count = 1;
889
    ctts_entries[0].duration = track->cluster[0].cts;
890
    for (i=1; i<track->entry; i++) {
891
        if (track->cluster[i].cts == ctts_entries[entries].duration) {
892
            ctts_entries[entries].count++; /* compress */
893
        } else {
894
            entries++;
895
            ctts_entries[entries].duration = track->cluster[i].cts;
896
            ctts_entries[entries].count = 1;
897
        }
898
    }
899
    entries++; /* last one */
900
    atom_size = 16 + (entries * 8);
901
    put_be32(pb, atom_size); /* size */
902
    put_tag(pb, "ctts");
903
    put_be32(pb, 0); /* version & flags */
904
    put_be32(pb, entries); /* entry count */
905
    for (i=0; i<entries; i++) {
906
        put_be32(pb, ctts_entries[i].count);
907
        put_be32(pb, ctts_entries[i].duration);
908
    }
909
    av_free(ctts_entries);
910
    return atom_size;
911
}
912

    
913
/* Time to sample atom */
914
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack *track)
915
{
916
    MOVStts *stts_entries;
917
    uint32_t entries = -1;
918
    uint32_t atom_size;
919
    int i;
920

    
921
    if (track->enc->codec_type == CODEC_TYPE_AUDIO && !track->audio_vbr) {
922
        stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
923
        stts_entries[0].count = track->sampleCount;
924
        stts_entries[0].duration = 1;
925
        entries = 1;
926
    } else {
927
        stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
928
        for (i=0; i<track->entry; i++) {
929
            int64_t duration = i + 1 == track->entry ?
930
                track->trackDuration - track->cluster[i].dts + track->cluster[0].dts : /* readjusting */
931
                track->cluster[i+1].dts - track->cluster[i].dts;
932
            if (i && duration == stts_entries[entries].duration) {
933
                stts_entries[entries].count++; /* compress */
934
            } else {
935
                entries++;
936
                stts_entries[entries].duration = duration;
937
                stts_entries[entries].count = 1;
938
            }
939
        }
940
        entries++; /* last one */
941
    }
942
    atom_size = 16 + (entries * 8);
943
    put_be32(pb, atom_size); /* size */
944
    put_tag(pb, "stts");
945
    put_be32(pb, 0); /* version & flags */
946
    put_be32(pb, entries); /* entry count */
947
    for (i=0; i<entries; i++) {
948
        put_be32(pb, stts_entries[i].count);
949
        put_be32(pb, stts_entries[i].duration);
950
    }
951
    av_free(stts_entries);
952
    return atom_size;
953
}
954

    
955
static int mov_write_dref_tag(ByteIOContext *pb)
956
{
957
    put_be32(pb, 28); /* size */
958
    put_tag(pb, "dref");
959
    put_be32(pb, 0); /* version & flags */
960
    put_be32(pb, 1); /* entry count */
961

    
962
    put_be32(pb, 0xc); /* size */
963
    put_tag(pb, "url ");
964
    put_be32(pb, 1); /* version & flags */
965

    
966
    return 28;
967
}
968

    
969
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack *track)
970
{
971
    int64_t pos = url_ftell(pb);
972
    put_be32(pb, 0); /* size */
973
    put_tag(pb, "stbl");
974
    mov_write_stsd_tag(pb, track);
975
    mov_write_stts_tag(pb, track);
976
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
977
        track->hasKeyframes && track->hasKeyframes < track->entry)
978
        mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
979
    if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
980
        mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
981
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
982
        track->flags & MOV_TRACK_CTTS)
983
        mov_write_ctts_tag(pb, track);
984
    mov_write_stsc_tag(pb, track);
985
    mov_write_stsz_tag(pb, track);
986
    mov_write_stco_tag(pb, track);
987
    return updateSize(pb, pos);
988
}
989

    
990
static int mov_write_dinf_tag(ByteIOContext *pb)
991
{
992
    int64_t pos = url_ftell(pb);
993
    put_be32(pb, 0); /* size */
994
    put_tag(pb, "dinf");
995
    mov_write_dref_tag(pb);
996
    return updateSize(pb, pos);
997
}
998

    
999
static int mov_write_nmhd_tag(ByteIOContext *pb)
1000
{
1001
    put_be32(pb, 12);
1002
    put_tag(pb, "nmhd");
1003
    put_be32(pb, 0);
1004
    return 12;
1005
}
1006

    
1007
static int mov_write_gmhd_tag(ByteIOContext *pb)
1008
{
1009
    put_be32(pb, 0x20);   /* size */
1010
    put_tag(pb, "gmhd");
1011
    put_be32(pb, 0x18);   /* gmin size */
1012
    put_tag(pb, "gmin");  /* generic media info */
1013
    put_be32(pb, 0);      /* version & flags */
1014
    put_be16(pb, 0x40);   /* graphics mode = */
1015
    put_be16(pb, 0x8000); /* opColor (r?) */
1016
    put_be16(pb, 0x8000); /* opColor (g?) */
1017
    put_be16(pb, 0x8000); /* opColor (b?) */
1018
    put_be16(pb, 0);      /* balance */
1019
    put_be16(pb, 0);      /* reserved */
1020
    return 0x20;
1021
}
1022

    
1023
static int mov_write_smhd_tag(ByteIOContext *pb)
1024
{
1025
    put_be32(pb, 16); /* size */
1026
    put_tag(pb, "smhd");
1027
    put_be32(pb, 0); /* version & flags */
1028
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
1029
    put_be16(pb, 0); /* reserved */
1030
    return 16;
1031
}
1032

    
1033
static int mov_write_vmhd_tag(ByteIOContext *pb)
1034
{
1035
    put_be32(pb, 0x14); /* size (always 0x14) */
1036
    put_tag(pb, "vmhd");
1037
    put_be32(pb, 0x01); /* version & flags */
1038
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
1039
    return 0x14;
1040
}
1041

    
1042
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)
1043
{
1044
    const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1045
    int64_t pos = url_ftell(pb);
1046

    
1047
    if (!track) { /* no media --> data handler */
1048
        hdlr = "dhlr";
1049
        hdlr_type = "url ";
1050
        descr = "DataHandler";
1051
    } else {
1052
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1053
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
1054
            hdlr_type = "vide";
1055
            descr = "VideoHandler";
1056
        } else if (track->enc->codec_type == CODEC_TYPE_AUDIO) {
1057
            hdlr_type = "soun";
1058
            descr = "SoundHandler";
1059
        } else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
1060
            if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
1061
            else                                      hdlr_type = "text";
1062
            descr = "SubtitleHandler";
1063
        }
1064
    }
1065

    
1066
    put_be32(pb, 0); /* size */
1067
    put_tag(pb, "hdlr");
1068
    put_be32(pb, 0); /* Version & flags */
1069
    put_buffer(pb, hdlr, 4); /* handler */
1070
    put_tag(pb, hdlr_type); /* handler type */
1071
    put_be32(pb ,0); /* reserved */
1072
    put_be32(pb ,0); /* reserved */
1073
    put_be32(pb ,0); /* reserved */
1074
    if (!track || track->mode == MODE_MOV)
1075
        put_byte(pb, strlen(descr)); /* pascal string */
1076
    put_buffer(pb, descr, strlen(descr)); /* handler description */
1077
    if (track && track->mode != MODE_MOV)
1078
        put_byte(pb, 0); /* c string */
1079
    return updateSize(pb, pos);
1080
}
1081

    
1082
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack *track)
1083
{
1084
    int64_t pos = url_ftell(pb);
1085
    put_be32(pb, 0); /* size */
1086
    put_tag(pb, "minf");
1087
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
1088
        mov_write_vmhd_tag(pb);
1089
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
1090
        mov_write_smhd_tag(pb);
1091
    else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
1092
        if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb);
1093
        else                                      mov_write_nmhd_tag(pb);
1094
    }
1095
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1096
        mov_write_hdlr_tag(pb, NULL);
1097
    mov_write_dinf_tag(pb);
1098
    mov_write_stbl_tag(pb, track);
1099
    return updateSize(pb, pos);
1100
}
1101

    
1102
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack *track)
1103
{
1104
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
1105

    
1106
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
1107
    put_tag(pb, "mdhd");
1108
    put_byte(pb, version);
1109
    put_be24(pb, 0); /* flags */
1110
    if (version == 1) {
1111
        put_be64(pb, track->time);
1112
        put_be64(pb, track->time);
1113
    } else {
1114
        put_be32(pb, track->time); /* creation time */
1115
        put_be32(pb, track->time); /* modification time */
1116
    }
1117
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
1118
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
1119
    put_be16(pb, track->language); /* language */
1120
    put_be16(pb, 0); /* reserved (quality) */
1121

    
1122
    if(version!=0 && track->mode == MODE_MOV){
1123
        av_log(NULL, AV_LOG_ERROR,
1124
            "FATAL error, file duration too long for timebase, this file will not be\n"
1125
            "playable with quicktime. Choose a different timebase or a different\n"
1126
            "container format\n");
1127
    }
1128

    
1129
    return 32;
1130
}
1131

    
1132
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack *track)
1133
{
1134
    int64_t pos = url_ftell(pb);
1135
    put_be32(pb, 0); /* size */
1136
    put_tag(pb, "mdia");
1137
    mov_write_mdhd_tag(pb, track);
1138
    mov_write_hdlr_tag(pb, track);
1139
    mov_write_minf_tag(pb, track);
1140
    return updateSize(pb, pos);
1141
}
1142

    
1143
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1144
{
1145
    int64_t duration = av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1146
                                      track->timescale, AV_ROUND_UP);
1147
    int version = duration < INT32_MAX ? 0 : 1;
1148

    
1149
    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
1150
    put_tag(pb, "tkhd");
1151
    put_byte(pb, version);
1152
    put_be24(pb, 0xf); /* flags (track enabled) */
1153
    if (version == 1) {
1154
        put_be64(pb, track->time);
1155
        put_be64(pb, track->time);
1156
    } else {
1157
        put_be32(pb, track->time); /* creation time */
1158
        put_be32(pb, track->time); /* modification time */
1159
    }
1160
    put_be32(pb, track->trackID); /* track-id */
1161
    put_be32(pb, 0); /* reserved */
1162
    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
1163

    
1164
    put_be32(pb, 0); /* reserved */
1165
    put_be32(pb, 0); /* reserved */
1166
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
1167
    /* Volume, only for audio */
1168
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
1169
        put_be16(pb, 0x0100);
1170
    else
1171
        put_be16(pb, 0);
1172
    put_be16(pb, 0); /* reserved */
1173

    
1174
    /* Matrix structure */
1175
    put_be32(pb, 0x00010000); /* reserved */
1176
    put_be32(pb, 0x0); /* reserved */
1177
    put_be32(pb, 0x0); /* reserved */
1178
    put_be32(pb, 0x0); /* reserved */
1179
    put_be32(pb, 0x00010000); /* reserved */
1180
    put_be32(pb, 0x0); /* reserved */
1181
    put_be32(pb, 0x0); /* reserved */
1182
    put_be32(pb, 0x0); /* reserved */
1183
    put_be32(pb, 0x40000000); /* reserved */
1184

    
1185
    /* Track width and height, for visual only */
1186
    if(track->enc->codec_type == CODEC_TYPE_VIDEO ||
1187
       track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
1188
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1189
        if(!sample_aspect_ratio || track->height != track->enc->height)
1190
            sample_aspect_ratio = 1;
1191
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1192
        put_be32(pb, track->height*0x10000);
1193
    }
1194
    else {
1195
        put_be32(pb, 0);
1196
        put_be32(pb, 0);
1197
    }
1198
    return 0x5c;
1199
}
1200

    
1201
// This box seems important for the psp playback ... without it the movie seems to hang
1202
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
1203
{
1204
    put_be32(pb, 0x24); /* size  */
1205
    put_tag(pb, "edts");
1206
    put_be32(pb, 0x1c); /* size  */
1207
    put_tag(pb, "elst");
1208
    put_be32(pb, 0x0);
1209
    put_be32(pb, 0x1);
1210

    
1211
    /* duration   ... doesn't seem to effect psp */
1212
    put_be32(pb, av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1213
                                track->timescale, AV_ROUND_UP));
1214

    
1215
    put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
1216
    put_be32(pb, 0x00010000);
1217
    return 0x24;
1218
}
1219

    
1220
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1221
static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
1222
{
1223
    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1224
    put_tag(pb, "uuid");
1225
    put_tag(pb, "USMT");
1226
    put_be32(pb, 0x21d24fce);
1227
    put_be32(pb, 0xbb88695c);
1228
    put_be32(pb, 0xfac9c740);
1229
    put_be32(pb, 0x1c);     // another size here!
1230
    put_tag(pb, "MTDT");
1231
    put_be32(pb, 0x00010012);
1232
    put_be32(pb, 0x0a);
1233
    put_be32(pb, 0x55c40000);
1234
    put_be32(pb, 0x1);
1235
    put_be32(pb, 0x0);
1236
    return 0x34;
1237
}
1238

    
1239
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1240
{
1241
    int64_t pos = url_ftell(pb);
1242
    put_be32(pb, 0); /* size */
1243
    put_tag(pb, "trak");
1244
    mov_write_tkhd_tag(pb, track, st);
1245
    if (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS)
1246
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1247
    mov_write_mdia_tag(pb, track);
1248
    if (track->mode == MODE_PSP)
1249
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1250
    return updateSize(pb, pos);
1251
}
1252

    
1253
#if 0
1254
/* TODO: Not sorted out, but not necessary either */
1255
static int mov_write_iods_tag(ByteIOContext *pb, MOVMuxContext *mov)
1256
{
1257
    put_be32(pb, 0x15); /* size */
1258
    put_tag(pb, "iods");
1259
    put_be32(pb, 0);    /* version & flags */
1260
    put_be16(pb, 0x1007);
1261
    put_byte(pb, 0);
1262
    put_be16(pb, 0x4fff);
1263
    put_be16(pb, 0xfffe);
1264
    put_be16(pb, 0x01ff);
1265
    return 0x15;
1266
}
1267
#endif
1268

    
1269
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVMuxContext *mov)
1270
{
1271
    int maxTrackID = 1, i;
1272
    int64_t maxTrackLenTemp, maxTrackLen = 0;
1273
    int version;
1274

    
1275
    for (i=0; i<mov->nb_streams; i++) {
1276
        if(mov->tracks[i].entry > 0) {
1277
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration,
1278
                                             MOV_TIMESCALE,
1279
                                             mov->tracks[i].timescale,
1280
                                             AV_ROUND_UP);
1281
            if(maxTrackLen < maxTrackLenTemp)
1282
                maxTrackLen = maxTrackLenTemp;
1283
            if(maxTrackID < mov->tracks[i].trackID)
1284
                maxTrackID = mov->tracks[i].trackID;
1285
        }
1286
    }
1287

    
1288
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1289
    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1290
    put_tag(pb, "mvhd");
1291
    put_byte(pb, version);
1292
    put_be24(pb, 0); /* flags */
1293
    if (version == 1) {
1294
        put_be64(pb, mov->time);
1295
        put_be64(pb, mov->time);
1296
    } else {
1297
        put_be32(pb, mov->time); /* creation time */
1298
        put_be32(pb, mov->time); /* modification time */
1299
    }
1300
    put_be32(pb, MOV_TIMESCALE);
1301
    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1302

    
1303
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1304
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1305
    put_be16(pb, 0); /* reserved */
1306
    put_be32(pb, 0); /* reserved */
1307
    put_be32(pb, 0); /* reserved */
1308

    
1309
    /* Matrix structure */
1310
    put_be32(pb, 0x00010000); /* reserved */
1311
    put_be32(pb, 0x0); /* reserved */
1312
    put_be32(pb, 0x0); /* reserved */
1313
    put_be32(pb, 0x0); /* reserved */
1314
    put_be32(pb, 0x00010000); /* reserved */
1315
    put_be32(pb, 0x0); /* reserved */
1316
    put_be32(pb, 0x0); /* reserved */
1317
    put_be32(pb, 0x0); /* reserved */
1318
    put_be32(pb, 0x40000000); /* reserved */
1319

    
1320
    put_be32(pb, 0); /* reserved (preview time) */
1321
    put_be32(pb, 0); /* reserved (preview duration) */
1322
    put_be32(pb, 0); /* reserved (poster time) */
1323
    put_be32(pb, 0); /* reserved (selection time) */
1324
    put_be32(pb, 0); /* reserved (selection duration) */
1325
    put_be32(pb, 0); /* reserved (current time) */
1326
    put_be32(pb, maxTrackID+1); /* Next track id */
1327
    return 0x6c;
1328
}
1329

    
1330
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVMuxContext *mov,
1331
                                     AVFormatContext *s)
1332
{
1333
    int64_t pos = url_ftell(pb);
1334
    put_be32(pb, 0); /* size */
1335
    put_tag(pb, "hdlr");
1336
    put_be32(pb, 0);
1337
    put_be32(pb, 0);
1338
    put_tag(pb, "mdir");
1339
    put_tag(pb, "appl");
1340
    put_be32(pb, 0);
1341
    put_be32(pb, 0);
1342
    put_byte(pb, 0);
1343
    return updateSize(pb, pos);
1344
}
1345

    
1346
/* helper function to write a data tag with the specified string as data */
1347
static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int lang, int long_style)
1348
{
1349
    if(long_style){
1350
        int64_t pos = url_ftell(pb);
1351
        put_be32(pb, 0); /* size */
1352
        put_tag(pb, "data");
1353
        put_be32(pb, 1);
1354
        put_be32(pb, 0);
1355
        put_buffer(pb, data, strlen(data));
1356
        return updateSize(pb, pos);
1357
    }else{
1358
        put_be16(pb, strlen(data)); /* string length */
1359
        put_be16(pb, lang);
1360
        put_buffer(pb, data, strlen(data));
1361
        return strlen(data) + 4;
1362
    }
1363
}
1364

    
1365
static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int lang, int long_style){
1366
    int size = 0;
1367
    if (value && value[0]) {
1368
        int64_t pos = url_ftell(pb);
1369
        put_be32(pb, 0); /* size */
1370
        put_tag(pb, name);
1371
        mov_write_string_data_tag(pb, value, lang, long_style);
1372
        size= updateSize(pb, pos);
1373
    }
1374
    return size;
1375
}
1376

    
1377
static int mov_write_string_metadata(AVFormatContext *s, ByteIOContext *pb,
1378
                                     const char *name, const char *tag,
1379
                                     int long_style)
1380
{
1381
    int l, lang = 0, len, len2;
1382
    AVMetadataTag *t, *t2 = NULL;
1383
    char tag2[16];
1384

    
1385
    if (!(t = av_metadata_get(s->metadata, tag, NULL, 0)))
1386
        return 0;
1387

    
1388
    len = strlen(t->key);
1389
    snprintf(tag2, sizeof(tag2), "%s-", tag);
1390
    while ((t2 = av_metadata_get(s->metadata, tag2, t2, AV_METADATA_IGNORE_SUFFIX))) {
1391
        len2 = strlen(t2->key);
1392
        if (len2 == len+4 && !strcmp(t->value, t2->value)
1393
            && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 0)) >= 0) {
1394
            lang = l;
1395
            break;
1396
        }
1397
    }
1398
    return mov_write_string_tag(pb, name, t->value, lang, long_style);
1399
}
1400

    
1401
/* iTunes track number */
1402
static int mov_write_trkn_tag(ByteIOContext *pb, MOVMuxContext *mov,
1403
                              AVFormatContext *s)
1404
{
1405
    AVMetadataTag *t = av_metadata_get(s->metadata, "track", NULL, 0);
1406
    int size = 0, track = t ? atoi(t->value) : 0;
1407
    if (track) {
1408
        int64_t pos = url_ftell(pb);
1409
        put_be32(pb, 0); /* size */
1410
        put_tag(pb, "trkn");
1411
        {
1412
            int64_t pos = url_ftell(pb);
1413
            put_be32(pb, 0); /* size */
1414
            put_tag(pb, "data");
1415
            put_be32(pb, 0);        // 8 bytes empty
1416
            put_be32(pb, 0);
1417
            put_be16(pb, 0);        // empty
1418
            put_be16(pb, track);    // track number
1419
            put_be16(pb, 0);        // total track number
1420
            put_be16(pb, 0);        // empty
1421
            updateSize(pb, pos);
1422
        }
1423
        size = updateSize(pb, pos);
1424
    }
1425
    return size;
1426
}
1427

    
1428
/* iTunes meta data list */
1429
static int mov_write_ilst_tag(ByteIOContext *pb, MOVMuxContext *mov,
1430
                              AVFormatContext *s)
1431
{
1432
    int64_t pos = url_ftell(pb);
1433
    put_be32(pb, 0); /* size */
1434
    put_tag(pb, "ilst");
1435
    mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1436
    mov_write_string_metadata(s, pb, "\251ART", "author"   , 1);
1437
    mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
1438
    mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1439
    mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1440
    mov_write_string_metadata(s, pb, "\251day", "year"     , 1);
1441
    mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1442
    mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1443
    mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1444
    mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1445
    mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
1446
    mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
1447
    mov_write_string_metadata(s, pb, "desc",    "description",1);
1448
    mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
1449
    mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
1450
    mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
1451
    mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
1452
    mov_write_trkn_tag(pb, mov, s);
1453
    return updateSize(pb, pos);
1454
}
1455

    
1456
/* iTunes meta data tag */
1457
static int mov_write_meta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1458
                              AVFormatContext *s)
1459
{
1460
    int size = 0;
1461
    int64_t pos = url_ftell(pb);
1462
    put_be32(pb, 0); /* size */
1463
    put_tag(pb, "meta");
1464
    put_be32(pb, 0);
1465
    mov_write_itunes_hdlr_tag(pb, mov, s);
1466
    mov_write_ilst_tag(pb, mov, s);
1467
    size = updateSize(pb, pos);
1468
    return size;
1469
}
1470

    
1471
static int utf8len(const uint8_t *b)
1472
{
1473
    int len=0;
1474
    int val;
1475
    while(*b){
1476
        GET_UTF8(val, *b++, return -1;)
1477
        len++;
1478
    }
1479
    return len;
1480
}
1481

    
1482
static int ascii_to_wc(ByteIOContext *pb, const uint8_t *b)
1483
{
1484
    int val;
1485
    while(*b){
1486
        GET_UTF8(val, *b++, return -1;)
1487
        put_be16(pb, val);
1488
    }
1489
    put_be16(pb, 0x00);
1490
    return 0;
1491
}
1492

    
1493
static uint16_t language_code(const char *str)
1494
{
1495
    return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1496
}
1497

    
1498
static int mov_write_3gp_udta_tag(ByteIOContext *pb, AVFormatContext *s,
1499
                                  const char *tag, const char *str)
1500
{
1501
    int64_t pos = url_ftell(pb);
1502
    AVMetadataTag *t = av_metadata_get(s->metadata, str, NULL, 0);
1503
    if (!t || !utf8len(t->value))
1504
        return 0;
1505
    put_be32(pb, 0);   /* size */
1506
    put_tag (pb, tag); /* type */
1507
    put_be32(pb, 0);   /* version + flags */
1508
    if (!strcmp(tag, "yrrc"))
1509
        put_be16(pb, atoi(t->value));
1510
    else {
1511
        put_be16(pb, language_code("eng")); /* language */
1512
        put_buffer(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
1513
        if (!strcmp(tag, "albm") &&
1514
            (t = av_metadata_get(s->metadata, "year", NULL, 0)))
1515
            put_byte(pb, atoi(t->value));
1516
    }
1517
    return updateSize(pb, pos);
1518
}
1519

    
1520
static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1521
                              AVFormatContext *s)
1522
{
1523
    ByteIOContext *pb_buf;
1524
    int i, ret, size;
1525
    uint8_t *buf;
1526

    
1527
    for (i = 0; i < s->nb_streams; i++)
1528
        if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1529
            return 0;
1530
        }
1531

    
1532
    ret = url_open_dyn_buf(&pb_buf);
1533
    if(ret < 0)
1534
        return ret;
1535

    
1536
        if (mov->mode & MODE_3GP) {
1537
            mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1538
            mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1539
            mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1540
            mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1541
            mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1542
            mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1543
            mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "year");
1544
        } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1545
            mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
1546
            mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
1547
            mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
1548
            mov_write_string_metadata(s, pb_buf, "\251day", "year"       , 0);
1549
            mov_write_string_tag(pb_buf, "\251enc", LIBAVFORMAT_IDENT, 0, 0);
1550
            mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
1551
            mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
1552
            mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
1553
        } else {
1554
            /* iTunes meta data */
1555
            mov_write_meta_tag(pb_buf, mov, s);
1556
        }
1557

    
1558
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1559
        put_be32(pb, size+8);
1560
        put_tag(pb, "udta");
1561
        put_buffer(pb, buf, size);
1562
        av_free(buf);
1563
    }
1564

    
1565
    return 0;
1566
}
1567

    
1568
static void mov_write_psp_udta_tag(ByteIOContext *pb,
1569
                                  const char *str, const char *lang, int type)
1570
{
1571
    int len = utf8len(str)+1;
1572
    if(len<=0)
1573
        return;
1574
    put_be16(pb, len*2+10);            /* size */
1575
    put_be32(pb, type);                /* type */
1576
    put_be16(pb, language_code(lang)); /* language */
1577
    put_be16(pb, 0x01);                /* ? */
1578
    ascii_to_wc(pb, str);
1579
}
1580

    
1581
static int mov_write_uuidusmt_tag(ByteIOContext *pb, AVFormatContext *s)
1582
{
1583
    AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
1584
    int64_t pos, pos2;
1585

    
1586
    if (title) {
1587
        pos = url_ftell(pb);
1588
        put_be32(pb, 0); /* size placeholder*/
1589
        put_tag(pb, "uuid");
1590
        put_tag(pb, "USMT");
1591
        put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1592
        put_be32(pb, 0xbb88695c);
1593
        put_be32(pb, 0xfac9c740);
1594

    
1595
        pos2 = url_ftell(pb);
1596
        put_be32(pb, 0); /* size placeholder*/
1597
        put_tag(pb, "MTDT");
1598
        put_be16(pb, 4);
1599

    
1600
        // ?
1601
        put_be16(pb, 0x0C);                 /* size */
1602
        put_be32(pb, 0x0B);                 /* type */
1603
        put_be16(pb, language_code("und")); /* language */
1604
        put_be16(pb, 0x0);                  /* ? */
1605
        put_be16(pb, 0x021C);               /* data */
1606

    
1607
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1608
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1609
//        snprintf(dt,32,"%04d/%02d/%02d %02d:%02d:%02d",t_st->tm_year+1900,t_st->tm_mon+1,t_st->tm_mday,t_st->tm_hour,t_st->tm_min,t_st->tm_sec);
1610
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1611

    
1612
        updateSize(pb, pos2);
1613
        return updateSize(pb, pos);
1614
    }
1615

    
1616
    return 0;
1617
}
1618

    
1619
static int mov_write_moov_tag(ByteIOContext *pb, MOVMuxContext *mov,
1620
                              AVFormatContext *s)
1621
{
1622
    int i;
1623
    int64_t pos = url_ftell(pb);
1624
    put_be32(pb, 0); /* size placeholder*/
1625
    put_tag(pb, "moov");
1626

    
1627
    for (i=0; i<mov->nb_streams; i++) {
1628
        if(mov->tracks[i].entry <= 0) continue;
1629

    
1630
        mov->tracks[i].time = mov->time;
1631
        mov->tracks[i].trackID = i+1;
1632
    }
1633

    
1634
    mov_write_mvhd_tag(pb, mov);
1635
    //mov_write_iods_tag(pb, mov);
1636
    for (i=0; i<mov->nb_streams; i++) {
1637
        if(mov->tracks[i].entry > 0) {
1638
            mov_write_trak_tag(pb, &(mov->tracks[i]), s->streams[i]);
1639
        }
1640
    }
1641

    
1642
    if (mov->mode == MODE_PSP)
1643
        mov_write_uuidusmt_tag(pb, s);
1644
    else
1645
        mov_write_udta_tag(pb, mov, s);
1646

    
1647
    return updateSize(pb, pos);
1648
}
1649

    
1650
static int mov_write_mdat_tag(ByteIOContext *pb, MOVMuxContext *mov)
1651
{
1652
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1653
    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1654

    
1655
    mov->mdat_pos = url_ftell(pb);
1656
    put_be32(pb, 0); /* size placeholder*/
1657
    put_tag(pb, "mdat");
1658
    return 0;
1659
}
1660

    
1661
/* TODO: This needs to be more general */
1662
static int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
1663
{
1664
    MOVMuxContext *mov = s->priv_data;
1665
    int64_t pos = url_ftell(pb);
1666
    int has_h264 = 0, has_video = 0;
1667
    int minor = 0x200;
1668
    int i;
1669

    
1670
    for (i = 0; i < s->nb_streams; i++) {
1671
        AVStream *st = s->streams[i];
1672
        if (st->codec->codec_type == CODEC_TYPE_VIDEO)
1673
            has_video = 1;
1674
        if (st->codec->codec_id == CODEC_ID_H264)
1675
            has_h264 = 1;
1676
    }
1677

    
1678
    put_be32(pb, 0); /* size */
1679
    put_tag(pb, "ftyp");
1680

    
1681
    if (mov->mode == MODE_3GP) {
1682
        put_tag(pb, has_h264 ? "3gp6"  : "3gp4");
1683
        minor =     has_h264 ?   0x100 :   0x200;
1684
    } else if (mov->mode & MODE_3G2) {
1685
        put_tag(pb, has_h264 ? "3g2b"  : "3g2a");
1686
        minor =     has_h264 ? 0x20000 : 0x10000;
1687
    }else if (mov->mode == MODE_PSP)
1688
        put_tag(pb, "MSNV");
1689
    else if (mov->mode == MODE_MP4)
1690
        put_tag(pb, "isom");
1691
    else if (mov->mode == MODE_IPOD)
1692
        put_tag(pb, has_video ? "M4V ":"M4A ");
1693
    else
1694
        put_tag(pb, "qt  ");
1695

    
1696
    put_be32(pb, minor);
1697

    
1698
    if(mov->mode == MODE_MOV)
1699
        put_tag(pb, "qt  ");
1700
    else{
1701
        put_tag(pb, "isom");
1702
        put_tag(pb, "iso2");
1703
        if(has_h264)
1704
            put_tag(pb, "avc1");
1705
    }
1706

    
1707
    if (mov->mode == MODE_3GP)
1708
        put_tag(pb, has_h264 ? "3gp6":"3gp4");
1709
    else if (mov->mode & MODE_3G2)
1710
        put_tag(pb, has_h264 ? "3g2b":"3g2a");
1711
    else if (mov->mode == MODE_PSP)
1712
        put_tag(pb, "MSNV");
1713
    else if (mov->mode == MODE_MP4)
1714
        put_tag(pb, "mp41");
1715
    return updateSize(pb, pos);
1716
}
1717

    
1718
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1719
{
1720
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1721
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1722
    int AudioRate = AudioCodec->sample_rate;
1723
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1724
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1725
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1726

    
1727
    put_be32(pb, 0x94); /* size */
1728
    put_tag(pb, "uuid");
1729
    put_tag(pb, "PROF");
1730

    
1731
    put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1732
    put_be32(pb, 0xbb88695c);
1733
    put_be32(pb, 0xfac9c740);
1734

    
1735
    put_be32(pb, 0x0);  /* ? */
1736
    put_be32(pb, 0x3);  /* 3 sections ? */
1737

    
1738
    put_be32(pb, 0x14); /* size */
1739
    put_tag(pb, "FPRF");
1740
    put_be32(pb, 0x0);  /* ? */
1741
    put_be32(pb, 0x0);  /* ? */
1742
    put_be32(pb, 0x0);  /* ? */
1743

    
1744
    put_be32(pb, 0x2c);  /* size */
1745
    put_tag(pb, "APRF");   /* audio */
1746
    put_be32(pb, 0x0);
1747
    put_be32(pb, 0x2);   /* TrackID */
1748
    put_tag(pb, "mp4a");
1749
    put_be32(pb, 0x20f);
1750
    put_be32(pb, 0x0);
1751
    put_be32(pb, audio_kbitrate);
1752
    put_be32(pb, audio_kbitrate);
1753
    put_be32(pb, AudioRate);
1754
    put_be32(pb, AudioCodec->channels);
1755

    
1756
    put_be32(pb, 0x34);  /* size */
1757
    put_tag(pb, "VPRF");   /* video */
1758
    put_be32(pb, 0x0);
1759
    put_be32(pb, 0x1);    /* TrackID */
1760
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1761
        put_tag(pb, "avc1");
1762
        put_be16(pb, 0x014D);
1763
        put_be16(pb, 0x0015);
1764
    } else {
1765
        put_tag(pb, "mp4v");
1766
        put_be16(pb, 0x0000);
1767
        put_be16(pb, 0x0103);
1768
    }
1769
    put_be32(pb, 0x0);
1770
    put_be32(pb, video_kbitrate);
1771
    put_be32(pb, video_kbitrate);
1772
    put_be32(pb, FrameRate);
1773
    put_be32(pb, FrameRate);
1774
    put_be16(pb, VideoCodec->width);
1775
    put_be16(pb, VideoCodec->height);
1776
    put_be32(pb, 0x010001); /* ? */
1777
}
1778

    
1779
static int mov_write_header(AVFormatContext *s)
1780
{
1781
    ByteIOContext *pb = s->pb;
1782
    MOVMuxContext *mov = s->priv_data;
1783
    int i;
1784

    
1785
    if (url_is_streamed(s->pb)) {
1786
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
1787
        return -1;
1788
    }
1789

    
1790
    /* Default mode == MP4 */
1791
    mov->mode = MODE_MP4;
1792

    
1793
    if (s->oformat != NULL) {
1794
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1795
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
1796
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1797
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1798
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
1799

    
1800
        mov_write_ftyp_tag(pb,s);
1801
        if (mov->mode == MODE_PSP) {
1802
            if (s->nb_streams != 2) {
1803
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1804
                return -1;
1805
            }
1806
            mov_write_uuidprof_tag(pb,s);
1807
        }
1808
    }
1809

    
1810
    mov->tracks = av_mallocz(s->nb_streams*sizeof(*mov->tracks));
1811
    if (!mov->tracks)
1812
        return AVERROR(ENOMEM);
1813

    
1814
    for(i=0; i<s->nb_streams; i++){
1815
        AVStream *st= s->streams[i];
1816
        MOVTrack *track= &mov->tracks[i];
1817
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
1818

    
1819
        track->enc = st->codec;
1820
        track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
1821
        if (track->language < 0)
1822
            track->language = 0;
1823
        track->mode = mov->mode;
1824
        track->tag = mov_find_codec_tag(s, track);
1825
        if (!track->tag) {
1826
            av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
1827
                   "codec not currently supported in container\n", i);
1828
            goto error;
1829
        }
1830
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1831
            if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
1832
                track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
1833
                track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
1834
                if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
1835
                    av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
1836
                    goto error;
1837
                }
1838
                track->height = track->tag>>24 == 'n' ? 486 : 576;
1839
            }
1840
            track->timescale = st->codec->time_base.den;
1841
            if (track->mode == MODE_MOV && track->timescale > 100000)
1842
                av_log(s, AV_LOG_WARNING,
1843
                       "WARNING codec timebase is very high. If duration is too long,\n"
1844
                       "file may not be playable by quicktime. Specify a shorter timebase\n"
1845
                       "or choose different container.\n");
1846
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO){
1847
            track->timescale = st->codec->sample_rate;
1848
            if(!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
1849
                av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
1850
                goto error;
1851
            }else if(st->codec->frame_size > 1){ /* assume compressed audio */
1852
                track->audio_vbr = 1;
1853
            }else{
1854
                st->codec->frame_size = 1;
1855
                track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
1856
            }
1857
            if (track->mode != MODE_MOV) {
1858
                if (track->timescale > UINT16_MAX) {
1859
                    av_log(s, AV_LOG_ERROR, "track %d: output format does not support "
1860
                           "sample rate %dhz\n", i, track->timescale);
1861
                    goto error;
1862
                }
1863
                if (track->enc->codec_id == CODEC_ID_MP3 && track->timescale < 16000) {
1864
                    av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
1865
                           i, track->enc->sample_rate);
1866
                    goto error;
1867
                }
1868
            }
1869
        }else if(st->codec->codec_type == CODEC_TYPE_SUBTITLE){
1870
            track->timescale = st->codec->time_base.den;
1871
        }
1872
        if (!track->height)
1873
            track->height = st->codec->height;
1874

    
1875
        av_set_pts_info(st, 64, 1, track->timescale);
1876
    }
1877

    
1878
    mov_write_mdat_tag(pb, mov);
1879
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1880
    mov->nb_streams = s->nb_streams;
1881

    
1882
    put_flush_packet(pb);
1883

    
1884
    return 0;
1885
 error:
1886
    av_freep(&mov->tracks);
1887
    return -1;
1888
}
1889

    
1890
static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
1891
{
1892
    uint32_t c = -1;
1893
    int i, closed_gop = 0;
1894

    
1895
    for (i = 0; i < pkt->size - 4; i++) {
1896
        c = (c<<8) + pkt->data[i];
1897
        if (c == 0x1b8) { // gop
1898
            closed_gop = pkt->data[i+4]>>6 & 0x01;
1899
        } else if (c == 0x100) { // pic
1900
            int temp_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
1901
            if (!temp_ref || closed_gop) // I picture is not reordered
1902
                *flags = MOV_SYNC_SAMPLE;
1903
            else
1904
                *flags = MOV_PARTIAL_SYNC_SAMPLE;
1905
            break;
1906
        }
1907
    }
1908
    return 0;
1909
}
1910

    
1911
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1912
{
1913
    MOVMuxContext *mov = s->priv_data;
1914
    ByteIOContext *pb = s->pb;
1915
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1916
    AVCodecContext *enc = trk->enc;
1917
    unsigned int samplesInChunk = 0;
1918
    int size= pkt->size;
1919

    
1920
    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1921
    if (!size) return 0; /* Discard 0 sized packets */
1922

    
1923
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1924
        /* We must find out how many AMR blocks there are in one packet */
1925
        static uint16_t packed_size[16] =
1926
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1927
        int len = 0;
1928

    
1929
        while (len < size && samplesInChunk < 100) {
1930
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1931
            samplesInChunk++;
1932
        }
1933
        if(samplesInChunk > 1){
1934
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
1935
            return -1;
1936
        }
1937
    } else if (trk->sampleSize)
1938
        samplesInChunk = size/trk->sampleSize;
1939
    else
1940
        samplesInChunk = 1;
1941

    
1942
    /* copy extradata if it exists */
1943
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1944
        trk->vosLen = enc->extradata_size;
1945
        trk->vosData = av_malloc(trk->vosLen);
1946
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1947
    }
1948

    
1949
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1950
        /* from x264 or from bytestream h264 */
1951
        /* nal reformating needed */
1952
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1953
    } else {
1954
        put_buffer(pb, pkt->data, size);
1955
    }
1956

    
1957
    if ((enc->codec_id == CODEC_ID_DNXHD ||
1958
         enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
1959
        /* copy frame to create needed atoms */
1960
        trk->vosLen = size;
1961
        trk->vosData = av_malloc(size);
1962
        if (!trk->vosData)
1963
            return AVERROR(ENOMEM);
1964
        memcpy(trk->vosData, pkt->data, size);
1965
    }
1966

    
1967
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1968
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1969
        if (!trk->cluster)
1970
            return -1;
1971
    }
1972

    
1973
    trk->cluster[trk->entry].pos = url_ftell(pb) - size;
1974
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1975
    trk->cluster[trk->entry].size = size;
1976
    trk->cluster[trk->entry].entries = samplesInChunk;
1977
    trk->cluster[trk->entry].dts = pkt->dts;
1978
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1979

    
1980
    if (pkt->pts == AV_NOPTS_VALUE) {
1981
        av_log(s, AV_LOG_WARNING, "pts has no value\n");
1982
        pkt->pts = pkt->dts;
1983
    }
1984
    if (pkt->dts != pkt->pts)
1985
        trk->flags |= MOV_TRACK_CTTS;
1986
    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1987
    trk->cluster[trk->entry].flags = 0;
1988
    if (pkt->flags & PKT_FLAG_KEY) {
1989
        if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO) {
1990
            mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
1991
            if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
1992
                trk->flags |= MOV_TRACK_STPS;
1993
        } else {
1994
            trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
1995
        }
1996
        if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
1997
            trk->hasKeyframes++;
1998
    }
1999
    trk->entry++;
2000
    trk->sampleCount += samplesInChunk;
2001
    mov->mdat_size += size;
2002

    
2003
    put_flush_packet(pb);
2004
    return 0;
2005
}
2006

    
2007
static int mov_write_trailer(AVFormatContext *s)
2008
{
2009
    MOVMuxContext *mov = s->priv_data;
2010
    ByteIOContext *pb = s->pb;
2011
    int res = 0;
2012
    int i;
2013

    
2014
    int64_t moov_pos = url_ftell(pb);
2015

    
2016
    /* Write size of mdat tag */
2017
    if (mov->mdat_size+8 <= UINT32_MAX) {
2018
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
2019
        put_be32(pb, mov->mdat_size+8);
2020
    } else {
2021
        /* overwrite 'wide' placeholder atom */
2022
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
2023
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
2024
        put_tag(pb, "mdat");
2025
        put_be64(pb, mov->mdat_size+16);
2026
    }
2027
    url_fseek(pb, moov_pos, SEEK_SET);
2028

    
2029
    mov_write_moov_tag(pb, mov, s);
2030

    
2031
    for (i=0; i<mov->nb_streams; i++) {
2032
        av_freep(&mov->tracks[i].cluster);
2033

    
2034
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2035

    
2036
    }
2037

    
2038
    put_flush_packet(pb);
2039

    
2040
    av_freep(&mov->tracks);
2041

    
2042
    return res;
2043
}
2044

    
2045
#if CONFIG_MOV_MUXER
2046
AVOutputFormat mov_muxer = {
2047
    "mov",
2048
    NULL_IF_CONFIG_SMALL("MOV format"),
2049
    NULL,
2050
    "mov",
2051
    sizeof(MOVMuxContext),
2052
    CODEC_ID_AAC,
2053
    CODEC_ID_MPEG4,
2054
    mov_write_header,
2055
    mov_write_packet,
2056
    mov_write_trailer,
2057
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
2058
    .codec_tag = (const AVCodecTag* const []){codec_movvideo_tags, codec_movaudio_tags, 0},
2059
};
2060
#endif
2061
#if CONFIG_TGP_MUXER
2062
AVOutputFormat tgp_muxer = {
2063
    "3gp",
2064
    NULL_IF_CONFIG_SMALL("3GP format"),
2065
    NULL,
2066
    "3gp",
2067
    sizeof(MOVMuxContext),
2068
    CODEC_ID_AMR_NB,
2069
    CODEC_ID_H263,
2070
    mov_write_header,
2071
    mov_write_packet,
2072
    mov_write_trailer,
2073
    .flags = AVFMT_GLOBALHEADER,
2074
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2075
};
2076
#endif
2077
#if CONFIG_MP4_MUXER
2078
AVOutputFormat mp4_muxer = {
2079
    "mp4",
2080
    NULL_IF_CONFIG_SMALL("MP4 format"),
2081
    "application/mp4",
2082
    "mp4",
2083
    sizeof(MOVMuxContext),
2084
    CODEC_ID_AAC,
2085
    CODEC_ID_MPEG4,
2086
    mov_write_header,
2087
    mov_write_packet,
2088
    mov_write_trailer,
2089
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
2090
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2091
};
2092
#endif
2093
#if CONFIG_PSP_MUXER
2094
AVOutputFormat psp_muxer = {
2095
    "psp",
2096
    NULL_IF_CONFIG_SMALL("PSP MP4 format"),
2097
    NULL,
2098
    "mp4,psp",
2099
    sizeof(MOVMuxContext),
2100
    CODEC_ID_AAC,
2101
    CODEC_ID_MPEG4,
2102
    mov_write_header,
2103
    mov_write_packet,
2104
    mov_write_trailer,
2105
    .flags = AVFMT_GLOBALHEADER,
2106
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2107
};
2108
#endif
2109
#if CONFIG_TG2_MUXER
2110
AVOutputFormat tg2_muxer = {
2111
    "3g2",
2112
    NULL_IF_CONFIG_SMALL("3GP2 format"),
2113
    NULL,
2114
    "3g2",
2115
    sizeof(MOVMuxContext),
2116
    CODEC_ID_AMR_NB,
2117
    CODEC_ID_H263,
2118
    mov_write_header,
2119
    mov_write_packet,
2120
    mov_write_trailer,
2121
    .flags = AVFMT_GLOBALHEADER,
2122
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2123
};
2124
#endif
2125
#if CONFIG_IPOD_MUXER
2126
AVOutputFormat ipod_muxer = {
2127
    "ipod",
2128
    NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
2129
    "application/mp4",
2130
    "m4v,m4a",
2131
    sizeof(MOVMuxContext),
2132
    CODEC_ID_AAC,
2133
    CODEC_ID_H264,
2134
    mov_write_header,
2135
    mov_write_packet,
2136
    mov_write_trailer,
2137
    .flags = AVFMT_GLOBALHEADER,
2138
    .codec_tag = (const AVCodecTag* const []){codec_ipod_tags, 0},
2139
};
2140
#endif