Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ b2755007

History | View | Annotate | Download (64.7 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/bitstream.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 globalTimescale 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 flags, size;
48
    uint64_t     pos;
49
    unsigned int samplesInChunk;
50
    char         key_frame;
51
    unsigned int entries;
52
    int64_t      cts;
53
    int64_t      dts;
54
} MOVIentry;
55

    
56
typedef struct MOVIndex {
57
    int         mode;
58
    int         entry;
59
    long        timescale;
60
    long        time;
61
    int64_t     trackDuration;
62
    long        sampleCount;
63
    long        sampleSize;
64
    int         hasKeyframes;
65
    int         hasBframes;
66
    int         language;
67
    int         trackID;
68
    int         tag; ///< stsd fourcc
69
    AVCodecContext *enc;
70

    
71
    int         vosLen;
72
    uint8_t     *vosData;
73
    MOVIentry   *cluster;
74
    int         audio_vbr;
75
    int         height; ///< active picture (w/o VBI) height for D-10/IMX
76
} MOVTrack;
77

    
78
typedef struct MOVMuxContext {
79
    int     mode;
80
    int64_t time;
81
    int     nb_streams;
82
    int64_t mdat_pos;
83
    uint64_t mdat_size;
84
    long    timescale;
85
    MOVTrack *tracks;
86
} MOVMuxContext;
87

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

    
96
    return curpos - pos;
97
}
98

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

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

    
128
    int64_t pos = url_ftell(pb);
129
    put_be32(pb, 0); /* size */
130
    put_tag(pb, "stsz");
131
    put_be32(pb, 0); /* version & flags */
132

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

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

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

    
186
    return updateSize(pb, pos);
187
}
188

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

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

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

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

    
234
    if (track->vosLen < 7)
235
        return -1;
236

    
237
    put_be32(pb, 11);
238
    put_tag(pb, "dac3");
239

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

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

    
265
    flush_put_bits(&pbc);
266
    put_buffer(pb, buf, sizeof(buf));
267

    
268
    return 11;
269
}
270

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

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

    
289
static unsigned int descrLength(unsigned int len)
290
{
291
    int i;
292
    for(i=1; len>>(7*i); i++);
293
    return len + 1 + i;
294
}
295

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

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

    
310
    put_be32(pb, 0); // size
311
    put_tag(pb, "esds");
312
    put_be32(pb, 0); // Version
313

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

    
320
    // DecoderConfig descriptor
321
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
322

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

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

    
338
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));    // Buffersize DB (24 bits)
339
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
340

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

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

    
353
    // SL descriptor
354
    putDescr(pb, 0x06, 1);
355
    put_byte(pb, 0x02);
356
    return updateSize(pb, pos);
357
}
358

    
359
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack *track)
360
{
361
    int64_t pos = url_ftell(pb);
362

    
363
    put_be32(pb, 0);     /* size */
364
    put_tag(pb, "wave");
365

    
366
    put_be32(pb, 12);    /* size */
367
    put_tag(pb, "frma");
368
    put_le32(pb, track->tag);
369

    
370
    if (track->enc->codec_id == CODEC_ID_AAC) {
371
        /* useless atom needed by mplayer, ipod, not needed by quicktime */
372
        put_be32(pb, 12); /* size */
373
        put_tag(pb, "mp4a");
374
        put_be32(pb, 0);
375
        mov_write_esds_tag(pb, track);
376
    } else if (track->enc->codec_id == CODEC_ID_PCM_S24LE ||
377
               track->enc->codec_id == CODEC_ID_PCM_S32LE) {
378
        mov_write_enda_tag(pb);
379
    } else if (track->enc->codec_id == CODEC_ID_AMR_NB) {
380
        mov_write_amr_tag(pb, track);
381
    } else if (track->enc->codec_id == CODEC_ID_AC3) {
382
        mov_write_ac3_tag(pb, track);
383
    } else if (track->enc->codec_id == CODEC_ID_ALAC) {
384
        mov_write_extradata_tag(pb, track);
385
    }
386

    
387
    put_be32(pb, 8);     /* size */
388
    put_be32(pb, 0);     /* null tag */
389

    
390
    return updateSize(pb, pos);
391
}
392

    
393
static int mov_write_glbl_tag(ByteIOContext *pb, MOVTrack *track)
394
{
395
    put_be32(pb, track->vosLen+8);
396
    put_tag(pb, "glbl");
397
    put_buffer(pb, track->vosData, track->vosLen);
398
    return 8+track->vosLen;
399
}
400

    
401
static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack *track)
402
{
403
    int64_t pos = url_ftell(pb);
404
    int version = track->mode == MODE_MOV &&
405
        (track->audio_vbr ||
406
         track->enc->codec_id == CODEC_ID_PCM_S32LE ||
407
         track->enc->codec_id == CODEC_ID_PCM_S24LE);
408

    
409
    put_be32(pb, 0); /* size */
410
    put_le32(pb, track->tag); // store it byteswapped
411
    put_be32(pb, 0); /* Reserved */
412
    put_be16(pb, 0); /* Reserved */
413
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
414

    
415
    /* SoundDescription */
416
    put_be16(pb, version); /* Version */
417
    put_be16(pb, 0); /* Revision level */
418
    put_be32(pb, 0); /* Reserved */
419

    
420
    if (track->mode == MODE_MOV) {
421
        put_be16(pb, track->enc->channels);
422
        if (track->enc->codec_id == CODEC_ID_PCM_U8 ||
423
            track->enc->codec_id == CODEC_ID_PCM_S8)
424
            put_be16(pb, 8); /* bits per sample */
425
        else
426
            put_be16(pb, 16);
427
        put_be16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
428
    } else { /* reserved for mp4/3gp */
429
        put_be16(pb, 2);
430
        put_be16(pb, 16);
431
        put_be16(pb, 0);
432
    }
433

    
434
    put_be16(pb, 0); /* packet size (= 0) */
435
    put_be16(pb, track->timescale); /* Time scale */
436
    put_be16(pb, 0); /* Reserved */
437

    
438
    if(version == 1) { /* SoundDescription V1 extended info */
439
        put_be32(pb, track->enc->frame_size); /* Samples per packet */
440
        put_be32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
441
        put_be32(pb, track->sampleSize); /* Bytes per frame */
442
        put_be32(pb, 2); /* Bytes per sample */
443
    }
444

    
445
    if(track->mode == MODE_MOV &&
446
       (track->enc->codec_id == CODEC_ID_AAC ||
447
        track->enc->codec_id == CODEC_ID_AC3 ||
448
        track->enc->codec_id == CODEC_ID_AMR_NB ||
449
        track->enc->codec_id == CODEC_ID_PCM_S24LE ||
450
        track->enc->codec_id == CODEC_ID_PCM_S32LE ||
451
        track->enc->codec_id == CODEC_ID_ALAC))
452
        mov_write_wave_tag(pb, track);
453
    else if(track->tag == MKTAG('m','p','4','a'))
454
        mov_write_esds_tag(pb, track);
455
    else if(track->enc->codec_id == CODEC_ID_AMR_NB)
456
        mov_write_amr_tag(pb, track);
457
    else if(track->enc->codec_id == CODEC_ID_AC3)
458
        mov_write_ac3_tag(pb, track);
459
    else if(track->enc->codec_id == CODEC_ID_ALAC)
460
        mov_write_extradata_tag(pb, track);
461
    else if(track->vosLen > 0)
462
        mov_write_glbl_tag(pb, track);
463

    
464
    return updateSize(pb, pos);
465
}
466

    
467
static int mov_write_d263_tag(ByteIOContext *pb)
468
{
469
    put_be32(pb, 0xf); /* size */
470
    put_tag(pb, "d263");
471
    put_tag(pb, "FFMP");
472
    put_byte(pb, 0); /* decoder version */
473
    /* FIXME use AVCodecContext level/profile, when encoder will set values */
474
    put_byte(pb, 0xa); /* level */
475
    put_byte(pb, 0); /* profile */
476
    return 0xf;
477
}
478

    
479
/* TODO: No idea about these values */
480
static int mov_write_svq3_tag(ByteIOContext *pb)
481
{
482
    put_be32(pb, 0x15);
483
    put_tag(pb, "SMI ");
484
    put_tag(pb, "SEQH");
485
    put_be32(pb, 0x5);
486
    put_be32(pb, 0xe2c0211d);
487
    put_be32(pb, 0xc0000000);
488
    put_byte(pb, 0);
489
    return 0x15;
490
}
491

    
492
static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
493
{
494
    int64_t pos = url_ftell(pb);
495

    
496
    put_be32(pb, 0);
497
    put_tag(pb, "avcC");
498
    ff_isom_write_avcc(pb, track->vosData, track->vosLen);
499
    return updateSize(pb, pos);
500
}
501

    
502
/* also used by all avid codecs (dv, imx, meridien) and their variants */
503
static int mov_write_avid_tag(ByteIOContext *pb, MOVTrack *track)
504
{
505
    int i;
506
    put_be32(pb, 24); /* size */
507
    put_tag(pb, "ACLR");
508
    put_tag(pb, "ACLR");
509
    put_tag(pb, "0001");
510
    put_be32(pb, 1); /* yuv 1 / rgb 2 ? */
511
    put_be32(pb, 0); /* unknown */
512

    
513
    put_be32(pb, 24); /* size */
514
    put_tag(pb, "APRG");
515
    put_tag(pb, "APRG");
516
    put_tag(pb, "0001");
517
    put_be32(pb, 1); /* unknown */
518
    put_be32(pb, 0); /* unknown */
519

    
520
    put_be32(pb, 120); /* size */
521
    put_tag(pb, "ARES");
522
    put_tag(pb, "ARES");
523
    put_tag(pb, "0001");
524
    put_be32(pb, AV_RB32(track->vosData + 0x28)); /* dnxhd cid, some id ? */
525
    put_be32(pb, track->enc->width);
526
    /* values below are based on samples created with quicktime and avid codecs */
527
    if (track->vosData[5] & 2) { // interlaced
528
        put_be32(pb, track->enc->height/2);
529
        put_be32(pb, 2); /* unknown */
530
        put_be32(pb, 0); /* unknown */
531
        put_be32(pb, 4); /* unknown */
532
    } else {
533
        put_be32(pb, track->enc->height);
534
        put_be32(pb, 1); /* unknown */
535
        put_be32(pb, 0); /* unknown */
536
        if (track->enc->height == 1080)
537
            put_be32(pb, 5); /* unknown */
538
        else
539
            put_be32(pb, 6); /* unknown */
540
    }
541
    /* padding */
542
    for (i = 0; i < 10; i++)
543
        put_be64(pb, 0);
544

    
545
    /* extra padding for stsd needed */
546
    put_be32(pb, 0);
547
    return 0;
548
}
549

    
550
static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
551
{
552
    int tag = track->enc->codec_tag;
553

    
554
    if (!codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
555
        return 0;
556

    
557
    if      (track->enc->codec_id == CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
558
    else if (track->enc->codec_id == CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
559
    else if (track->enc->codec_id == CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
560
    else if (track->enc->codec_id == CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
561
    else if (track->enc->codec_type == CODEC_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
562
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
563

    
564
    return tag;
565
}
566

    
567
static const AVCodecTag codec_ipod_tags[] = {
568
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
569
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
570
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
571
    { CODEC_ID_ALAC,   MKTAG('a','l','a','c') },
572
    { CODEC_ID_AC3,    MKTAG('a','c','-','3') },
573
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
574
    { CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
575
    { CODEC_ID_NONE, 0 },
576
};
577

    
578
static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
579
{
580
    int tag = track->enc->codec_tag;
581

    
582
    // keep original tag for subs, ipod supports both formats
583
    if (!(track->enc->codec_type == CODEC_TYPE_SUBTITLE &&
584
        (tag == MKTAG('t','x','3','g') ||
585
         tag == MKTAG('t','e','x','t'))))
586
        tag = codec_get_tag(codec_ipod_tags, track->enc->codec_id);
587

    
588
    if (!match_ext(s->filename, "m4a") && !match_ext(s->filename, "m4v"))
589
        av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
590
               "Quicktime/Ipod might not play the file\n");
591

    
592
    return tag;
593
}
594

    
595
static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
596
{
597
    int tag;
598

    
599
    if (track->enc->height == 480) /* NTSC */
600
        if  (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
601
        else                                         tag = MKTAG('d','v','c',' ');
602
    else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
603
    else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
604
    else                                             tag = MKTAG('d','v','p','p');
605

    
606
    return tag;
607
}
608

    
609
static const struct {
610
    enum PixelFormat pix_fmt;
611
    uint32_t tag;
612
    unsigned bps;
613
} mov_pix_fmt_tags[] = {
614
    { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
615
    { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
616
    { PIX_FMT_BGR555,  MKTAG('r','a','w',' '), 16 },
617
    { PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
618
    { PIX_FMT_BGR32_1, MKTAG('r','a','w',' '), 32 },
619
};
620

    
621
static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
622
{
623
    int tag = track->enc->codec_tag;
624
    int i;
625

    
626
    for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
627
        if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
628
            tag = mov_pix_fmt_tags[i].tag;
629
            track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
630
            break;
631
        }
632
    }
633

    
634
    return tag;
635
}
636

    
637
static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
638
{
639
    int tag = track->enc->codec_tag;
640

    
641
    if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
642
                 (tag == MKTAG('d','v','c','p') ||
643
                  track->enc->codec_id == CODEC_ID_RAWVIDEO ||
644
                  av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
645
        if (track->enc->codec_id == CODEC_ID_DVVIDEO)
646
            tag = mov_get_dv_codec_tag(s, track);
647
        else if (track->enc->codec_id == CODEC_ID_RAWVIDEO)
648
            tag = mov_get_rawvideo_codec_tag(s, track);
649
        else if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
650
            tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
651
            if (!tag) { // if no mac fcc found, try with Microsoft tags
652
                tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
653
                if (tag)
654
                    av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, "
655
                           "the file may be unplayable!\n");
656
            }
657
        } else if (track->enc->codec_type == CODEC_TYPE_AUDIO) {
658
            tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
659
            if (!tag) { // if no mac fcc found, try with Microsoft tags
660
                int ms_tag = codec_get_tag(codec_wav_tags, track->enc->codec_id);
661
                if (ms_tag) {
662
                    tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
663
                    av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, "
664
                           "the file may be unplayable!\n");
665
                }
666
            }
667
        } else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE)
668
            tag = codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
669
    }
670

    
671
    return tag;
672
}
673

    
674
static const AVCodecTag codec_3gp_tags[] = {
675
    { CODEC_ID_H263,   MKTAG('s','2','6','3') },
676
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
677
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
678
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
679
    { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
680
    { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
681
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
682
    { CODEC_ID_NONE, 0 },
683
};
684

    
685
static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
686
{
687
    int tag = track->enc->codec_tag;
688

    
689
    if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
690
        tag = mp4_get_codec_tag(s, track);
691
    else if (track->mode == MODE_IPOD)
692
        tag = ipod_get_codec_tag(s, track);
693
    else if (track->mode & MODE_3GP)
694
        tag = codec_get_tag(codec_3gp_tags, track->enc->codec_id);
695
    else
696
        tag = mov_get_codec_tag(s, track);
697

    
698
    return tag;
699
}
700

    
701
/** Write uuid atom.
702
 * Needed to make file play in iPods running newest firmware
703
 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
704
 */
705
static int mov_write_uuid_tag_ipod(ByteIOContext *pb)
706
{
707
    put_be32(pb, 28);
708
    put_tag(pb, "uuid");
709
    put_be32(pb, 0x6b6840f2);
710
    put_be32(pb, 0x5f244fc5);
711
    put_be32(pb, 0xba39a51b);
712
    put_be32(pb, 0xcf0323f3);
713
    put_be32(pb, 0x0);
714
    return 28;
715
}
716

    
717
static int mov_write_subtitle_tag(ByteIOContext *pb, MOVTrack *track)
718
{
719
    int64_t pos = url_ftell(pb);
720
    put_be32(pb, 0);    /* size */
721
    put_le32(pb, track->tag); // store it byteswapped
722
    put_be32(pb, 0);    /* Reserved */
723
    put_be16(pb, 0);    /* Reserved */
724
    put_be16(pb, 1);    /* Data-reference index */
725

    
726
    if (track->enc->extradata_size)
727
        put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
728

    
729
    return updateSize(pb, pos);
730
}
731

    
732
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack *track)
733
{
734
    int64_t pos = url_ftell(pb);
735
    char compressor_name[32];
736

    
737
    put_be32(pb, 0); /* size */
738
    put_le32(pb, track->tag); // store it byteswapped
739
    put_be32(pb, 0); /* Reserved */
740
    put_be16(pb, 0); /* Reserved */
741
    put_be16(pb, 1); /* Data-reference index */
742

    
743
    put_be16(pb, 0); /* Codec stream version */
744
    put_be16(pb, 0); /* Codec stream revision (=0) */
745
    if (track->mode == MODE_MOV) {
746
        put_tag(pb, "FFMP"); /* Vendor */
747
        if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
748
            put_be32(pb, 0); /* Temporal Quality */
749
            put_be32(pb, 0x400); /* Spatial Quality = lossless*/
750
        } else {
751
            put_be32(pb, 0x200); /* Temporal Quality = normal */
752
            put_be32(pb, 0x200); /* Spatial Quality = normal */
753
        }
754
    } else {
755
        put_be32(pb, 0); /* Reserved */
756
        put_be32(pb, 0); /* Reserved */
757
        put_be32(pb, 0); /* Reserved */
758
    }
759
    put_be16(pb, track->enc->width); /* Video width */
760
    put_be16(pb, track->height); /* Video height */
761
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
762
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
763
    put_be32(pb, 0); /* Data size (= 0) */
764
    put_be16(pb, 1); /* Frame count (= 1) */
765

    
766
    memset(compressor_name,0,32);
767
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
768
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
769
        strncpy(compressor_name,track->enc->codec->name,31);
770
    put_byte(pb, strlen(compressor_name));
771
    put_buffer(pb, compressor_name, 31);
772

    
773
    if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
774
        put_be16(pb, track->enc->bits_per_coded_sample);
775
    else
776
        put_be16(pb, 0x18); /* Reserved */
777
    put_be16(pb, 0xffff); /* Reserved */
778
    if(track->tag == MKTAG('m','p','4','v'))
779
        mov_write_esds_tag(pb, track);
780
    else if(track->enc->codec_id == CODEC_ID_H263)
781
        mov_write_d263_tag(pb);
782
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
783
        mov_write_svq3_tag(pb);
784
    else if(track->enc->codec_id == CODEC_ID_DNXHD)
785
        mov_write_avid_tag(pb, track);
786
    else if(track->enc->codec_id == CODEC_ID_H264) {
787
        mov_write_avcc_tag(pb, track);
788
        if(track->mode == MODE_IPOD)
789
            mov_write_uuid_tag_ipod(pb);
790
    } else if(track->vosLen > 0)
791
        mov_write_glbl_tag(pb, track);
792

    
793
    return updateSize(pb, pos);
794
}
795

    
796
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack *track)
797
{
798
    int64_t pos = url_ftell(pb);
799
    put_be32(pb, 0); /* size */
800
    put_tag(pb, "stsd");
801
    put_be32(pb, 0); /* version & flags */
802
    put_be32(pb, 1); /* entry count */
803
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
804
        mov_write_video_tag(pb, track);
805
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
806
        mov_write_audio_tag(pb, track);
807
    else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE)
808
        mov_write_subtitle_tag(pb, track);
809
    return updateSize(pb, pos);
810
}
811

    
812
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack *track)
813
{
814
    MOVStts *ctts_entries;
815
    uint32_t entries = 0;
816
    uint32_t atom_size;
817
    int i;
818

    
819
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
820
    ctts_entries[0].count = 1;
821
    ctts_entries[0].duration = track->cluster[0].cts;
822
    for (i=1; i<track->entry; i++) {
823
        if (track->cluster[i].cts == ctts_entries[entries].duration) {
824
            ctts_entries[entries].count++; /* compress */
825
        } else {
826
            entries++;
827
            ctts_entries[entries].duration = track->cluster[i].cts;
828
            ctts_entries[entries].count = 1;
829
        }
830
    }
831
    entries++; /* last one */
832
    atom_size = 16 + (entries * 8);
833
    put_be32(pb, atom_size); /* size */
834
    put_tag(pb, "ctts");
835
    put_be32(pb, 0); /* version & flags */
836
    put_be32(pb, entries); /* entry count */
837
    for (i=0; i<entries; i++) {
838
        put_be32(pb, ctts_entries[i].count);
839
        put_be32(pb, ctts_entries[i].duration);
840
    }
841
    av_free(ctts_entries);
842
    return atom_size;
843
}
844

    
845
/* Time to sample atom */
846
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack *track)
847
{
848
    MOVStts *stts_entries;
849
    uint32_t entries = -1;
850
    uint32_t atom_size;
851
    int i;
852

    
853
    if (track->enc->codec_type == CODEC_TYPE_AUDIO && !track->audio_vbr) {
854
        stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
855
        stts_entries[0].count = track->sampleCount;
856
        stts_entries[0].duration = 1;
857
        entries = 1;
858
    } else {
859
        stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
860
        for (i=0; i<track->entry; i++) {
861
            int64_t duration = i + 1 == track->entry ?
862
                track->trackDuration - track->cluster[i].dts + track->cluster[0].dts : /* readjusting */
863
                track->cluster[i+1].dts - track->cluster[i].dts;
864
            if (i && duration == stts_entries[entries].duration) {
865
                stts_entries[entries].count++; /* compress */
866
            } else {
867
                entries++;
868
                stts_entries[entries].duration = duration;
869
                stts_entries[entries].count = 1;
870
            }
871
        }
872
        entries++; /* last one */
873
    }
874
    atom_size = 16 + (entries * 8);
875
    put_be32(pb, atom_size); /* size */
876
    put_tag(pb, "stts");
877
    put_be32(pb, 0); /* version & flags */
878
    put_be32(pb, entries); /* entry count */
879
    for (i=0; i<entries; i++) {
880
        put_be32(pb, stts_entries[i].count);
881
        put_be32(pb, stts_entries[i].duration);
882
    }
883
    av_free(stts_entries);
884
    return atom_size;
885
}
886

    
887
static int mov_write_dref_tag(ByteIOContext *pb)
888
{
889
    put_be32(pb, 28); /* size */
890
    put_tag(pb, "dref");
891
    put_be32(pb, 0); /* version & flags */
892
    put_be32(pb, 1); /* entry count */
893

    
894
    put_be32(pb, 0xc); /* size */
895
    put_tag(pb, "url ");
896
    put_be32(pb, 1); /* version & flags */
897

    
898
    return 28;
899
}
900

    
901
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack *track)
902
{
903
    int64_t pos = url_ftell(pb);
904
    put_be32(pb, 0); /* size */
905
    put_tag(pb, "stbl");
906
    mov_write_stsd_tag(pb, track);
907
    mov_write_stts_tag(pb, track);
908
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
909
        track->hasKeyframes && track->hasKeyframes < track->entry)
910
        mov_write_stss_tag(pb, track);
911
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
912
        track->hasBframes)
913
        mov_write_ctts_tag(pb, track);
914
    mov_write_stsc_tag(pb, track);
915
    mov_write_stsz_tag(pb, track);
916
    mov_write_stco_tag(pb, track);
917
    return updateSize(pb, pos);
918
}
919

    
920
static int mov_write_dinf_tag(ByteIOContext *pb)
921
{
922
    int64_t pos = url_ftell(pb);
923
    put_be32(pb, 0); /* size */
924
    put_tag(pb, "dinf");
925
    mov_write_dref_tag(pb);
926
    return updateSize(pb, pos);
927
}
928

    
929
static int mov_write_nmhd_tag(ByteIOContext *pb)
930
{
931
    put_be32(pb, 12);
932
    put_tag(pb, "nmhd");
933
    put_be32(pb, 0);
934
    return 12;
935
}
936

    
937
static int mov_write_gmhd_tag(ByteIOContext *pb)
938
{
939
    put_be32(pb, 0x20);   /* size */
940
    put_tag(pb, "gmhd");
941
    put_be32(pb, 0x18);   /* gmin size */
942
    put_tag(pb, "gmin");  /* generic media info */
943
    put_be32(pb, 0);      /* version & flags */
944
    put_be16(pb, 0x40);   /* graphics mode = */
945
    put_be16(pb, 0x8000); /* opColor (r?) */
946
    put_be16(pb, 0x8000); /* opColor (g?) */
947
    put_be16(pb, 0x8000); /* opColor (b?) */
948
    put_be16(pb, 0);      /* balance */
949
    put_be16(pb, 0);      /* reserved */
950
    return 0x20;
951
}
952

    
953
static int mov_write_smhd_tag(ByteIOContext *pb)
954
{
955
    put_be32(pb, 16); /* size */
956
    put_tag(pb, "smhd");
957
    put_be32(pb, 0); /* version & flags */
958
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
959
    put_be16(pb, 0); /* reserved */
960
    return 16;
961
}
962

    
963
static int mov_write_vmhd_tag(ByteIOContext *pb)
964
{
965
    put_be32(pb, 0x14); /* size (always 0x14) */
966
    put_tag(pb, "vmhd");
967
    put_be32(pb, 0x01); /* version & flags */
968
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
969
    return 0x14;
970
}
971

    
972
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)
973
{
974
    const char *hdlr, *descr = NULL, *hdlr_type = NULL;
975
    int64_t pos = url_ftell(pb);
976

    
977
    if (!track) { /* no media --> data handler */
978
        hdlr = "dhlr";
979
        hdlr_type = "url ";
980
        descr = "DataHandler";
981
    } else {
982
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
983
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
984
            hdlr_type = "vide";
985
            descr = "VideoHandler";
986
        } else if (track->enc->codec_type == CODEC_TYPE_AUDIO) {
987
            hdlr_type = "soun";
988
            descr = "SoundHandler";
989
        } else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
990
            if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
991
            else                                      hdlr_type = "text";
992
            descr = "SubtitleHandler";
993
        }
994
    }
995

    
996
    put_be32(pb, 0); /* size */
997
    put_tag(pb, "hdlr");
998
    put_be32(pb, 0); /* Version & flags */
999
    put_buffer(pb, hdlr, 4); /* handler */
1000
    put_tag(pb, hdlr_type); /* handler type */
1001
    put_be32(pb ,0); /* reserved */
1002
    put_be32(pb ,0); /* reserved */
1003
    put_be32(pb ,0); /* reserved */
1004
    put_byte(pb, strlen(descr)); /* string counter */
1005
    put_buffer(pb, descr, strlen(descr)); /* handler description */
1006
    return updateSize(pb, pos);
1007
}
1008

    
1009
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack *track)
1010
{
1011
    int64_t pos = url_ftell(pb);
1012
    put_be32(pb, 0); /* size */
1013
    put_tag(pb, "minf");
1014
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
1015
        mov_write_vmhd_tag(pb);
1016
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
1017
        mov_write_smhd_tag(pb);
1018
    else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
1019
        if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb);
1020
        else                                      mov_write_nmhd_tag(pb);
1021
    }
1022
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1023
        mov_write_hdlr_tag(pb, NULL);
1024
    mov_write_dinf_tag(pb);
1025
    mov_write_stbl_tag(pb, track);
1026
    return updateSize(pb, pos);
1027
}
1028

    
1029
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack *track)
1030
{
1031
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
1032

    
1033
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
1034
    put_tag(pb, "mdhd");
1035
    put_byte(pb, version);
1036
    put_be24(pb, 0); /* flags */
1037
    if (version == 1) {
1038
        put_be64(pb, track->time);
1039
        put_be64(pb, track->time);
1040
    } else {
1041
        put_be32(pb, track->time); /* creation time */
1042
        put_be32(pb, track->time); /* modification time */
1043
    }
1044
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
1045
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
1046
    put_be16(pb, track->language); /* language */
1047
    put_be16(pb, 0); /* reserved (quality) */
1048

    
1049
    if(version!=0 && track->mode == MODE_MOV){
1050
        av_log(NULL, AV_LOG_ERROR,
1051
            "FATAL error, file duration too long for timebase, this file will not be\n"
1052
            "playable with quicktime. Choose a different timebase or a different\n"
1053
            "container format\n");
1054
    }
1055

    
1056
    return 32;
1057
}
1058

    
1059
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack *track)
1060
{
1061
    int64_t pos = url_ftell(pb);
1062
    put_be32(pb, 0); /* size */
1063
    put_tag(pb, "mdia");
1064
    mov_write_mdhd_tag(pb, track);
1065
    mov_write_hdlr_tag(pb, track);
1066
    mov_write_minf_tag(pb, track);
1067
    return updateSize(pb, pos);
1068
}
1069

    
1070
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1071
{
1072
    int64_t duration = av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP);
1073
    int version = duration < INT32_MAX ? 0 : 1;
1074

    
1075
    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
1076
    put_tag(pb, "tkhd");
1077
    put_byte(pb, version);
1078
    put_be24(pb, 0xf); /* flags (track enabled) */
1079
    if (version == 1) {
1080
        put_be64(pb, track->time);
1081
        put_be64(pb, track->time);
1082
    } else {
1083
        put_be32(pb, track->time); /* creation time */
1084
        put_be32(pb, track->time); /* modification time */
1085
    }
1086
    put_be32(pb, track->trackID); /* track-id */
1087
    put_be32(pb, 0); /* reserved */
1088
    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
1089

    
1090
    put_be32(pb, 0); /* reserved */
1091
    put_be32(pb, 0); /* reserved */
1092
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
1093
    /* Volume, only for audio */
1094
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
1095
        put_be16(pb, 0x0100);
1096
    else
1097
        put_be16(pb, 0);
1098
    put_be16(pb, 0); /* reserved */
1099

    
1100
    /* Matrix structure */
1101
    put_be32(pb, 0x00010000); /* reserved */
1102
    put_be32(pb, 0x0); /* reserved */
1103
    put_be32(pb, 0x0); /* reserved */
1104
    put_be32(pb, 0x0); /* reserved */
1105
    put_be32(pb, 0x00010000); /* reserved */
1106
    put_be32(pb, 0x0); /* reserved */
1107
    put_be32(pb, 0x0); /* reserved */
1108
    put_be32(pb, 0x0); /* reserved */
1109
    put_be32(pb, 0x40000000); /* reserved */
1110

    
1111
    /* Track width and height, for visual only */
1112
    if(track->enc->codec_type == CODEC_TYPE_VIDEO ||
1113
       track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
1114
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1115
        if(!sample_aspect_ratio || track->height != track->enc->height)
1116
            sample_aspect_ratio = 1;
1117
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1118
        put_be32(pb, track->height*0x10000);
1119
    }
1120
    else {
1121
        put_be32(pb, 0);
1122
        put_be32(pb, 0);
1123
    }
1124
    return 0x5c;
1125
}
1126

    
1127
// This box seems important for the psp playback ... without it the movie seems to hang
1128
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
1129
{
1130
    put_be32(pb, 0x24); /* size  */
1131
    put_tag(pb, "edts");
1132
    put_be32(pb, 0x1c); /* size  */
1133
    put_tag(pb, "elst");
1134
    put_be32(pb, 0x0);
1135
    put_be32(pb, 0x1);
1136

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

    
1139
    put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
1140
    put_be32(pb, 0x00010000);
1141
    return 0x24;
1142
}
1143

    
1144
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1145
static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
1146
{
1147
    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1148
    put_tag(pb, "uuid");
1149
    put_tag(pb, "USMT");
1150
    put_be32(pb, 0x21d24fce);
1151
    put_be32(pb, 0xbb88695c);
1152
    put_be32(pb, 0xfac9c740);
1153
    put_be32(pb, 0x1c);     // another size here!
1154
    put_tag(pb, "MTDT");
1155
    put_be32(pb, 0x00010012);
1156
    put_be32(pb, 0x0a);
1157
    put_be32(pb, 0x55c40000);
1158
    put_be32(pb, 0x1);
1159
    put_be32(pb, 0x0);
1160
    return 0x34;
1161
}
1162

    
1163
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1164
{
1165
    int64_t pos = url_ftell(pb);
1166
    put_be32(pb, 0); /* size */
1167
    put_tag(pb, "trak");
1168
    mov_write_tkhd_tag(pb, track, st);
1169
    if (track->mode == MODE_PSP || track->hasBframes)
1170
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1171
    mov_write_mdia_tag(pb, track);
1172
    if (track->mode == MODE_PSP)
1173
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1174
    return updateSize(pb, pos);
1175
}
1176

    
1177
#if 0
1178
/* TODO: Not sorted out, but not necessary either */
1179
static int mov_write_iods_tag(ByteIOContext *pb, MOVMuxContext *mov)
1180
{
1181
    put_be32(pb, 0x15); /* size */
1182
    put_tag(pb, "iods");
1183
    put_be32(pb, 0);    /* version & flags */
1184
    put_be16(pb, 0x1007);
1185
    put_byte(pb, 0);
1186
    put_be16(pb, 0x4fff);
1187
    put_be16(pb, 0xfffe);
1188
    put_be16(pb, 0x01ff);
1189
    return 0x15;
1190
}
1191
#endif
1192

    
1193
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVMuxContext *mov)
1194
{
1195
    int maxTrackID = 1, i;
1196
    int64_t maxTrackLenTemp, maxTrackLen = 0;
1197
    int version;
1198

    
1199
    for (i=0; i<mov->nb_streams; i++) {
1200
        if(mov->tracks[i].entry > 0) {
1201
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
1202
            if(maxTrackLen < maxTrackLenTemp)
1203
                maxTrackLen = maxTrackLenTemp;
1204
            if(maxTrackID < mov->tracks[i].trackID)
1205
                maxTrackID = mov->tracks[i].trackID;
1206
        }
1207
    }
1208

    
1209
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1210
    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1211
    put_tag(pb, "mvhd");
1212
    put_byte(pb, version);
1213
    put_be24(pb, 0); /* flags */
1214
    if (version == 1) {
1215
        put_be64(pb, mov->time);
1216
        put_be64(pb, mov->time);
1217
    } else {
1218
        put_be32(pb, mov->time); /* creation time */
1219
        put_be32(pb, mov->time); /* modification time */
1220
    }
1221
    put_be32(pb, mov->timescale); /* timescale */
1222
    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1223

    
1224
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1225
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1226
    put_be16(pb, 0); /* reserved */
1227
    put_be32(pb, 0); /* reserved */
1228
    put_be32(pb, 0); /* reserved */
1229

    
1230
    /* Matrix structure */
1231
    put_be32(pb, 0x00010000); /* reserved */
1232
    put_be32(pb, 0x0); /* reserved */
1233
    put_be32(pb, 0x0); /* reserved */
1234
    put_be32(pb, 0x0); /* reserved */
1235
    put_be32(pb, 0x00010000); /* reserved */
1236
    put_be32(pb, 0x0); /* reserved */
1237
    put_be32(pb, 0x0); /* reserved */
1238
    put_be32(pb, 0x0); /* reserved */
1239
    put_be32(pb, 0x40000000); /* reserved */
1240

    
1241
    put_be32(pb, 0); /* reserved (preview time) */
1242
    put_be32(pb, 0); /* reserved (preview duration) */
1243
    put_be32(pb, 0); /* reserved (poster time) */
1244
    put_be32(pb, 0); /* reserved (selection time) */
1245
    put_be32(pb, 0); /* reserved (selection duration) */
1246
    put_be32(pb, 0); /* reserved (current time) */
1247
    put_be32(pb, maxTrackID+1); /* Next track id */
1248
    return 0x6c;
1249
}
1250

    
1251
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVMuxContext *mov,
1252
                                     AVFormatContext *s)
1253
{
1254
    int64_t pos = url_ftell(pb);
1255
    put_be32(pb, 0); /* size */
1256
    put_tag(pb, "hdlr");
1257
    put_be32(pb, 0);
1258
    put_be32(pb, 0);
1259
    put_tag(pb, "mdir");
1260
    put_tag(pb, "appl");
1261
    put_be32(pb, 0);
1262
    put_be32(pb, 0);
1263
    put_be16(pb, 0);
1264
    return updateSize(pb, pos);
1265
}
1266

    
1267
/* helper function to write a data tag with the specified string as data */
1268
static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int lang, int long_style)
1269
{
1270
    if(long_style){
1271
        int64_t pos = url_ftell(pb);
1272
        put_be32(pb, 0); /* size */
1273
        put_tag(pb, "data");
1274
        put_be32(pb, 1);
1275
        put_be32(pb, 0);
1276
        put_buffer(pb, data, strlen(data));
1277
        return updateSize(pb, pos);
1278
    }else{
1279
        put_be16(pb, strlen(data)); /* string length */
1280
        put_be16(pb, lang);
1281
        put_buffer(pb, data, strlen(data));
1282
        return strlen(data) + 4;
1283
    }
1284
}
1285

    
1286
static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int lang, int long_style){
1287
    int size = 0;
1288
    if (value && value[0]) {
1289
        int64_t pos = url_ftell(pb);
1290
        put_be32(pb, 0); /* size */
1291
        put_tag(pb, name);
1292
        mov_write_string_data_tag(pb, value, lang, long_style);
1293
        size= updateSize(pb, pos);
1294
    }
1295
    return size;
1296
}
1297

    
1298
static int mov_write_string_metadata(AVFormatContext *s, ByteIOContext *pb,
1299
                                     const char *name, const char *tag,
1300
                                     int long_style)
1301
{
1302
    int l, lang = 0, len, len2;
1303
    AVMetadataTag *t, *t2 = NULL;
1304
    char tag2[16];
1305

    
1306
    if (!(t = av_metadata_get(s->metadata, tag, NULL, 0)))
1307
        return 0;
1308

    
1309
    len = strlen(t->key);
1310
    snprintf(tag2, sizeof(tag2), "%s-", tag);
1311
    while ((t2 = av_metadata_get(s->metadata, tag2, t2, AV_METADATA_IGNORE_SUFFIX))) {
1312
        len2 = strlen(t2->key);
1313
        if (len2 == len+4 && !strcmp(t->value, t2->value)
1314
            && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 0)) >= 0) {
1315
            lang = l;
1316
            break;
1317
        }
1318
    }
1319
    return mov_write_string_tag(pb, name, t->value, lang, long_style);
1320
}
1321

    
1322
/* iTunes track number */
1323
static int mov_write_trkn_tag(ByteIOContext *pb, MOVMuxContext *mov,
1324
                              AVFormatContext *s)
1325
{
1326
    AVMetadataTag *t = av_metadata_get(s->metadata, "track", NULL, 0);
1327
    int size = 0, track = t ? atoi(t->value) : 0;
1328
    if (track) {
1329
        int64_t pos = url_ftell(pb);
1330
        put_be32(pb, 0); /* size */
1331
        put_tag(pb, "trkn");
1332
        {
1333
            int64_t pos = url_ftell(pb);
1334
            put_be32(pb, 0); /* size */
1335
            put_tag(pb, "data");
1336
            put_be32(pb, 0);        // 8 bytes empty
1337
            put_be32(pb, 0);
1338
            put_be16(pb, 0);        // empty
1339
            put_be16(pb, track);    // track number
1340
            put_be16(pb, 0);        // total track number
1341
            put_be16(pb, 0);        // empty
1342
            updateSize(pb, pos);
1343
        }
1344
        size = updateSize(pb, pos);
1345
    }
1346
    return size;
1347
}
1348

    
1349
/* iTunes meta data list */
1350
static int mov_write_ilst_tag(ByteIOContext *pb, MOVMuxContext *mov,
1351
                              AVFormatContext *s)
1352
{
1353
    int64_t pos = url_ftell(pb);
1354
    put_be32(pb, 0); /* size */
1355
    put_tag(pb, "ilst");
1356
    mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1357
    mov_write_string_metadata(s, pb, "\251ART", "author"   , 1);
1358
    mov_write_string_metadata(s, pb, "\251wrt", "author"   , 1);
1359
    mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1360
    mov_write_string_metadata(s, pb, "\251day", "year"     , 1);
1361
    mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1362
    mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1363
    mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1364
    mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1365
    mov_write_trkn_tag(pb, mov, s);
1366
    return updateSize(pb, pos);
1367
}
1368

    
1369
/* iTunes meta data tag */
1370
static int mov_write_meta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1371
                              AVFormatContext *s)
1372
{
1373
    int size = 0;
1374
    int64_t pos = url_ftell(pb);
1375
    put_be32(pb, 0); /* size */
1376
    put_tag(pb, "meta");
1377
    put_be32(pb, 0);
1378
    mov_write_itunes_hdlr_tag(pb, mov, s);
1379
    mov_write_ilst_tag(pb, mov, s);
1380
    size = updateSize(pb, pos);
1381
    return size;
1382
}
1383

    
1384
static int utf8len(const uint8_t *b)
1385
{
1386
    int len=0;
1387
    int val;
1388
    while(*b){
1389
        GET_UTF8(val, *b++, return -1;)
1390
        len++;
1391
    }
1392
    return len;
1393
}
1394

    
1395
static int ascii_to_wc(ByteIOContext *pb, const uint8_t *b)
1396
{
1397
    int val;
1398
    while(*b){
1399
        GET_UTF8(val, *b++, return -1;)
1400
        put_be16(pb, val);
1401
    }
1402
    put_be16(pb, 0x00);
1403
    return 0;
1404
}
1405

    
1406
static uint16_t language_code(const char *str)
1407
{
1408
    return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1409
}
1410

    
1411
static int mov_write_3gp_udta_tag(ByteIOContext *pb, AVFormatContext *s,
1412
                                  const char *tag, const char *str)
1413
{
1414
    int64_t pos = url_ftell(pb);
1415
    AVMetadataTag *t = av_metadata_get(s->metadata, str, NULL, 0);
1416
    if (!t || !utf8len(t->value))
1417
        return 0;
1418
    put_be32(pb, 0);   /* size */
1419
    put_tag (pb, tag); /* type */
1420
    put_be32(pb, 0);   /* version + flags */
1421
    if (!strcmp(tag, "yrrc"))
1422
        put_be16(pb, atoi(t->value));
1423
    else {
1424
        put_be16(pb, language_code("eng")); /* language */
1425
        ascii_to_wc(pb, t->value);
1426
        if (!strcmp(tag, "albm") &&
1427
            (t = av_metadata_get(s->metadata, "year", NULL, 0)))
1428
            put_byte(pb, atoi(t->value));
1429
    }
1430
    return updateSize(pb, pos);
1431
}
1432

    
1433
static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1434
                              AVFormatContext *s)
1435
{
1436
    ByteIOContext *pb_buf;
1437
    int i, ret, size;
1438
    uint8_t *buf;
1439

    
1440
    for (i = 0; i < s->nb_streams; i++)
1441
        if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1442
            return 0;
1443
        }
1444

    
1445
    ret = url_open_dyn_buf(&pb_buf);
1446
    if(ret < 0)
1447
        return ret;
1448

    
1449
        if (mov->mode & MODE_3GP) {
1450
            mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1451
            mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1452
            mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1453
            mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1454
            mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1455
            mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1456
            mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "year");
1457
        } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1458
            mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
1459
            mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
1460
            mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
1461
            mov_write_string_metadata(s, pb_buf, "\251day", "year"       , 0);
1462
            mov_write_string_tag(pb_buf, "\251enc", LIBAVFORMAT_IDENT, 0, 0);
1463
            mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
1464
            mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
1465
            mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
1466
        } else {
1467
            /* iTunes meta data */
1468
            mov_write_meta_tag(pb_buf, mov, s);
1469
        }
1470

    
1471
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1472
        put_be32(pb, size+8);
1473
        put_tag(pb, "udta");
1474
        put_buffer(pb, buf, size);
1475
        av_free(buf);
1476
    }
1477

    
1478
    return 0;
1479
}
1480

    
1481
static void mov_write_psp_udta_tag(ByteIOContext *pb,
1482
                                  const char *str, const char *lang, int type)
1483
{
1484
    int len = utf8len(str)+1;
1485
    if(len<=0)
1486
        return;
1487
    put_be16(pb, len*2+10);            /* size */
1488
    put_be32(pb, type);                /* type */
1489
    put_be16(pb, language_code(lang)); /* language */
1490
    put_be16(pb, 0x01);                /* ? */
1491
    ascii_to_wc(pb, str);
1492
}
1493

    
1494
static int mov_write_uuidusmt_tag(ByteIOContext *pb, AVFormatContext *s)
1495
{
1496
    AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
1497
    int64_t pos, pos2;
1498

    
1499
    if (title) {
1500
        pos = url_ftell(pb);
1501
        put_be32(pb, 0); /* size placeholder*/
1502
        put_tag(pb, "uuid");
1503
        put_tag(pb, "USMT");
1504
        put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1505
        put_be32(pb, 0xbb88695c);
1506
        put_be32(pb, 0xfac9c740);
1507

    
1508
        pos2 = url_ftell(pb);
1509
        put_be32(pb, 0); /* size placeholder*/
1510
        put_tag(pb, "MTDT");
1511
        put_be16(pb, 4);
1512

    
1513
        // ?
1514
        put_be16(pb, 0x0C);                 /* size */
1515
        put_be32(pb, 0x0B);                 /* type */
1516
        put_be16(pb, language_code("und")); /* language */
1517
        put_be16(pb, 0x0);                  /* ? */
1518
        put_be16(pb, 0x021C);               /* data */
1519

    
1520
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1521
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1522
//        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);
1523
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1524

    
1525
        updateSize(pb, pos2);
1526
        return updateSize(pb, pos);
1527
    }
1528

    
1529
    return 0;
1530
}
1531

    
1532
static int mov_write_moov_tag(ByteIOContext *pb, MOVMuxContext *mov,
1533
                              AVFormatContext *s)
1534
{
1535
    int i;
1536
    int64_t pos = url_ftell(pb);
1537
    put_be32(pb, 0); /* size placeholder*/
1538
    put_tag(pb, "moov");
1539
    mov->timescale = globalTimescale;
1540

    
1541
    for (i=0; i<mov->nb_streams; i++) {
1542
        if(mov->tracks[i].entry <= 0) continue;
1543

    
1544
        mov->tracks[i].time = mov->time;
1545
        mov->tracks[i].trackID = i+1;
1546
    }
1547

    
1548
    mov_write_mvhd_tag(pb, mov);
1549
    //mov_write_iods_tag(pb, mov);
1550
    for (i=0; i<mov->nb_streams; i++) {
1551
        if(mov->tracks[i].entry > 0) {
1552
            mov_write_trak_tag(pb, &(mov->tracks[i]), s->streams[i]);
1553
        }
1554
    }
1555

    
1556
    if (mov->mode == MODE_PSP)
1557
        mov_write_uuidusmt_tag(pb, s);
1558
    else
1559
        mov_write_udta_tag(pb, mov, s);
1560

    
1561
    return updateSize(pb, pos);
1562
}
1563

    
1564
static int mov_write_mdat_tag(ByteIOContext *pb, MOVMuxContext *mov)
1565
{
1566
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1567
    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1568

    
1569
    mov->mdat_pos = url_ftell(pb);
1570
    put_be32(pb, 0); /* size placeholder*/
1571
    put_tag(pb, "mdat");
1572
    return 0;
1573
}
1574

    
1575
/* TODO: This needs to be more general */
1576
static int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
1577
{
1578
    MOVMuxContext *mov = s->priv_data;
1579
    int64_t pos = url_ftell(pb);
1580
    int has_h264 = 0, has_video = 0;
1581
    int minor = 0x200;
1582
    int i;
1583

    
1584
    for (i = 0; i < s->nb_streams; i++) {
1585
        AVStream *st = s->streams[i];
1586
        if (st->codec->codec_type == CODEC_TYPE_VIDEO)
1587
            has_video = 1;
1588
        if (st->codec->codec_id == CODEC_ID_H264)
1589
            has_h264 = 1;
1590
    }
1591

    
1592
    put_be32(pb, 0); /* size */
1593
    put_tag(pb, "ftyp");
1594

    
1595
    if (mov->mode == MODE_3GP) {
1596
        put_tag(pb, has_h264 ? "3gp6"  : "3gp4");
1597
        minor =     has_h264 ?   0x100 :   0x200;
1598
    } else if (mov->mode & MODE_3G2) {
1599
        put_tag(pb, has_h264 ? "3g2b"  : "3g2a");
1600
        minor =     has_h264 ? 0x20000 : 0x10000;
1601
    }else if (mov->mode == MODE_PSP)
1602
        put_tag(pb, "MSNV");
1603
    else if (mov->mode == MODE_MP4)
1604
        put_tag(pb, "isom");
1605
    else if (mov->mode == MODE_IPOD)
1606
        put_tag(pb, has_video ? "M4V ":"M4A ");
1607
    else
1608
        put_tag(pb, "qt  ");
1609

    
1610
    put_be32(pb, minor);
1611

    
1612
    if(mov->mode == MODE_MOV)
1613
        put_tag(pb, "qt  ");
1614
    else{
1615
        put_tag(pb, "isom");
1616
        put_tag(pb, "iso2");
1617
        if(has_h264)
1618
            put_tag(pb, "avc1");
1619
    }
1620

    
1621
    if (mov->mode == MODE_3GP)
1622
        put_tag(pb, has_h264 ? "3gp6":"3gp4");
1623
    else if (mov->mode & MODE_3G2)
1624
        put_tag(pb, has_h264 ? "3g2b":"3g2a");
1625
    else if (mov->mode == MODE_PSP)
1626
        put_tag(pb, "MSNV");
1627
    else if (mov->mode == MODE_MP4)
1628
        put_tag(pb, "mp41");
1629
    return updateSize(pb, pos);
1630
}
1631

    
1632
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1633
{
1634
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1635
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1636
    int AudioRate = AudioCodec->sample_rate;
1637
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1638
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1639
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1640

    
1641
    put_be32(pb, 0x94); /* size */
1642
    put_tag(pb, "uuid");
1643
    put_tag(pb, "PROF");
1644

    
1645
    put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1646
    put_be32(pb, 0xbb88695c);
1647
    put_be32(pb, 0xfac9c740);
1648

    
1649
    put_be32(pb, 0x0);  /* ? */
1650
    put_be32(pb, 0x3);  /* 3 sections ? */
1651

    
1652
    put_be32(pb, 0x14); /* size */
1653
    put_tag(pb, "FPRF");
1654
    put_be32(pb, 0x0);  /* ? */
1655
    put_be32(pb, 0x0);  /* ? */
1656
    put_be32(pb, 0x0);  /* ? */
1657

    
1658
    put_be32(pb, 0x2c);  /* size */
1659
    put_tag(pb, "APRF");   /* audio */
1660
    put_be32(pb, 0x0);
1661
    put_be32(pb, 0x2);   /* TrackID */
1662
    put_tag(pb, "mp4a");
1663
    put_be32(pb, 0x20f);
1664
    put_be32(pb, 0x0);
1665
    put_be32(pb, audio_kbitrate);
1666
    put_be32(pb, audio_kbitrate);
1667
    put_be32(pb, AudioRate);
1668
    put_be32(pb, AudioCodec->channels);
1669

    
1670
    put_be32(pb, 0x34);  /* size */
1671
    put_tag(pb, "VPRF");   /* video */
1672
    put_be32(pb, 0x0);
1673
    put_be32(pb, 0x1);    /* TrackID */
1674
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1675
        put_tag(pb, "avc1");
1676
        put_be16(pb, 0x014D);
1677
        put_be16(pb, 0x0015);
1678
    } else {
1679
        put_tag(pb, "mp4v");
1680
        put_be16(pb, 0x0000);
1681
        put_be16(pb, 0x0103);
1682
    }
1683
    put_be32(pb, 0x0);
1684
    put_be32(pb, video_kbitrate);
1685
    put_be32(pb, video_kbitrate);
1686
    put_be32(pb, FrameRate);
1687
    put_be32(pb, FrameRate);
1688
    put_be16(pb, VideoCodec->width);
1689
    put_be16(pb, VideoCodec->height);
1690
    put_be32(pb, 0x010001); /* ? */
1691
}
1692

    
1693
static int mov_write_header(AVFormatContext *s)
1694
{
1695
    ByteIOContext *pb = s->pb;
1696
    MOVMuxContext *mov = s->priv_data;
1697
    int i;
1698

    
1699
    if (url_is_streamed(s->pb)) {
1700
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
1701
        return -1;
1702
    }
1703

    
1704
    /* Default mode == MP4 */
1705
    mov->mode = MODE_MP4;
1706

    
1707
    if (s->oformat != NULL) {
1708
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1709
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
1710
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1711
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1712
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
1713

    
1714
        mov_write_ftyp_tag(pb,s);
1715
        if (mov->mode == MODE_PSP) {
1716
            if (s->nb_streams != 2) {
1717
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1718
                return -1;
1719
            }
1720
            mov_write_uuidprof_tag(pb,s);
1721
        }
1722
    }
1723

    
1724
    mov->tracks = av_mallocz(s->nb_streams*sizeof(*mov->tracks));
1725
    if (!mov->tracks)
1726
        return AVERROR(ENOMEM);
1727

    
1728
    for(i=0; i<s->nb_streams; i++){
1729
        AVStream *st= s->streams[i];
1730
        MOVTrack *track= &mov->tracks[i];
1731
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
1732

    
1733
        track->enc = st->codec;
1734
        track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
1735
        if (track->language < 0)
1736
            track->language = 0;
1737
        track->mode = mov->mode;
1738
        track->tag = mov_find_codec_tag(s, track);
1739
        if (!track->tag) {
1740
            av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
1741
                   "codec not currently supported in container\n", i);
1742
            goto error;
1743
        }
1744
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1745
            if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
1746
                track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
1747
                track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
1748
                if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
1749
                    av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
1750
                    goto error;
1751
                }
1752
                track->height = track->tag>>24 == 'n' ? 486 : 576;
1753
            }
1754
            track->timescale = st->codec->time_base.den;
1755
            av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1756
            if (track->mode == MODE_MOV && track->timescale > 100000)
1757
                av_log(s, AV_LOG_WARNING,
1758
                       "WARNING codec timebase is very high. If duration is too long,\n"
1759
                       "file may not be playable by quicktime. Specify a shorter timebase\n"
1760
                       "or choose different container.\n");
1761
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO){
1762
            track->timescale = st->codec->sample_rate;
1763
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1764
            if(!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
1765
                av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
1766
                goto error;
1767
            }else if(st->codec->frame_size > 1){ /* assume compressed audio */
1768
                track->audio_vbr = 1;
1769
            }else{
1770
                st->codec->frame_size = 1;
1771
                track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
1772
            }
1773
            if(track->mode != MODE_MOV &&
1774
               track->enc->codec_id == CODEC_ID_MP3 && track->enc->sample_rate < 16000){
1775
                av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
1776
                       i, track->enc->sample_rate);
1777
                goto error;
1778
            }
1779
        }else if(st->codec->codec_type == CODEC_TYPE_SUBTITLE){
1780
            track->timescale = st->codec->time_base.den;
1781
            av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1782
        }
1783
        if (!track->height)
1784
            track->height = st->codec->height;
1785
    }
1786

    
1787
    mov_write_mdat_tag(pb, mov);
1788
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1789
    mov->nb_streams = s->nb_streams;
1790

    
1791
    put_flush_packet(pb);
1792

    
1793
    return 0;
1794
 error:
1795
    av_freep(&mov->tracks);
1796
    return -1;
1797
}
1798

    
1799
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1800
{
1801
    MOVMuxContext *mov = s->priv_data;
1802
    ByteIOContext *pb = s->pb;
1803
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1804
    AVCodecContext *enc = trk->enc;
1805
    unsigned int samplesInChunk = 0;
1806
    int size= pkt->size;
1807

    
1808
    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1809
    if (!size) return 0; /* Discard 0 sized packets */
1810

    
1811
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1812
        /* We must find out how many AMR blocks there are in one packet */
1813
        static uint16_t packed_size[16] =
1814
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1815
        int len = 0;
1816

    
1817
        while (len < size && samplesInChunk < 100) {
1818
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1819
            samplesInChunk++;
1820
        }
1821
        if(samplesInChunk > 1){
1822
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
1823
            return -1;
1824
        }
1825
    } else if (trk->sampleSize)
1826
        samplesInChunk = size/trk->sampleSize;
1827
    else
1828
        samplesInChunk = 1;
1829

    
1830
    /* copy extradata if it exists */
1831
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1832
        trk->vosLen = enc->extradata_size;
1833
        trk->vosData = av_malloc(trk->vosLen);
1834
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1835
    }
1836

    
1837
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1838
        /* from x264 or from bytestream h264 */
1839
        /* nal reformating needed */
1840
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1841
    } else {
1842
        put_buffer(pb, pkt->data, size);
1843
    }
1844

    
1845
    if ((enc->codec_id == CODEC_ID_DNXHD ||
1846
                enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
1847
        /* copy frame to create needed atoms */
1848
        trk->vosLen = size;
1849
        trk->vosData = av_malloc(size);
1850
        if (!trk->vosData)
1851
            return AVERROR(ENOMEM);
1852
        memcpy(trk->vosData, pkt->data, size);
1853
    }
1854

    
1855
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1856
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1857
        if (!trk->cluster)
1858
            return -1;
1859
    }
1860

    
1861
    trk->cluster[trk->entry].pos = url_ftell(pb) - size;
1862
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1863
    trk->cluster[trk->entry].size = size;
1864
    trk->cluster[trk->entry].entries = samplesInChunk;
1865
    trk->cluster[trk->entry].dts = pkt->dts;
1866
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1867

    
1868
    if (pkt->pts == AV_NOPTS_VALUE) {
1869
        av_log(s, AV_LOG_WARNING, "pts has no value\n");
1870
        pkt->pts = pkt->dts;
1871
    }
1872
    if (pkt->dts != pkt->pts)
1873
        trk->hasBframes = 1;
1874
    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1875
    trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1876
    if(trk->cluster[trk->entry].key_frame)
1877
        trk->hasKeyframes++;
1878
    trk->entry++;
1879
    trk->sampleCount += samplesInChunk;
1880
    mov->mdat_size += size;
1881

    
1882
    put_flush_packet(pb);
1883
    return 0;
1884
}
1885

    
1886
static int mov_write_trailer(AVFormatContext *s)
1887
{
1888
    MOVMuxContext *mov = s->priv_data;
1889
    ByteIOContext *pb = s->pb;
1890
    int res = 0;
1891
    int i;
1892

    
1893
    int64_t moov_pos = url_ftell(pb);
1894

    
1895
    /* Write size of mdat tag */
1896
    if (mov->mdat_size+8 <= UINT32_MAX) {
1897
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
1898
        put_be32(pb, mov->mdat_size+8);
1899
    } else {
1900
        /* overwrite 'wide' placeholder atom */
1901
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1902
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1903
        put_tag(pb, "mdat");
1904
        put_be64(pb, mov->mdat_size+16);
1905
    }
1906
    url_fseek(pb, moov_pos, SEEK_SET);
1907

    
1908
    mov_write_moov_tag(pb, mov, s);
1909

    
1910
    for (i=0; i<mov->nb_streams; i++) {
1911
        av_freep(&mov->tracks[i].cluster);
1912

    
1913
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
1914

    
1915
    }
1916

    
1917
    put_flush_packet(pb);
1918

    
1919
    av_freep(&mov->tracks);
1920

    
1921
    return res;
1922
}
1923

    
1924
#if CONFIG_MOV_MUXER
1925
AVOutputFormat mov_muxer = {
1926
    "mov",
1927
    NULL_IF_CONFIG_SMALL("MOV format"),
1928
    NULL,
1929
    "mov",
1930
    sizeof(MOVMuxContext),
1931
    CODEC_ID_AAC,
1932
    CODEC_ID_MPEG4,
1933
    mov_write_header,
1934
    mov_write_packet,
1935
    mov_write_trailer,
1936
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1937
    .codec_tag = (const AVCodecTag* const []){codec_movvideo_tags, codec_movaudio_tags, 0},
1938
};
1939
#endif
1940
#if CONFIG_TGP_MUXER
1941
AVOutputFormat tgp_muxer = {
1942
    "3gp",
1943
    NULL_IF_CONFIG_SMALL("3GP format"),
1944
    NULL,
1945
    "3gp",
1946
    sizeof(MOVMuxContext),
1947
    CODEC_ID_AMR_NB,
1948
    CODEC_ID_H263,
1949
    mov_write_header,
1950
    mov_write_packet,
1951
    mov_write_trailer,
1952
    .flags = AVFMT_GLOBALHEADER,
1953
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
1954
};
1955
#endif
1956
#if CONFIG_MP4_MUXER
1957
AVOutputFormat mp4_muxer = {
1958
    "mp4",
1959
    NULL_IF_CONFIG_SMALL("MP4 format"),
1960
    "application/mp4",
1961
    "mp4",
1962
    sizeof(MOVMuxContext),
1963
    CODEC_ID_AAC,
1964
    CODEC_ID_MPEG4,
1965
    mov_write_header,
1966
    mov_write_packet,
1967
    mov_write_trailer,
1968
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1969
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
1970
};
1971
#endif
1972
#if CONFIG_PSP_MUXER
1973
AVOutputFormat psp_muxer = {
1974
    "psp",
1975
    NULL_IF_CONFIG_SMALL("PSP MP4 format"),
1976
    NULL,
1977
    "mp4,psp",
1978
    sizeof(MOVMuxContext),
1979
    CODEC_ID_AAC,
1980
    CODEC_ID_MPEG4,
1981
    mov_write_header,
1982
    mov_write_packet,
1983
    mov_write_trailer,
1984
    .flags = AVFMT_GLOBALHEADER,
1985
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
1986
};
1987
#endif
1988
#if CONFIG_TG2_MUXER
1989
AVOutputFormat tg2_muxer = {
1990
    "3g2",
1991
    NULL_IF_CONFIG_SMALL("3GP2 format"),
1992
    NULL,
1993
    "3g2",
1994
    sizeof(MOVMuxContext),
1995
    CODEC_ID_AMR_NB,
1996
    CODEC_ID_H263,
1997
    mov_write_header,
1998
    mov_write_packet,
1999
    mov_write_trailer,
2000
    .flags = AVFMT_GLOBALHEADER,
2001
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2002
};
2003
#endif
2004
#if CONFIG_IPOD_MUXER
2005
AVOutputFormat ipod_muxer = {
2006
    "ipod",
2007
    NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
2008
    "application/mp4",
2009
    "m4v,m4a",
2010
    sizeof(MOVMuxContext),
2011
    CODEC_ID_AAC,
2012
    CODEC_ID_H264,
2013
    mov_write_header,
2014
    mov_write_packet,
2015
    mov_write_trailer,
2016
    .flags = AVFMT_GLOBALHEADER,
2017
    .codec_tag = (const AVCodecTag* const []){codec_ipod_tags, 0},
2018
};
2019
#endif