Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ ab4752e3

History | View | Annotate | Download (64.9 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 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 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
    uint32_t     flags;
55
} MOVIentry;
56

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

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

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

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

    
97
    return curpos - pos;
98
}
99

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
269
    return 11;
270
}
271

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
565
    return tag;
566
}
567

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

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

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

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

    
593
    return tag;
594
}
595

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

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

    
607
    return tag;
608
}
609

    
610
static const struct {
611
    enum PixelFormat pix_fmt;
612
    uint32_t tag;
613
    unsigned bps;
614
} mov_pix_fmt_tags[] = {
615
    { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
616
    { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
617
    { PIX_FMT_BGR555,  MKTAG('r','a','w',' '), 16 },
618
    { PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
619
    { PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
620
    { PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
621
    { PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
622
    { PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
623
    { PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
624
    { PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
625
    { PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
626
};
627

    
628
static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
629
{
630
    int tag = track->enc->codec_tag;
631
    int i;
632

    
633
    for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
634
        if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
635
            tag = mov_pix_fmt_tags[i].tag;
636
            track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
637
            break;
638
        }
639
    }
640

    
641
    return tag;
642
}
643

    
644
static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
645
{
646
    int tag = track->enc->codec_tag;
647

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

    
678
    return tag;
679
}
680

    
681
static const AVCodecTag codec_3gp_tags[] = {
682
    { CODEC_ID_H263,   MKTAG('s','2','6','3') },
683
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
684
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
685
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
686
    { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
687
    { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
688
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
689
    { CODEC_ID_NONE, 0 },
690
};
691

    
692
static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
693
{
694
    int tag = track->enc->codec_tag;
695

    
696
    if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
697
        tag = mp4_get_codec_tag(s, track);
698
    else if (track->mode == MODE_IPOD)
699
        tag = ipod_get_codec_tag(s, track);
700
    else if (track->mode & MODE_3GP)
701
        tag = codec_get_tag(codec_3gp_tags, track->enc->codec_id);
702
    else
703
        tag = mov_get_codec_tag(s, track);
704

    
705
    return tag;
706
}
707

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

    
724
static int mov_write_subtitle_tag(ByteIOContext *pb, MOVTrack *track)
725
{
726
    int64_t pos = url_ftell(pb);
727
    put_be32(pb, 0);    /* size */
728
    put_le32(pb, track->tag); // store it byteswapped
729
    put_be32(pb, 0);    /* Reserved */
730
    put_be16(pb, 0);    /* Reserved */
731
    put_be16(pb, 1);    /* Data-reference index */
732

    
733
    if (track->enc->extradata_size)
734
        put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
735

    
736
    return updateSize(pb, pos);
737
}
738

    
739
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack *track)
740
{
741
    int64_t pos = url_ftell(pb);
742
    char compressor_name[32];
743

    
744
    put_be32(pb, 0); /* size */
745
    put_le32(pb, track->tag); // store it byteswapped
746
    put_be32(pb, 0); /* Reserved */
747
    put_be16(pb, 0); /* Reserved */
748
    put_be16(pb, 1); /* Data-reference index */
749

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

    
773
    memset(compressor_name,0,32);
774
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
775
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
776
        strncpy(compressor_name,track->enc->codec->name,31);
777
    put_byte(pb, strlen(compressor_name));
778
    put_buffer(pb, compressor_name, 31);
779

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

    
800
    return updateSize(pb, pos);
801
}
802

    
803
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack *track)
804
{
805
    int64_t pos = url_ftell(pb);
806
    put_be32(pb, 0); /* size */
807
    put_tag(pb, "stsd");
808
    put_be32(pb, 0); /* version & flags */
809
    put_be32(pb, 1); /* entry count */
810
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
811
        mov_write_video_tag(pb, track);
812
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
813
        mov_write_audio_tag(pb, track);
814
    else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE)
815
        mov_write_subtitle_tag(pb, track);
816
    return updateSize(pb, pos);
817
}
818

    
819
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack *track)
820
{
821
    MOVStts *ctts_entries;
822
    uint32_t entries = 0;
823
    uint32_t atom_size;
824
    int i;
825

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

    
852
/* Time to sample atom */
853
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack *track)
854
{
855
    MOVStts *stts_entries;
856
    uint32_t entries = -1;
857
    uint32_t atom_size;
858
    int i;
859

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

    
894
static int mov_write_dref_tag(ByteIOContext *pb)
895
{
896
    put_be32(pb, 28); /* size */
897
    put_tag(pb, "dref");
898
    put_be32(pb, 0); /* version & flags */
899
    put_be32(pb, 1); /* entry count */
900

    
901
    put_be32(pb, 0xc); /* size */
902
    put_tag(pb, "url ");
903
    put_be32(pb, 1); /* version & flags */
904

    
905
    return 28;
906
}
907

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

    
927
static int mov_write_dinf_tag(ByteIOContext *pb)
928
{
929
    int64_t pos = url_ftell(pb);
930
    put_be32(pb, 0); /* size */
931
    put_tag(pb, "dinf");
932
    mov_write_dref_tag(pb);
933
    return updateSize(pb, pos);
934
}
935

    
936
static int mov_write_nmhd_tag(ByteIOContext *pb)
937
{
938
    put_be32(pb, 12);
939
    put_tag(pb, "nmhd");
940
    put_be32(pb, 0);
941
    return 12;
942
}
943

    
944
static int mov_write_gmhd_tag(ByteIOContext *pb)
945
{
946
    put_be32(pb, 0x20);   /* size */
947
    put_tag(pb, "gmhd");
948
    put_be32(pb, 0x18);   /* gmin size */
949
    put_tag(pb, "gmin");  /* generic media info */
950
    put_be32(pb, 0);      /* version & flags */
951
    put_be16(pb, 0x40);   /* graphics mode = */
952
    put_be16(pb, 0x8000); /* opColor (r?) */
953
    put_be16(pb, 0x8000); /* opColor (g?) */
954
    put_be16(pb, 0x8000); /* opColor (b?) */
955
    put_be16(pb, 0);      /* balance */
956
    put_be16(pb, 0);      /* reserved */
957
    return 0x20;
958
}
959

    
960
static int mov_write_smhd_tag(ByteIOContext *pb)
961
{
962
    put_be32(pb, 16); /* size */
963
    put_tag(pb, "smhd");
964
    put_be32(pb, 0); /* version & flags */
965
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
966
    put_be16(pb, 0); /* reserved */
967
    return 16;
968
}
969

    
970
static int mov_write_vmhd_tag(ByteIOContext *pb)
971
{
972
    put_be32(pb, 0x14); /* size (always 0x14) */
973
    put_tag(pb, "vmhd");
974
    put_be32(pb, 0x01); /* version & flags */
975
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
976
    return 0x14;
977
}
978

    
979
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)
980
{
981
    const char *hdlr, *descr = NULL, *hdlr_type = NULL;
982
    int64_t pos = url_ftell(pb);
983

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

    
1003
    put_be32(pb, 0); /* size */
1004
    put_tag(pb, "hdlr");
1005
    put_be32(pb, 0); /* Version & flags */
1006
    put_buffer(pb, hdlr, 4); /* handler */
1007
    put_tag(pb, hdlr_type); /* handler type */
1008
    put_be32(pb ,0); /* reserved */
1009
    put_be32(pb ,0); /* reserved */
1010
    put_be32(pb ,0); /* reserved */
1011
    put_byte(pb, strlen(descr)); /* string counter */
1012
    put_buffer(pb, descr, strlen(descr)); /* handler description */
1013
    return updateSize(pb, pos);
1014
}
1015

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

    
1036
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack *track)
1037
{
1038
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
1039

    
1040
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
1041
    put_tag(pb, "mdhd");
1042
    put_byte(pb, version);
1043
    put_be24(pb, 0); /* flags */
1044
    if (version == 1) {
1045
        put_be64(pb, track->time);
1046
        put_be64(pb, track->time);
1047
    } else {
1048
        put_be32(pb, track->time); /* creation time */
1049
        put_be32(pb, track->time); /* modification time */
1050
    }
1051
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
1052
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
1053
    put_be16(pb, track->language); /* language */
1054
    put_be16(pb, 0); /* reserved (quality) */
1055

    
1056
    if(version!=0 && track->mode == MODE_MOV){
1057
        av_log(NULL, AV_LOG_ERROR,
1058
            "FATAL error, file duration too long for timebase, this file will not be\n"
1059
            "playable with quicktime. Choose a different timebase or a different\n"
1060
            "container format\n");
1061
    }
1062

    
1063
    return 32;
1064
}
1065

    
1066
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack *track)
1067
{
1068
    int64_t pos = url_ftell(pb);
1069
    put_be32(pb, 0); /* size */
1070
    put_tag(pb, "mdia");
1071
    mov_write_mdhd_tag(pb, track);
1072
    mov_write_hdlr_tag(pb, track);
1073
    mov_write_minf_tag(pb, track);
1074
    return updateSize(pb, pos);
1075
}
1076

    
1077
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1078
{
1079
    int64_t duration = av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP);
1080
    int version = duration < INT32_MAX ? 0 : 1;
1081

    
1082
    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
1083
    put_tag(pb, "tkhd");
1084
    put_byte(pb, version);
1085
    put_be24(pb, 0xf); /* flags (track enabled) */
1086
    if (version == 1) {
1087
        put_be64(pb, track->time);
1088
        put_be64(pb, track->time);
1089
    } else {
1090
        put_be32(pb, track->time); /* creation time */
1091
        put_be32(pb, track->time); /* modification time */
1092
    }
1093
    put_be32(pb, track->trackID); /* track-id */
1094
    put_be32(pb, 0); /* reserved */
1095
    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
1096

    
1097
    put_be32(pb, 0); /* reserved */
1098
    put_be32(pb, 0); /* reserved */
1099
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
1100
    /* Volume, only for audio */
1101
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
1102
        put_be16(pb, 0x0100);
1103
    else
1104
        put_be16(pb, 0);
1105
    put_be16(pb, 0); /* reserved */
1106

    
1107
    /* Matrix structure */
1108
    put_be32(pb, 0x00010000); /* reserved */
1109
    put_be32(pb, 0x0); /* reserved */
1110
    put_be32(pb, 0x0); /* reserved */
1111
    put_be32(pb, 0x0); /* reserved */
1112
    put_be32(pb, 0x00010000); /* reserved */
1113
    put_be32(pb, 0x0); /* reserved */
1114
    put_be32(pb, 0x0); /* reserved */
1115
    put_be32(pb, 0x0); /* reserved */
1116
    put_be32(pb, 0x40000000); /* reserved */
1117

    
1118
    /* Track width and height, for visual only */
1119
    if(track->enc->codec_type == CODEC_TYPE_VIDEO ||
1120
       track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
1121
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1122
        if(!sample_aspect_ratio || track->height != track->enc->height)
1123
            sample_aspect_ratio = 1;
1124
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1125
        put_be32(pb, track->height*0x10000);
1126
    }
1127
    else {
1128
        put_be32(pb, 0);
1129
        put_be32(pb, 0);
1130
    }
1131
    return 0x5c;
1132
}
1133

    
1134
// This box seems important for the psp playback ... without it the movie seems to hang
1135
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
1136
{
1137
    put_be32(pb, 0x24); /* size  */
1138
    put_tag(pb, "edts");
1139
    put_be32(pb, 0x1c); /* size  */
1140
    put_tag(pb, "elst");
1141
    put_be32(pb, 0x0);
1142
    put_be32(pb, 0x1);
1143

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

    
1146
    put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
1147
    put_be32(pb, 0x00010000);
1148
    return 0x24;
1149
}
1150

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

    
1170
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1171
{
1172
    int64_t pos = url_ftell(pb);
1173
    put_be32(pb, 0); /* size */
1174
    put_tag(pb, "trak");
1175
    mov_write_tkhd_tag(pb, track, st);
1176
    if (track->mode == MODE_PSP || track->hasBframes)
1177
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1178
    mov_write_mdia_tag(pb, track);
1179
    if (track->mode == MODE_PSP)
1180
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1181
    return updateSize(pb, pos);
1182
}
1183

    
1184
#if 0
1185
/* TODO: Not sorted out, but not necessary either */
1186
static int mov_write_iods_tag(ByteIOContext *pb, MOVMuxContext *mov)
1187
{
1188
    put_be32(pb, 0x15); /* size */
1189
    put_tag(pb, "iods");
1190
    put_be32(pb, 0);    /* version & flags */
1191
    put_be16(pb, 0x1007);
1192
    put_byte(pb, 0);
1193
    put_be16(pb, 0x4fff);
1194
    put_be16(pb, 0xfffe);
1195
    put_be16(pb, 0x01ff);
1196
    return 0x15;
1197
}
1198
#endif
1199

    
1200
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVMuxContext *mov)
1201
{
1202
    int maxTrackID = 1, i;
1203
    int64_t maxTrackLenTemp, maxTrackLen = 0;
1204
    int version;
1205

    
1206
    for (i=0; i<mov->nb_streams; i++) {
1207
        if(mov->tracks[i].entry > 0) {
1208
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
1209
            if(maxTrackLen < maxTrackLenTemp)
1210
                maxTrackLen = maxTrackLenTemp;
1211
            if(maxTrackID < mov->tracks[i].trackID)
1212
                maxTrackID = mov->tracks[i].trackID;
1213
        }
1214
    }
1215

    
1216
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1217
    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1218
    put_tag(pb, "mvhd");
1219
    put_byte(pb, version);
1220
    put_be24(pb, 0); /* flags */
1221
    if (version == 1) {
1222
        put_be64(pb, mov->time);
1223
        put_be64(pb, mov->time);
1224
    } else {
1225
        put_be32(pb, mov->time); /* creation time */
1226
        put_be32(pb, mov->time); /* modification time */
1227
    }
1228
    put_be32(pb, mov->timescale); /* timescale */
1229
    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1230

    
1231
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1232
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1233
    put_be16(pb, 0); /* reserved */
1234
    put_be32(pb, 0); /* reserved */
1235
    put_be32(pb, 0); /* reserved */
1236

    
1237
    /* Matrix structure */
1238
    put_be32(pb, 0x00010000); /* reserved */
1239
    put_be32(pb, 0x0); /* reserved */
1240
    put_be32(pb, 0x0); /* reserved */
1241
    put_be32(pb, 0x0); /* reserved */
1242
    put_be32(pb, 0x00010000); /* reserved */
1243
    put_be32(pb, 0x0); /* reserved */
1244
    put_be32(pb, 0x0); /* reserved */
1245
    put_be32(pb, 0x0); /* reserved */
1246
    put_be32(pb, 0x40000000); /* reserved */
1247

    
1248
    put_be32(pb, 0); /* reserved (preview time) */
1249
    put_be32(pb, 0); /* reserved (preview duration) */
1250
    put_be32(pb, 0); /* reserved (poster time) */
1251
    put_be32(pb, 0); /* reserved (selection time) */
1252
    put_be32(pb, 0); /* reserved (selection duration) */
1253
    put_be32(pb, 0); /* reserved (current time) */
1254
    put_be32(pb, maxTrackID+1); /* Next track id */
1255
    return 0x6c;
1256
}
1257

    
1258
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVMuxContext *mov,
1259
                                     AVFormatContext *s)
1260
{
1261
    int64_t pos = url_ftell(pb);
1262
    put_be32(pb, 0); /* size */
1263
    put_tag(pb, "hdlr");
1264
    put_be32(pb, 0);
1265
    put_be32(pb, 0);
1266
    put_tag(pb, "mdir");
1267
    put_tag(pb, "appl");
1268
    put_be32(pb, 0);
1269
    put_be32(pb, 0);
1270
    put_be16(pb, 0);
1271
    return updateSize(pb, pos);
1272
}
1273

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

    
1293
static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int lang, int long_style){
1294
    int size = 0;
1295
    if (value && value[0]) {
1296
        int64_t pos = url_ftell(pb);
1297
        put_be32(pb, 0); /* size */
1298
        put_tag(pb, name);
1299
        mov_write_string_data_tag(pb, value, lang, long_style);
1300
        size= updateSize(pb, pos);
1301
    }
1302
    return size;
1303
}
1304

    
1305
static int mov_write_string_metadata(AVFormatContext *s, ByteIOContext *pb,
1306
                                     const char *name, const char *tag,
1307
                                     int long_style)
1308
{
1309
    int l, lang = 0, len, len2;
1310
    AVMetadataTag *t, *t2 = NULL;
1311
    char tag2[16];
1312

    
1313
    if (!(t = av_metadata_get(s->metadata, tag, NULL, 0)))
1314
        return 0;
1315

    
1316
    len = strlen(t->key);
1317
    snprintf(tag2, sizeof(tag2), "%s-", tag);
1318
    while ((t2 = av_metadata_get(s->metadata, tag2, t2, AV_METADATA_IGNORE_SUFFIX))) {
1319
        len2 = strlen(t2->key);
1320
        if (len2 == len+4 && !strcmp(t->value, t2->value)
1321
            && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 0)) >= 0) {
1322
            lang = l;
1323
            break;
1324
        }
1325
    }
1326
    return mov_write_string_tag(pb, name, t->value, lang, long_style);
1327
}
1328

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

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

    
1376
/* iTunes meta data tag */
1377
static int mov_write_meta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1378
                              AVFormatContext *s)
1379
{
1380
    int size = 0;
1381
    int64_t pos = url_ftell(pb);
1382
    put_be32(pb, 0); /* size */
1383
    put_tag(pb, "meta");
1384
    put_be32(pb, 0);
1385
    mov_write_itunes_hdlr_tag(pb, mov, s);
1386
    mov_write_ilst_tag(pb, mov, s);
1387
    size = updateSize(pb, pos);
1388
    return size;
1389
}
1390

    
1391
static int utf8len(const uint8_t *b)
1392
{
1393
    int len=0;
1394
    int val;
1395
    while(*b){
1396
        GET_UTF8(val, *b++, return -1;)
1397
        len++;
1398
    }
1399
    return len;
1400
}
1401

    
1402
static int ascii_to_wc(ByteIOContext *pb, const uint8_t *b)
1403
{
1404
    int val;
1405
    while(*b){
1406
        GET_UTF8(val, *b++, return -1;)
1407
        put_be16(pb, val);
1408
    }
1409
    put_be16(pb, 0x00);
1410
    return 0;
1411
}
1412

    
1413
static uint16_t language_code(const char *str)
1414
{
1415
    return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1416
}
1417

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

    
1440
static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1441
                              AVFormatContext *s)
1442
{
1443
    ByteIOContext *pb_buf;
1444
    int i, ret, size;
1445
    uint8_t *buf;
1446

    
1447
    for (i = 0; i < s->nb_streams; i++)
1448
        if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1449
            return 0;
1450
        }
1451

    
1452
    ret = url_open_dyn_buf(&pb_buf);
1453
    if(ret < 0)
1454
        return ret;
1455

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

    
1478
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1479
        put_be32(pb, size+8);
1480
        put_tag(pb, "udta");
1481
        put_buffer(pb, buf, size);
1482
        av_free(buf);
1483
    }
1484

    
1485
    return 0;
1486
}
1487

    
1488
static void mov_write_psp_udta_tag(ByteIOContext *pb,
1489
                                  const char *str, const char *lang, int type)
1490
{
1491
    int len = utf8len(str)+1;
1492
    if(len<=0)
1493
        return;
1494
    put_be16(pb, len*2+10);            /* size */
1495
    put_be32(pb, type);                /* type */
1496
    put_be16(pb, language_code(lang)); /* language */
1497
    put_be16(pb, 0x01);                /* ? */
1498
    ascii_to_wc(pb, str);
1499
}
1500

    
1501
static int mov_write_uuidusmt_tag(ByteIOContext *pb, AVFormatContext *s)
1502
{
1503
    AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
1504
    int64_t pos, pos2;
1505

    
1506
    if (title) {
1507
        pos = url_ftell(pb);
1508
        put_be32(pb, 0); /* size placeholder*/
1509
        put_tag(pb, "uuid");
1510
        put_tag(pb, "USMT");
1511
        put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1512
        put_be32(pb, 0xbb88695c);
1513
        put_be32(pb, 0xfac9c740);
1514

    
1515
        pos2 = url_ftell(pb);
1516
        put_be32(pb, 0); /* size placeholder*/
1517
        put_tag(pb, "MTDT");
1518
        put_be16(pb, 4);
1519

    
1520
        // ?
1521
        put_be16(pb, 0x0C);                 /* size */
1522
        put_be32(pb, 0x0B);                 /* type */
1523
        put_be16(pb, language_code("und")); /* language */
1524
        put_be16(pb, 0x0);                  /* ? */
1525
        put_be16(pb, 0x021C);               /* data */
1526

    
1527
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1528
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1529
//        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);
1530
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1531

    
1532
        updateSize(pb, pos2);
1533
        return updateSize(pb, pos);
1534
    }
1535

    
1536
    return 0;
1537
}
1538

    
1539
static int mov_write_moov_tag(ByteIOContext *pb, MOVMuxContext *mov,
1540
                              AVFormatContext *s)
1541
{
1542
    int i;
1543
    int64_t pos = url_ftell(pb);
1544
    put_be32(pb, 0); /* size placeholder*/
1545
    put_tag(pb, "moov");
1546
    mov->timescale = globalTimescale;
1547

    
1548
    for (i=0; i<mov->nb_streams; i++) {
1549
        if(mov->tracks[i].entry <= 0) continue;
1550

    
1551
        mov->tracks[i].time = mov->time;
1552
        mov->tracks[i].trackID = i+1;
1553
    }
1554

    
1555
    mov_write_mvhd_tag(pb, mov);
1556
    //mov_write_iods_tag(pb, mov);
1557
    for (i=0; i<mov->nb_streams; i++) {
1558
        if(mov->tracks[i].entry > 0) {
1559
            mov_write_trak_tag(pb, &(mov->tracks[i]), s->streams[i]);
1560
        }
1561
    }
1562

    
1563
    if (mov->mode == MODE_PSP)
1564
        mov_write_uuidusmt_tag(pb, s);
1565
    else
1566
        mov_write_udta_tag(pb, mov, s);
1567

    
1568
    return updateSize(pb, pos);
1569
}
1570

    
1571
static int mov_write_mdat_tag(ByteIOContext *pb, MOVMuxContext *mov)
1572
{
1573
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1574
    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1575

    
1576
    mov->mdat_pos = url_ftell(pb);
1577
    put_be32(pb, 0); /* size placeholder*/
1578
    put_tag(pb, "mdat");
1579
    return 0;
1580
}
1581

    
1582
/* TODO: This needs to be more general */
1583
static int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
1584
{
1585
    MOVMuxContext *mov = s->priv_data;
1586
    int64_t pos = url_ftell(pb);
1587
    int has_h264 = 0, has_video = 0;
1588
    int minor = 0x200;
1589
    int i;
1590

    
1591
    for (i = 0; i < s->nb_streams; i++) {
1592
        AVStream *st = s->streams[i];
1593
        if (st->codec->codec_type == CODEC_TYPE_VIDEO)
1594
            has_video = 1;
1595
        if (st->codec->codec_id == CODEC_ID_H264)
1596
            has_h264 = 1;
1597
    }
1598

    
1599
    put_be32(pb, 0); /* size */
1600
    put_tag(pb, "ftyp");
1601

    
1602
    if (mov->mode == MODE_3GP) {
1603
        put_tag(pb, has_h264 ? "3gp6"  : "3gp4");
1604
        minor =     has_h264 ?   0x100 :   0x200;
1605
    } else if (mov->mode & MODE_3G2) {
1606
        put_tag(pb, has_h264 ? "3g2b"  : "3g2a");
1607
        minor =     has_h264 ? 0x20000 : 0x10000;
1608
    }else if (mov->mode == MODE_PSP)
1609
        put_tag(pb, "MSNV");
1610
    else if (mov->mode == MODE_MP4)
1611
        put_tag(pb, "isom");
1612
    else if (mov->mode == MODE_IPOD)
1613
        put_tag(pb, has_video ? "M4V ":"M4A ");
1614
    else
1615
        put_tag(pb, "qt  ");
1616

    
1617
    put_be32(pb, minor);
1618

    
1619
    if(mov->mode == MODE_MOV)
1620
        put_tag(pb, "qt  ");
1621
    else{
1622
        put_tag(pb, "isom");
1623
        put_tag(pb, "iso2");
1624
        if(has_h264)
1625
            put_tag(pb, "avc1");
1626
    }
1627

    
1628
    if (mov->mode == MODE_3GP)
1629
        put_tag(pb, has_h264 ? "3gp6":"3gp4");
1630
    else if (mov->mode & MODE_3G2)
1631
        put_tag(pb, has_h264 ? "3g2b":"3g2a");
1632
    else if (mov->mode == MODE_PSP)
1633
        put_tag(pb, "MSNV");
1634
    else if (mov->mode == MODE_MP4)
1635
        put_tag(pb, "mp41");
1636
    return updateSize(pb, pos);
1637
}
1638

    
1639
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1640
{
1641
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1642
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1643
    int AudioRate = AudioCodec->sample_rate;
1644
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1645
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1646
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1647

    
1648
    put_be32(pb, 0x94); /* size */
1649
    put_tag(pb, "uuid");
1650
    put_tag(pb, "PROF");
1651

    
1652
    put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1653
    put_be32(pb, 0xbb88695c);
1654
    put_be32(pb, 0xfac9c740);
1655

    
1656
    put_be32(pb, 0x0);  /* ? */
1657
    put_be32(pb, 0x3);  /* 3 sections ? */
1658

    
1659
    put_be32(pb, 0x14); /* size */
1660
    put_tag(pb, "FPRF");
1661
    put_be32(pb, 0x0);  /* ? */
1662
    put_be32(pb, 0x0);  /* ? */
1663
    put_be32(pb, 0x0);  /* ? */
1664

    
1665
    put_be32(pb, 0x2c);  /* size */
1666
    put_tag(pb, "APRF");   /* audio */
1667
    put_be32(pb, 0x0);
1668
    put_be32(pb, 0x2);   /* TrackID */
1669
    put_tag(pb, "mp4a");
1670
    put_be32(pb, 0x20f);
1671
    put_be32(pb, 0x0);
1672
    put_be32(pb, audio_kbitrate);
1673
    put_be32(pb, audio_kbitrate);
1674
    put_be32(pb, AudioRate);
1675
    put_be32(pb, AudioCodec->channels);
1676

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

    
1700
static int mov_write_header(AVFormatContext *s)
1701
{
1702
    ByteIOContext *pb = s->pb;
1703
    MOVMuxContext *mov = s->priv_data;
1704
    int i;
1705

    
1706
    if (url_is_streamed(s->pb)) {
1707
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
1708
        return -1;
1709
    }
1710

    
1711
    /* Default mode == MP4 */
1712
    mov->mode = MODE_MP4;
1713

    
1714
    if (s->oformat != NULL) {
1715
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1716
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
1717
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1718
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1719
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
1720

    
1721
        mov_write_ftyp_tag(pb,s);
1722
        if (mov->mode == MODE_PSP) {
1723
            if (s->nb_streams != 2) {
1724
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1725
                return -1;
1726
            }
1727
            mov_write_uuidprof_tag(pb,s);
1728
        }
1729
    }
1730

    
1731
    mov->tracks = av_mallocz(s->nb_streams*sizeof(*mov->tracks));
1732
    if (!mov->tracks)
1733
        return AVERROR(ENOMEM);
1734

    
1735
    for(i=0; i<s->nb_streams; i++){
1736
        AVStream *st= s->streams[i];
1737
        MOVTrack *track= &mov->tracks[i];
1738
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
1739

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

    
1790
        av_set_pts_info(st, 64, 1, track->timescale);
1791
    }
1792

    
1793
    mov_write_mdat_tag(pb, mov);
1794
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1795
    mov->nb_streams = s->nb_streams;
1796

    
1797
    put_flush_packet(pb);
1798

    
1799
    return 0;
1800
 error:
1801
    av_freep(&mov->tracks);
1802
    return -1;
1803
}
1804

    
1805
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1806
{
1807
    MOVMuxContext *mov = s->priv_data;
1808
    ByteIOContext *pb = s->pb;
1809
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1810
    AVCodecContext *enc = trk->enc;
1811
    unsigned int samplesInChunk = 0;
1812
    int size= pkt->size;
1813

    
1814
    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1815
    if (!size) return 0; /* Discard 0 sized packets */
1816

    
1817
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1818
        /* We must find out how many AMR blocks there are in one packet */
1819
        static uint16_t packed_size[16] =
1820
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1821
        int len = 0;
1822

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

    
1836
    /* copy extradata if it exists */
1837
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1838
        trk->vosLen = enc->extradata_size;
1839
        trk->vosData = av_malloc(trk->vosLen);
1840
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1841
    }
1842

    
1843
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1844
        /* from x264 or from bytestream h264 */
1845
        /* nal reformating needed */
1846
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1847
    } else {
1848
        put_buffer(pb, pkt->data, size);
1849
    }
1850

    
1851
    if ((enc->codec_id == CODEC_ID_DNXHD ||
1852
         enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
1853
        /* copy frame to create needed atoms */
1854
        trk->vosLen = size;
1855
        trk->vosData = av_malloc(size);
1856
        if (!trk->vosData)
1857
            return AVERROR(ENOMEM);
1858
        memcpy(trk->vosData, pkt->data, size);
1859
    }
1860

    
1861
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1862
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1863
        if (!trk->cluster)
1864
            return -1;
1865
    }
1866

    
1867
    trk->cluster[trk->entry].pos = url_ftell(pb) - size;
1868
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1869
    trk->cluster[trk->entry].size = size;
1870
    trk->cluster[trk->entry].entries = samplesInChunk;
1871
    trk->cluster[trk->entry].dts = pkt->dts;
1872
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1873

    
1874
    if (pkt->pts == AV_NOPTS_VALUE) {
1875
        av_log(s, AV_LOG_WARNING, "pts has no value\n");
1876
        pkt->pts = pkt->dts;
1877
    }
1878
    if (pkt->dts != pkt->pts)
1879
        trk->hasBframes = 1;
1880
    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1881
    if (pkt->flags & PKT_FLAG_KEY) {
1882
        trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
1883
        trk->hasKeyframes++;
1884
    }
1885
    trk->entry++;
1886
    trk->sampleCount += samplesInChunk;
1887
    mov->mdat_size += size;
1888

    
1889
    put_flush_packet(pb);
1890
    return 0;
1891
}
1892

    
1893
static int mov_write_trailer(AVFormatContext *s)
1894
{
1895
    MOVMuxContext *mov = s->priv_data;
1896
    ByteIOContext *pb = s->pb;
1897
    int res = 0;
1898
    int i;
1899

    
1900
    int64_t moov_pos = url_ftell(pb);
1901

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

    
1915
    mov_write_moov_tag(pb, mov, s);
1916

    
1917
    for (i=0; i<mov->nb_streams; i++) {
1918
        av_freep(&mov->tracks[i].cluster);
1919

    
1920
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
1921

    
1922
    }
1923

    
1924
    put_flush_packet(pb);
1925

    
1926
    av_freep(&mov->tracks);
1927

    
1928
    return res;
1929
}
1930

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