Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 72415b2a

History | View | Annotate | Download (69 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 == AVMEDIA_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 == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
624
    else if (track->enc->codec_type == AVMEDIA_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 == AVMEDIA_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 == AVMEDIA_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 == AVMEDIA_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 == AVMEDIA_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 == AVMEDIA_TYPE_VIDEO)
872
        mov_write_video_tag(pb, track);
873
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
874
        mov_write_audio_tag(pb, track);
875
    else if (track->enc->codec_type == AVMEDIA_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 == AVMEDIA_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 == AVMEDIA_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 == AVMEDIA_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 == AVMEDIA_TYPE_VIDEO) {
1054
            hdlr_type = "vide";
1055
            descr = "VideoHandler";
1056
        } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1057
            hdlr_type = "soun";
1058
            descr = "SoundHandler";
1059
        } else if (track->enc->codec_type == AVMEDIA_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 == AVMEDIA_TYPE_VIDEO)
1088
        mov_write_vmhd_tag(pb);
1089
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1090
        mov_write_smhd_tag(pb);
1091
    else if (track->enc->codec_type == AVMEDIA_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 == AVMEDIA_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 == AVMEDIA_TYPE_VIDEO ||
1187
       track->enc->codec_type == AVMEDIA_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
        if (!lang)
1359
            lang = ff_mov_iso639_to_lang("und", 1);
1360
        put_be16(pb, strlen(data)); /* string length */
1361
        put_be16(pb, lang);
1362
        put_buffer(pb, data, strlen(data));
1363
        return strlen(data) + 4;
1364
    }
1365
}
1366

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1534
    ret = url_open_dyn_buf(&pb_buf);
1535
    if(ret < 0)
1536
        return ret;
1537

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

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

    
1567
    return 0;
1568
}
1569

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

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

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

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

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

    
1609
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1610
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1611
//        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);
1612
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1613

    
1614
        updateSize(pb, pos2);
1615
        return updateSize(pb, pos);
1616
    }
1617

    
1618
    return 0;
1619
}
1620

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

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

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

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

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

    
1649
    return updateSize(pb, pos);
1650
}
1651

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

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

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

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

    
1680
    put_be32(pb, 0); /* size */
1681
    put_tag(pb, "ftyp");
1682

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

    
1698
    put_be32(pb, minor);
1699

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

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

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

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

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

    
1737
    put_be32(pb, 0x0);  /* ? */
1738
    put_be32(pb, 0x3);  /* 3 sections ? */
1739

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

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

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

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

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

    
1792
    /* Default mode == MP4 */
1793
    mov->mode = MODE_MP4;
1794

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

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

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

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

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

    
1877
        av_set_pts_info(st, 64, 1, track->timescale);
1878
    }
1879

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

    
1884
    put_flush_packet(pb);
1885

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2005
    put_flush_packet(pb);
2006
    return 0;
2007
}
2008

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

    
2016
    int64_t moov_pos = url_ftell(pb);
2017

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

    
2031
    mov_write_moov_tag(pb, mov, s);
2032

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

    
2036
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2037

    
2038
    }
2039

    
2040
    put_flush_packet(pb);
2041

    
2042
    av_freep(&mov->tracks);
2043

    
2044
    return res;
2045
}
2046

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