Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 80357cfc

History | View | Annotate | Download (63.2 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
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22
#include "avformat.h"
23
#include "riff.h"
24
#include "avio.h"
25
#include "isom.h"
26
#include "avc.h"
27
#include "libavcodec/bitstream.h"
28

    
29
#undef NDEBUG
30
#include <assert.h>
31

    
32
#define MOV_INDEX_CLUSTER_SIZE 16384
33
#define globalTimescale 1000
34

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

    
43
typedef struct MOVIentry {
44
    unsigned int flags, size;
45
    uint64_t     pos;
46
    unsigned int samplesInChunk;
47
    char         key_frame;
48
    unsigned int entries;
49
    int64_t      cts;
50
    int64_t      dts;
51
} MOVIentry;
52

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

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

    
75
typedef struct MOVMuxContext {
76
    int     mode;
77
    int64_t time;
78
    int     nb_streams;
79
    int64_t mdat_pos;
80
    uint64_t mdat_size;
81
    long    timescale;
82
    MOVTrack tracks[MAX_STREAMS];
83
} MOVMuxContext;
84

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

    
93
    return curpos - pos;
94
}
95

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

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

    
125
    int64_t pos = url_ftell(pb);
126
    put_be32(pb, 0); /* size */
127
    put_tag(pb, "stsz");
128
    put_be32(pb, 0); /* version & flags */
129

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

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

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

    
183
    return updateSize(pb, pos);
184
}
185

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

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

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

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

    
231
    if (track->vosLen < 7)
232
        return -1;
233

    
234
    put_be32(pb, 11);
235
    put_tag(pb, "dac3");
236

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

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

    
262
    flush_put_bits(&pbc);
263
    put_buffer(pb, buf, sizeof(buf));
264

    
265
    return 11;
266
}
267

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

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

    
286
static unsigned int descrLength(unsigned int len)
287
{
288
    int i;
289
    for(i=1; len>>(7*i); i++);
290
    return len + 1 + i;
291
}
292

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

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

    
307
    put_be32(pb, 0); // size
308
    put_tag(pb, "esds");
309
    put_be32(pb, 0); // Version
310

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

    
317
    // DecoderConfig descriptor
318
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
319

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

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

    
335
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));    // Buffersize DB (24 bits)
336
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
337

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

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

    
350
    // SL descriptor
351
    putDescr(pb, 0x06, 1);
352
    put_byte(pb, 0x02);
353
    return updateSize(pb, pos);
354
}
355

    
356
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack *track)
357
{
358
    int64_t pos = url_ftell(pb);
359

    
360
    put_be32(pb, 0);     /* size */
361
    put_tag(pb, "wave");
362

    
363
    put_be32(pb, 12);    /* size */
364
    put_tag(pb, "frma");
365
    put_le32(pb, track->tag);
366

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

    
384
    put_be32(pb, 8);     /* size */
385
    put_be32(pb, 0);     /* null tag */
386

    
387
    return updateSize(pb, pos);
388
}
389

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

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

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

    
412
    /* SoundDescription */
413
    put_be16(pb, version); /* Version */
414
    put_be16(pb, 0); /* Revision level */
415
    put_be32(pb, 0); /* Reserved */
416

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

    
431
    put_be16(pb, 0); /* packet size (= 0) */
432
    put_be16(pb, track->timescale); /* Time scale */
433
    put_be16(pb, 0); /* Reserved */
434

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

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

    
461
    return updateSize(pb, pos);
462
}
463

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

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

    
489
static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
490
{
491
    int64_t pos = url_ftell(pb);
492

    
493
    put_be32(pb, 0);
494
    put_tag(pb, "avcC");
495
    ff_isom_write_avcc(pb, track->vosData, track->vosLen);
496
    return updateSize(pb, pos);
497
}
498

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

    
510
    put_be32(pb, 24); /* size */
511
    put_tag(pb, "APRG");
512
    put_tag(pb, "APRG");
513
    put_tag(pb, "0001");
514
    put_be32(pb, 1); /* unknown */
515
    put_be32(pb, 0); /* unknown */
516

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

    
542
    /* extra padding for stsd needed */
543
    put_be32(pb, 0);
544
    return 0;
545
}
546

    
547
static const AVCodecTag codec_3gp_tags[] = {
548
    { CODEC_ID_H263,   MKTAG('s','2','6','3') },
549
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
550
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
551
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
552
    { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
553
    { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
554
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
555
    { CODEC_ID_NONE, 0 },
556
};
557

    
558
static const AVCodecTag mov_pix_fmt_tags[] = {
559
    { PIX_FMT_YUYV422, MKTAG('y','u','v','s') },
560
    { PIX_FMT_UYVY422, MKTAG('2','v','u','y') },
561
    { PIX_FMT_BGR555,  MKTAG('r','a','w',' ') },
562
    { PIX_FMT_RGB24,   MKTAG('r','a','w',' ') },
563
    { PIX_FMT_BGR32_1, MKTAG('r','a','w',' ') },
564
};
565

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

    
576
static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
577
{
578
    int tag = track->enc->codec_tag;
579
    if (track->mode == MODE_MP4 || track->mode == MODE_PSP) {
580
        if (!codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
581
            return 0;
582
        if      (track->enc->codec_id == CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
583
        else if (track->enc->codec_id == CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
584
        else if (track->enc->codec_id == CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
585
        else if (track->enc->codec_id == CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
586
        else if (track->enc->codec_type == CODEC_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
587
        else if (track->enc->codec_type == CODEC_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
588
    } else if (track->mode == MODE_IPOD) {
589
        tag = codec_get_tag(codec_ipod_tags, track->enc->codec_id);
590
        if (!match_ext(s->filename, "m4a") && !match_ext(s->filename, "m4v"))
591
            av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
592
                   "Quicktime/Ipod might not play the file\n");
593
    } else if (track->mode & MODE_3GP) {
594
        tag = codec_get_tag(codec_3gp_tags, track->enc->codec_id);
595
    } else if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
596
                        (tag == MKTAG('d','v','c','p') ||
597
                         track->enc->codec_id == CODEC_ID_RAWVIDEO))) {
598
        if (track->enc->codec_id == CODEC_ID_DVVIDEO) {
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
        } else if (track->enc->codec_id == CODEC_ID_RAWVIDEO) {
606
            tag = codec_get_tag(mov_pix_fmt_tags, track->enc->pix_fmt);
607
            if (!tag) // restore tag
608
                tag = track->enc->codec_tag;
609
        } else {
610
            if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
611
                tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
612
                if (!tag) { // if no mac fcc found, try with Microsoft tags
613
                    tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
614
                    if (tag)
615
                        av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, "
616
                               "the file may be unplayable!\n");
617
                }
618
            } else if (track->enc->codec_type == CODEC_TYPE_AUDIO) {
619
                tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
620
                if (!tag) { // if no mac fcc found, try with Microsoft tags
621
                    int ms_tag = codec_get_tag(codec_wav_tags, track->enc->codec_id);
622
                    if (ms_tag) {
623
                        tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
624
                        av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, "
625
                               "the file may be unplayable!\n");
626
                    }
627
                }
628
            } else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
629
                tag = codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
630
            }
631
        }
632
    }
633
    return tag;
634
}
635

    
636
/** Write uuid atom.
637
 * Needed to make file play in iPods running newest firmware
638
 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
639
 */
640
static int mov_write_uuid_tag_ipod(ByteIOContext *pb)
641
{
642
    put_be32(pb, 28);
643
    put_tag(pb, "uuid");
644
    put_be32(pb, 0x6b6840f2);
645
    put_be32(pb, 0x5f244fc5);
646
    put_be32(pb, 0xba39a51b);
647
    put_be32(pb, 0xcf0323f3);
648
    put_be32(pb, 0x0);
649
    return 28;
650
}
651

    
652
static int mov_write_subtitle_tag(ByteIOContext *pb, MOVTrack *track)
653
{
654
    int64_t pos = url_ftell(pb);
655
    put_be32(pb, 0);    /* size */
656
    put_le32(pb, track->tag); // store it byteswapped
657
    put_be32(pb, 0);    /* Reserved */
658
    put_be16(pb, 0);    /* Reserved */
659
    put_be16(pb, 1);    /* Data-reference index */
660

    
661
    if (track->enc->extradata_size)
662
        put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
663

    
664
    return updateSize(pb, pos);
665
}
666

    
667
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack *track)
668
{
669
    int64_t pos = url_ftell(pb);
670
    char compressor_name[32];
671

    
672
    put_be32(pb, 0); /* size */
673
    put_le32(pb, track->tag); // store it byteswapped
674
    put_be32(pb, 0); /* Reserved */
675
    put_be16(pb, 0); /* Reserved */
676
    put_be16(pb, 1); /* Data-reference index */
677

    
678
    put_be16(pb, 0); /* Codec stream version */
679
    put_be16(pb, 0); /* Codec stream revision (=0) */
680
    if (track->mode == MODE_MOV) {
681
        put_tag(pb, "FFMP"); /* Vendor */
682
        if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
683
            put_be32(pb, 0); /* Temporal Quality */
684
            put_be32(pb, 0x400); /* Spatial Quality = lossless*/
685
        } else {
686
            put_be32(pb, 0x200); /* Temporal Quality = normal */
687
            put_be32(pb, 0x200); /* Spatial Quality = normal */
688
        }
689
    } else {
690
        put_be32(pb, 0); /* Reserved */
691
        put_be32(pb, 0); /* Reserved */
692
        put_be32(pb, 0); /* Reserved */
693
    }
694
    put_be16(pb, track->enc->width); /* Video width */
695
    put_be16(pb, track->height); /* Video height */
696
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
697
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
698
    put_be32(pb, 0); /* Data size (= 0) */
699
    put_be16(pb, 1); /* Frame count (= 1) */
700

    
701
    memset(compressor_name,0,32);
702
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
703
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
704
        strncpy(compressor_name,track->enc->codec->name,31);
705
    put_byte(pb, strlen(compressor_name));
706
    put_buffer(pb, compressor_name, 31);
707

    
708
    if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
709
        put_be16(pb, track->enc->bits_per_coded_sample);
710
    else
711
        put_be16(pb, 0x18); /* Reserved */
712
    put_be16(pb, 0xffff); /* Reserved */
713
    if(track->tag == MKTAG('m','p','4','v'))
714
        mov_write_esds_tag(pb, track);
715
    else if(track->enc->codec_id == CODEC_ID_H263)
716
        mov_write_d263_tag(pb);
717
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
718
        mov_write_svq3_tag(pb);
719
    else if(track->enc->codec_id == CODEC_ID_DNXHD)
720
        mov_write_avid_tag(pb, track);
721
    else if(track->enc->codec_id == CODEC_ID_H264) {
722
        mov_write_avcc_tag(pb, track);
723
        if(track->mode == MODE_IPOD)
724
            mov_write_uuid_tag_ipod(pb);
725
    } else if(track->vosLen > 0)
726
        mov_write_glbl_tag(pb, track);
727

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

    
731
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack *track)
732
{
733
    int64_t pos = url_ftell(pb);
734
    put_be32(pb, 0); /* size */
735
    put_tag(pb, "stsd");
736
    put_be32(pb, 0); /* version & flags */
737
    put_be32(pb, 1); /* entry count */
738
    if (track->enc->codec_type == CODEC_TYPE_VIDEO)
739
        mov_write_video_tag(pb, track);
740
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
741
        mov_write_audio_tag(pb, track);
742
    else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE)
743
        mov_write_subtitle_tag(pb, track);
744
    return updateSize(pb, pos);
745
}
746

    
747
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack *track)
748
{
749
    MOVStts *ctts_entries;
750
    uint32_t entries = 0;
751
    uint32_t atom_size;
752
    int i;
753

    
754
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
755
    ctts_entries[0].count = 1;
756
    ctts_entries[0].duration = track->cluster[0].cts;
757
    for (i=1; i<track->entry; i++) {
758
        if (track->cluster[i].cts == ctts_entries[entries].duration) {
759
            ctts_entries[entries].count++; /* compress */
760
        } else {
761
            entries++;
762
            ctts_entries[entries].duration = track->cluster[i].cts;
763
            ctts_entries[entries].count = 1;
764
        }
765
    }
766
    entries++; /* last one */
767
    atom_size = 16 + (entries * 8);
768
    put_be32(pb, atom_size); /* size */
769
    put_tag(pb, "ctts");
770
    put_be32(pb, 0); /* version & flags */
771
    put_be32(pb, entries); /* entry count */
772
    for (i=0; i<entries; i++) {
773
        put_be32(pb, ctts_entries[i].count);
774
        put_be32(pb, ctts_entries[i].duration);
775
    }
776
    av_free(ctts_entries);
777
    return atom_size;
778
}
779

    
780
/* Time to sample atom */
781
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack *track)
782
{
783
    MOVStts *stts_entries;
784
    uint32_t entries = -1;
785
    uint32_t atom_size;
786
    int i;
787

    
788
    if (track->enc->codec_type == CODEC_TYPE_AUDIO && !track->audio_vbr) {
789
        stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
790
        stts_entries[0].count = track->sampleCount;
791
        stts_entries[0].duration = 1;
792
        entries = 1;
793
    } else {
794
        stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
795
        for (i=0; i<track->entry; i++) {
796
            int64_t duration = i + 1 == track->entry ?
797
                track->trackDuration - track->cluster[i].dts + track->cluster[0].dts : /* readjusting */
798
                track->cluster[i+1].dts - track->cluster[i].dts;
799
            if (i && duration == stts_entries[entries].duration) {
800
                stts_entries[entries].count++; /* compress */
801
            } else {
802
                entries++;
803
                stts_entries[entries].duration = duration;
804
                stts_entries[entries].count = 1;
805
            }
806
        }
807
        entries++; /* last one */
808
    }
809
    atom_size = 16 + (entries * 8);
810
    put_be32(pb, atom_size); /* size */
811
    put_tag(pb, "stts");
812
    put_be32(pb, 0); /* version & flags */
813
    put_be32(pb, entries); /* entry count */
814
    for (i=0; i<entries; i++) {
815
        put_be32(pb, stts_entries[i].count);
816
        put_be32(pb, stts_entries[i].duration);
817
    }
818
    av_free(stts_entries);
819
    return atom_size;
820
}
821

    
822
static int mov_write_dref_tag(ByteIOContext *pb)
823
{
824
    put_be32(pb, 28); /* size */
825
    put_tag(pb, "dref");
826
    put_be32(pb, 0); /* version & flags */
827
    put_be32(pb, 1); /* entry count */
828

    
829
    put_be32(pb, 0xc); /* size */
830
    put_tag(pb, "url ");
831
    put_be32(pb, 1); /* version & flags */
832

    
833
    return 28;
834
}
835

    
836
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack *track)
837
{
838
    int64_t pos = url_ftell(pb);
839
    put_be32(pb, 0); /* size */
840
    put_tag(pb, "stbl");
841
    mov_write_stsd_tag(pb, track);
842
    mov_write_stts_tag(pb, track);
843
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
844
        track->hasKeyframes && track->hasKeyframes < track->entry)
845
        mov_write_stss_tag(pb, track);
846
    if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
847
        track->hasBframes)
848
        mov_write_ctts_tag(pb, track);
849
    mov_write_stsc_tag(pb, track);
850
    mov_write_stsz_tag(pb, track);
851
    mov_write_stco_tag(pb, track);
852
    return updateSize(pb, pos);
853
}
854

    
855
static int mov_write_dinf_tag(ByteIOContext *pb)
856
{
857
    int64_t pos = url_ftell(pb);
858
    put_be32(pb, 0); /* size */
859
    put_tag(pb, "dinf");
860
    mov_write_dref_tag(pb);
861
    return updateSize(pb, pos);
862
}
863

    
864
static int mov_write_nmhd_tag(ByteIOContext *pb)
865
{
866
    put_be32(pb, 12);
867
    put_tag(pb, "nmhd");
868
    put_be32(pb, 0);
869
    return 12;
870
}
871

    
872
static int mov_write_gmhd_tag(ByteIOContext *pb)
873
{
874
    put_be32(pb, 0x20);   /* size */
875
    put_tag(pb, "gmhd");
876
    put_be32(pb, 0x18);   /* gmin size */
877
    put_tag(pb, "gmin");  /* generic media info */
878
    put_be32(pb, 0);      /* version & flags */
879
    put_be16(pb, 0x40);   /* graphics mode = */
880
    put_be16(pb, 0x8000); /* opColor (r?) */
881
    put_be16(pb, 0x8000); /* opColor (g?) */
882
    put_be16(pb, 0x8000); /* opColor (b?) */
883
    put_be16(pb, 0);      /* balance */
884
    put_be16(pb, 0);      /* reserved */
885
    return 0x20;
886
}
887

    
888
static int mov_write_smhd_tag(ByteIOContext *pb)
889
{
890
    put_be32(pb, 16); /* size */
891
    put_tag(pb, "smhd");
892
    put_be32(pb, 0); /* version & flags */
893
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
894
    put_be16(pb, 0); /* reserved */
895
    return 16;
896
}
897

    
898
static int mov_write_vmhd_tag(ByteIOContext *pb)
899
{
900
    put_be32(pb, 0x14); /* size (always 0x14) */
901
    put_tag(pb, "vmhd");
902
    put_be32(pb, 0x01); /* version & flags */
903
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
904
    return 0x14;
905
}
906

    
907
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)
908
{
909
    const char *hdlr, *descr = NULL, *hdlr_type = NULL;
910
    int64_t pos = url_ftell(pb);
911

    
912
    if (!track) { /* no media --> data handler */
913
        hdlr = "dhlr";
914
        hdlr_type = "url ";
915
        descr = "DataHandler";
916
    } else {
917
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
918
        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
919
            hdlr_type = "vide";
920
            descr = "VideoHandler";
921
        } else if (track->enc->codec_type == CODEC_TYPE_AUDIO) {
922
            hdlr_type = "soun";
923
            descr = "SoundHandler";
924
        } else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
925
            if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
926
            else                                      hdlr_type = "text";
927
            descr = "SubtitleHandler";
928
        }
929
    }
930

    
931
    put_be32(pb, 0); /* size */
932
    put_tag(pb, "hdlr");
933
    put_be32(pb, 0); /* Version & flags */
934
    put_buffer(pb, hdlr, 4); /* handler */
935
    put_tag(pb, hdlr_type); /* handler type */
936
    put_be32(pb ,0); /* reserved */
937
    put_be32(pb ,0); /* reserved */
938
    put_be32(pb ,0); /* reserved */
939
    put_byte(pb, strlen(descr)); /* string counter */
940
    put_buffer(pb, descr, strlen(descr)); /* handler description */
941
    return updateSize(pb, pos);
942
}
943

    
944
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack *track)
945
{
946
    int64_t pos = url_ftell(pb);
947
    put_be32(pb, 0); /* size */
948
    put_tag(pb, "minf");
949
    if(track->enc->codec_type == CODEC_TYPE_VIDEO)
950
        mov_write_vmhd_tag(pb);
951
    else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
952
        mov_write_smhd_tag(pb);
953
    else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
954
        if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb);
955
        else                                      mov_write_nmhd_tag(pb);
956
    }
957
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
958
        mov_write_hdlr_tag(pb, NULL);
959
    mov_write_dinf_tag(pb);
960
    mov_write_stbl_tag(pb, track);
961
    return updateSize(pb, pos);
962
}
963

    
964
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack *track)
965
{
966
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
967

    
968
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
969
    put_tag(pb, "mdhd");
970
    put_byte(pb, version);
971
    put_be24(pb, 0); /* flags */
972
    if (version == 1) {
973
        put_be64(pb, track->time);
974
        put_be64(pb, track->time);
975
    } else {
976
        put_be32(pb, track->time); /* creation time */
977
        put_be32(pb, track->time); /* modification time */
978
    }
979
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
980
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
981
    put_be16(pb, track->language); /* language */
982
    put_be16(pb, 0); /* reserved (quality) */
983

    
984
    if(version!=0 && track->mode == MODE_MOV){
985
        av_log(NULL, AV_LOG_ERROR,
986
            "FATAL error, file duration too long for timebase, this file will not be\n"
987
            "playable with quicktime. Choose a different timebase or a different\n"
988
            "container format\n");
989
    }
990

    
991
    return 32;
992
}
993

    
994
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack *track)
995
{
996
    int64_t pos = url_ftell(pb);
997
    put_be32(pb, 0); /* size */
998
    put_tag(pb, "mdia");
999
    mov_write_mdhd_tag(pb, track);
1000
    mov_write_hdlr_tag(pb, track);
1001
    mov_write_minf_tag(pb, track);
1002
    return updateSize(pb, pos);
1003
}
1004

    
1005
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1006
{
1007
    int64_t duration = av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP);
1008
    int version = duration < INT32_MAX ? 0 : 1;
1009

    
1010
    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
1011
    put_tag(pb, "tkhd");
1012
    put_byte(pb, version);
1013
    put_be24(pb, 0xf); /* flags (track enabled) */
1014
    if (version == 1) {
1015
        put_be64(pb, track->time);
1016
        put_be64(pb, track->time);
1017
    } else {
1018
        put_be32(pb, track->time); /* creation time */
1019
        put_be32(pb, track->time); /* modification time */
1020
    }
1021
    put_be32(pb, track->trackID); /* track-id */
1022
    put_be32(pb, 0); /* reserved */
1023
    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
1024

    
1025
    put_be32(pb, 0); /* reserved */
1026
    put_be32(pb, 0); /* reserved */
1027
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
1028
    /* Volume, only for audio */
1029
    if(track->enc->codec_type == CODEC_TYPE_AUDIO)
1030
        put_be16(pb, 0x0100);
1031
    else
1032
        put_be16(pb, 0);
1033
    put_be16(pb, 0); /* reserved */
1034

    
1035
    /* Matrix structure */
1036
    put_be32(pb, 0x00010000); /* reserved */
1037
    put_be32(pb, 0x0); /* reserved */
1038
    put_be32(pb, 0x0); /* reserved */
1039
    put_be32(pb, 0x0); /* reserved */
1040
    put_be32(pb, 0x00010000); /* reserved */
1041
    put_be32(pb, 0x0); /* reserved */
1042
    put_be32(pb, 0x0); /* reserved */
1043
    put_be32(pb, 0x0); /* reserved */
1044
    put_be32(pb, 0x40000000); /* reserved */
1045

    
1046
    /* Track width and height, for visual only */
1047
    if(track->enc->codec_type == CODEC_TYPE_VIDEO ||
1048
       track->enc->codec_type == CODEC_TYPE_SUBTITLE) {
1049
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1050
        if(!sample_aspect_ratio || track->height != track->enc->height)
1051
            sample_aspect_ratio = 1;
1052
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1053
        put_be32(pb, track->height*0x10000);
1054
    }
1055
    else {
1056
        put_be32(pb, 0);
1057
        put_be32(pb, 0);
1058
    }
1059
    return 0x5c;
1060
}
1061

    
1062
// This box seems important for the psp playback ... without it the movie seems to hang
1063
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
1064
{
1065
    put_be32(pb, 0x24); /* size  */
1066
    put_tag(pb, "edts");
1067
    put_be32(pb, 0x1c); /* size  */
1068
    put_tag(pb, "elst");
1069
    put_be32(pb, 0x0);
1070
    put_be32(pb, 0x1);
1071

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

    
1074
    put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
1075
    put_be32(pb, 0x00010000);
1076
    return 0x24;
1077
}
1078

    
1079
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1080
static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
1081
{
1082
    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1083
    put_tag(pb, "uuid");
1084
    put_tag(pb, "USMT");
1085
    put_be32(pb, 0x21d24fce);
1086
    put_be32(pb, 0xbb88695c);
1087
    put_be32(pb, 0xfac9c740);
1088
    put_be32(pb, 0x1c);     // another size here!
1089
    put_tag(pb, "MTDT");
1090
    put_be32(pb, 0x00010012);
1091
    put_be32(pb, 0x0a);
1092
    put_be32(pb, 0x55c40000);
1093
    put_be32(pb, 0x1);
1094
    put_be32(pb, 0x0);
1095
    return 0x34;
1096
}
1097

    
1098
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1099
{
1100
    int64_t pos = url_ftell(pb);
1101
    put_be32(pb, 0); /* size */
1102
    put_tag(pb, "trak");
1103
    mov_write_tkhd_tag(pb, track, st);
1104
    if (track->mode == MODE_PSP || track->hasBframes)
1105
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1106
    mov_write_mdia_tag(pb, track);
1107
    if (track->mode == MODE_PSP)
1108
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1109
    return updateSize(pb, pos);
1110
}
1111

    
1112
#if 0
1113
/* TODO: Not sorted out, but not necessary either */
1114
static int mov_write_iods_tag(ByteIOContext *pb, MOVMuxContext *mov)
1115
{
1116
    put_be32(pb, 0x15); /* size */
1117
    put_tag(pb, "iods");
1118
    put_be32(pb, 0);    /* version & flags */
1119
    put_be16(pb, 0x1007);
1120
    put_byte(pb, 0);
1121
    put_be16(pb, 0x4fff);
1122
    put_be16(pb, 0xfffe);
1123
    put_be16(pb, 0x01ff);
1124
    return 0x15;
1125
}
1126
#endif
1127

    
1128
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVMuxContext *mov)
1129
{
1130
    int maxTrackID = 1, i;
1131
    int64_t maxTrackLenTemp, maxTrackLen = 0;
1132
    int version;
1133

    
1134
    for (i=0; i<mov->nb_streams; i++) {
1135
        if(mov->tracks[i].entry > 0) {
1136
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
1137
            if(maxTrackLen < maxTrackLenTemp)
1138
                maxTrackLen = maxTrackLenTemp;
1139
            if(maxTrackID < mov->tracks[i].trackID)
1140
                maxTrackID = mov->tracks[i].trackID;
1141
        }
1142
    }
1143

    
1144
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1145
    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1146
    put_tag(pb, "mvhd");
1147
    put_byte(pb, version);
1148
    put_be24(pb, 0); /* flags */
1149
    if (version == 1) {
1150
        put_be64(pb, mov->time);
1151
        put_be64(pb, mov->time);
1152
    } else {
1153
        put_be32(pb, mov->time); /* creation time */
1154
        put_be32(pb, mov->time); /* modification time */
1155
    }
1156
    put_be32(pb, mov->timescale); /* timescale */
1157
    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1158

    
1159
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1160
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1161
    put_be16(pb, 0); /* reserved */
1162
    put_be32(pb, 0); /* reserved */
1163
    put_be32(pb, 0); /* reserved */
1164

    
1165
    /* Matrix structure */
1166
    put_be32(pb, 0x00010000); /* reserved */
1167
    put_be32(pb, 0x0); /* reserved */
1168
    put_be32(pb, 0x0); /* reserved */
1169
    put_be32(pb, 0x0); /* reserved */
1170
    put_be32(pb, 0x00010000); /* reserved */
1171
    put_be32(pb, 0x0); /* reserved */
1172
    put_be32(pb, 0x0); /* reserved */
1173
    put_be32(pb, 0x0); /* reserved */
1174
    put_be32(pb, 0x40000000); /* reserved */
1175

    
1176
    put_be32(pb, 0); /* reserved (preview time) */
1177
    put_be32(pb, 0); /* reserved (preview duration) */
1178
    put_be32(pb, 0); /* reserved (poster time) */
1179
    put_be32(pb, 0); /* reserved (selection time) */
1180
    put_be32(pb, 0); /* reserved (selection duration) */
1181
    put_be32(pb, 0); /* reserved (current time) */
1182
    put_be32(pb, maxTrackID+1); /* Next track id */
1183
    return 0x6c;
1184
}
1185

    
1186
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVMuxContext *mov,
1187
                                     AVFormatContext *s)
1188
{
1189
    int64_t pos = url_ftell(pb);
1190
    put_be32(pb, 0); /* size */
1191
    put_tag(pb, "hdlr");
1192
    put_be32(pb, 0);
1193
    put_be32(pb, 0);
1194
    put_tag(pb, "mdir");
1195
    put_tag(pb, "appl");
1196
    put_be32(pb, 0);
1197
    put_be32(pb, 0);
1198
    put_be16(pb, 0);
1199
    return updateSize(pb, pos);
1200
}
1201

    
1202
/* helper function to write a data tag with the specified string as data */
1203
static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int lang, int long_style)
1204
{
1205
    if(long_style){
1206
        int64_t pos = url_ftell(pb);
1207
        put_be32(pb, 0); /* size */
1208
        put_tag(pb, "data");
1209
        put_be32(pb, 1);
1210
        put_be32(pb, 0);
1211
        put_buffer(pb, data, strlen(data));
1212
        return updateSize(pb, pos);
1213
    }else{
1214
        put_be16(pb, strlen(data)); /* string length */
1215
        put_be16(pb, lang);
1216
        put_buffer(pb, data, strlen(data));
1217
        return strlen(data) + 4;
1218
    }
1219
}
1220

    
1221
static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int lang, int long_style){
1222
    int size = 0;
1223
    if (value && value[0]) {
1224
        int64_t pos = url_ftell(pb);
1225
        put_be32(pb, 0); /* size */
1226
        put_tag(pb, name);
1227
        mov_write_string_data_tag(pb, value, lang, long_style);
1228
        size= updateSize(pb, pos);
1229
    }
1230
    return size;
1231
}
1232

    
1233
static int mov_write_string_metadata(AVFormatContext *s, ByteIOContext *pb,
1234
                                     const char *name, const char *tag,
1235
                                     int long_style)
1236
{
1237
    int l, lang = 0, len, len2;
1238
    AVMetadataTag *t, *t2 = NULL;
1239
    char tag2[16];
1240

    
1241
    if (!(t = av_metadata_get(s->metadata, tag, NULL, 0)))
1242
        return 0;
1243

    
1244
    len = strlen(t->key);
1245
    snprintf(tag2, sizeof(tag2), "%s-", tag);
1246
    while ((t2 = av_metadata_get(s->metadata, tag2, t2, AV_METADATA_IGNORE_SUFFIX))) {
1247
        len2 = strlen(t2->key);
1248
        if (len2 == len+4 && !strcmp(t->value, t2->value)
1249
            && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 0)) >= 0) {
1250
            lang = l;
1251
            break;
1252
        }
1253
    }
1254
    return mov_write_string_tag(pb, name, t->value, lang, long_style);
1255
}
1256

    
1257
/* iTunes track number */
1258
static int mov_write_trkn_tag(ByteIOContext *pb, MOVMuxContext *mov,
1259
                              AVFormatContext *s)
1260
{
1261
    AVMetadataTag *t = av_metadata_get(s->metadata, "track", NULL, 0);
1262
    int size = 0, track = t ? atoi(t->value) : 0;
1263
    if (track) {
1264
        int64_t pos = url_ftell(pb);
1265
        put_be32(pb, 0); /* size */
1266
        put_tag(pb, "trkn");
1267
        {
1268
            int64_t pos = url_ftell(pb);
1269
            put_be32(pb, 0); /* size */
1270
            put_tag(pb, "data");
1271
            put_be32(pb, 0);        // 8 bytes empty
1272
            put_be32(pb, 0);
1273
            put_be16(pb, 0);        // empty
1274
            put_be16(pb, track);    // track number
1275
            put_be16(pb, 0);        // total track number
1276
            put_be16(pb, 0);        // empty
1277
            updateSize(pb, pos);
1278
        }
1279
        size = updateSize(pb, pos);
1280
    }
1281
    return size;
1282
}
1283

    
1284
/* iTunes meta data list */
1285
static int mov_write_ilst_tag(ByteIOContext *pb, MOVMuxContext *mov,
1286
                              AVFormatContext *s)
1287
{
1288
    int64_t pos = url_ftell(pb);
1289
    put_be32(pb, 0); /* size */
1290
    put_tag(pb, "ilst");
1291
    mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1292
    mov_write_string_metadata(s, pb, "\251ART", "author"   , 1);
1293
    mov_write_string_metadata(s, pb, "\251wrt", "author"   , 1);
1294
    mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1295
    mov_write_string_metadata(s, pb, "\251day", "year"     , 1);
1296
    mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1297
    mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1298
    mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1299
    mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1300
    mov_write_trkn_tag(pb, mov, s);
1301
    return updateSize(pb, pos);
1302
}
1303

    
1304
/* iTunes meta data tag */
1305
static int mov_write_meta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1306
                              AVFormatContext *s)
1307
{
1308
    int size = 0;
1309
    int64_t pos = url_ftell(pb);
1310
    put_be32(pb, 0); /* size */
1311
    put_tag(pb, "meta");
1312
    put_be32(pb, 0);
1313
    mov_write_itunes_hdlr_tag(pb, mov, s);
1314
    mov_write_ilst_tag(pb, mov, s);
1315
    size = updateSize(pb, pos);
1316
    return size;
1317
}
1318

    
1319
static int utf8len(const uint8_t *b)
1320
{
1321
    int len=0;
1322
    int val;
1323
    while(*b){
1324
        GET_UTF8(val, *b++, return -1;)
1325
        len++;
1326
    }
1327
    return len;
1328
}
1329

    
1330
static int ascii_to_wc(ByteIOContext *pb, const uint8_t *b)
1331
{
1332
    int val;
1333
    while(*b){
1334
        GET_UTF8(val, *b++, return -1;)
1335
        put_be16(pb, val);
1336
    }
1337
    put_be16(pb, 0x00);
1338
    return 0;
1339
}
1340

    
1341
static uint16_t language_code(const char *str)
1342
{
1343
    return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1344
}
1345

    
1346
static int mov_write_3gp_udta_tag(ByteIOContext *pb, AVFormatContext *s,
1347
                                  const char *tag, const char *str)
1348
{
1349
    int64_t pos = url_ftell(pb);
1350
    AVMetadataTag *t = av_metadata_get(s->metadata, str, NULL, 0);
1351
    if (!t || !utf8len(t->value))
1352
        return 0;
1353
    put_be32(pb, 0);   /* size */
1354
    put_tag (pb, tag); /* type */
1355
    put_be32(pb, 0);   /* version + flags */
1356
    if (!strcmp(tag, "yrrc"))
1357
        put_be16(pb, atoi(t->value));
1358
    else {
1359
        put_be16(pb, language_code("eng")); /* language */
1360
        ascii_to_wc(pb, t->value);
1361
        if (!strcmp(tag, "albm") &&
1362
            (t = av_metadata_get(s->metadata, "year", NULL, 0)))
1363
            put_byte(pb, atoi(t->value));
1364
    }
1365
    return updateSize(pb, pos);
1366
}
1367

    
1368
static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1369
                              AVFormatContext *s)
1370
{
1371
    ByteIOContext *pb_buf;
1372
    int i, ret, size;
1373
    uint8_t *buf;
1374

    
1375
    for (i = 0; i < s->nb_streams; i++)
1376
        if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1377
            return 0;
1378
        }
1379

    
1380
    ret = url_open_dyn_buf(&pb_buf);
1381
    if(ret < 0)
1382
        return ret;
1383

    
1384
        if (mov->mode & MODE_3GP) {
1385
            mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1386
            mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1387
            mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1388
            mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1389
            mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1390
            mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1391
            mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "year");
1392
        } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1393
            mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
1394
            mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
1395
            mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
1396
            mov_write_string_metadata(s, pb_buf, "\251day", "year"       , 0);
1397
            mov_write_string_tag(pb_buf, "\251enc", LIBAVFORMAT_IDENT, 0, 0);
1398
            mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
1399
            mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
1400
            mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
1401
        } else {
1402
            /* iTunes meta data */
1403
            mov_write_meta_tag(pb_buf, mov, s);
1404
        }
1405

    
1406
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1407
        put_be32(pb, size+8);
1408
        put_tag(pb, "udta");
1409
        put_buffer(pb, buf, size);
1410
        av_free(buf);
1411
    }
1412

    
1413
    return 0;
1414
}
1415

    
1416
static void mov_write_psp_udta_tag(ByteIOContext *pb,
1417
                                  const char *str, const char *lang, int type)
1418
{
1419
    int len = utf8len(str)+1;
1420
    if(len<=0)
1421
        return;
1422
    put_be16(pb, len*2+10);            /* size */
1423
    put_be32(pb, type);                /* type */
1424
    put_be16(pb, language_code(lang)); /* language */
1425
    put_be16(pb, 0x01);                /* ? */
1426
    ascii_to_wc(pb, str);
1427
}
1428

    
1429
static int mov_write_uuidusmt_tag(ByteIOContext *pb, AVFormatContext *s)
1430
{
1431
    AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
1432
    int64_t pos, pos2;
1433

    
1434
    if (title) {
1435
        pos = url_ftell(pb);
1436
        put_be32(pb, 0); /* size placeholder*/
1437
        put_tag(pb, "uuid");
1438
        put_tag(pb, "USMT");
1439
        put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1440
        put_be32(pb, 0xbb88695c);
1441
        put_be32(pb, 0xfac9c740);
1442

    
1443
        pos2 = url_ftell(pb);
1444
        put_be32(pb, 0); /* size placeholder*/
1445
        put_tag(pb, "MTDT");
1446
        put_be16(pb, 4);
1447

    
1448
        // ?
1449
        put_be16(pb, 0x0C);                 /* size */
1450
        put_be32(pb, 0x0B);                 /* type */
1451
        put_be16(pb, language_code("und")); /* language */
1452
        put_be16(pb, 0x0);                  /* ? */
1453
        put_be16(pb, 0x021C);               /* data */
1454

    
1455
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1456
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1457
//        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);
1458
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1459

    
1460
        updateSize(pb, pos2);
1461
        return updateSize(pb, pos);
1462
    }
1463

    
1464
    return 0;
1465
}
1466

    
1467
static int mov_write_moov_tag(ByteIOContext *pb, MOVMuxContext *mov,
1468
                              AVFormatContext *s)
1469
{
1470
    int i;
1471
    int64_t pos = url_ftell(pb);
1472
    put_be32(pb, 0); /* size placeholder*/
1473
    put_tag(pb, "moov");
1474
    mov->timescale = globalTimescale;
1475

    
1476
    for (i=0; i<mov->nb_streams; i++) {
1477
        if(mov->tracks[i].entry <= 0) continue;
1478

    
1479
        mov->tracks[i].time = mov->time;
1480
        mov->tracks[i].trackID = i+1;
1481
    }
1482

    
1483
    mov_write_mvhd_tag(pb, mov);
1484
    //mov_write_iods_tag(pb, mov);
1485
    for (i=0; i<mov->nb_streams; i++) {
1486
        if(mov->tracks[i].entry > 0) {
1487
            mov_write_trak_tag(pb, &(mov->tracks[i]), s->streams[i]);
1488
        }
1489
    }
1490

    
1491
    if (mov->mode == MODE_PSP)
1492
        mov_write_uuidusmt_tag(pb, s);
1493
    else
1494
        mov_write_udta_tag(pb, mov, s);
1495

    
1496
    return updateSize(pb, pos);
1497
}
1498

    
1499
static int mov_write_mdat_tag(ByteIOContext *pb, MOVMuxContext *mov)
1500
{
1501
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1502
    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1503

    
1504
    mov->mdat_pos = url_ftell(pb);
1505
    put_be32(pb, 0); /* size placeholder*/
1506
    put_tag(pb, "mdat");
1507
    return 0;
1508
}
1509

    
1510
/* TODO: This needs to be more general */
1511
static int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
1512
{
1513
    MOVMuxContext *mov = s->priv_data;
1514
    int64_t pos = url_ftell(pb);
1515
    int has_h264 = 0, has_video = 0;
1516
    int minor = 0x200;
1517
    int i;
1518

    
1519
    for (i = 0; i < s->nb_streams; i++) {
1520
        AVStream *st = s->streams[i];
1521
        if (st->codec->codec_type == CODEC_TYPE_VIDEO)
1522
            has_video = 1;
1523
        if (st->codec->codec_id == CODEC_ID_H264)
1524
            has_h264 = 1;
1525
    }
1526

    
1527
    put_be32(pb, 0); /* size */
1528
    put_tag(pb, "ftyp");
1529

    
1530
    if (mov->mode == MODE_3GP) {
1531
        put_tag(pb, has_h264 ? "3gp6"  : "3gp4");
1532
        minor =     has_h264 ?   0x100 :   0x200;
1533
    } else if (mov->mode & MODE_3G2) {
1534
        put_tag(pb, has_h264 ? "3g2b"  : "3g2a");
1535
        minor =     has_h264 ? 0x20000 : 0x10000;
1536
    }else if (mov->mode == MODE_PSP)
1537
        put_tag(pb, "MSNV");
1538
    else if (mov->mode == MODE_MP4)
1539
        put_tag(pb, "isom");
1540
    else if (mov->mode == MODE_IPOD)
1541
        put_tag(pb, has_video ? "M4V ":"M4A ");
1542
    else
1543
        put_tag(pb, "qt  ");
1544

    
1545
    put_be32(pb, minor);
1546

    
1547
    if(mov->mode == MODE_MOV)
1548
        put_tag(pb, "qt  ");
1549
    else{
1550
        put_tag(pb, "isom");
1551
        put_tag(pb, "iso2");
1552
        if(has_h264)
1553
            put_tag(pb, "avc1");
1554
    }
1555

    
1556
    if (mov->mode == MODE_3GP)
1557
        put_tag(pb, has_h264 ? "3gp6":"3gp4");
1558
    else if (mov->mode & MODE_3G2)
1559
        put_tag(pb, has_h264 ? "3g2b":"3g2a");
1560
    else if (mov->mode == MODE_PSP)
1561
        put_tag(pb, "MSNV");
1562
    else if (mov->mode == MODE_MP4)
1563
        put_tag(pb, "mp41");
1564
    return updateSize(pb, pos);
1565
}
1566

    
1567
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1568
{
1569
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1570
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1571
    int AudioRate = AudioCodec->sample_rate;
1572
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1573
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1574
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1575

    
1576
    put_be32(pb, 0x94); /* size */
1577
    put_tag(pb, "uuid");
1578
    put_tag(pb, "PROF");
1579

    
1580
    put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1581
    put_be32(pb, 0xbb88695c);
1582
    put_be32(pb, 0xfac9c740);
1583

    
1584
    put_be32(pb, 0x0);  /* ? */
1585
    put_be32(pb, 0x3);  /* 3 sections ? */
1586

    
1587
    put_be32(pb, 0x14); /* size */
1588
    put_tag(pb, "FPRF");
1589
    put_be32(pb, 0x0);  /* ? */
1590
    put_be32(pb, 0x0);  /* ? */
1591
    put_be32(pb, 0x0);  /* ? */
1592

    
1593
    put_be32(pb, 0x2c);  /* size */
1594
    put_tag(pb, "APRF");   /* audio */
1595
    put_be32(pb, 0x0);
1596
    put_be32(pb, 0x2);   /* TrackID */
1597
    put_tag(pb, "mp4a");
1598
    put_be32(pb, 0x20f);
1599
    put_be32(pb, 0x0);
1600
    put_be32(pb, audio_kbitrate);
1601
    put_be32(pb, audio_kbitrate);
1602
    put_be32(pb, AudioRate);
1603
    put_be32(pb, AudioCodec->channels);
1604

    
1605
    put_be32(pb, 0x34);  /* size */
1606
    put_tag(pb, "VPRF");   /* video */
1607
    put_be32(pb, 0x0);
1608
    put_be32(pb, 0x1);    /* TrackID */
1609
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1610
        put_tag(pb, "avc1");
1611
        put_be16(pb, 0x014D);
1612
        put_be16(pb, 0x0015);
1613
    } else {
1614
        put_tag(pb, "mp4v");
1615
        put_be16(pb, 0x0000);
1616
        put_be16(pb, 0x0103);
1617
    }
1618
    put_be32(pb, 0x0);
1619
    put_be32(pb, video_kbitrate);
1620
    put_be32(pb, video_kbitrate);
1621
    put_be32(pb, FrameRate);
1622
    put_be32(pb, FrameRate);
1623
    put_be16(pb, VideoCodec->width);
1624
    put_be16(pb, VideoCodec->height);
1625
    put_be32(pb, 0x010001); /* ? */
1626
}
1627

    
1628
static int mov_write_header(AVFormatContext *s)
1629
{
1630
    ByteIOContext *pb = s->pb;
1631
    MOVMuxContext *mov = s->priv_data;
1632
    int i;
1633

    
1634
    if (url_is_streamed(s->pb)) {
1635
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
1636
        return -1;
1637
    }
1638

    
1639
    /* Default mode == MP4 */
1640
    mov->mode = MODE_MP4;
1641

    
1642
    if (s->oformat != NULL) {
1643
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1644
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
1645
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1646
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1647
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
1648

    
1649
        mov_write_ftyp_tag(pb,s);
1650
        if (mov->mode == MODE_PSP) {
1651
            if (s->nb_streams != 2) {
1652
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1653
                return -1;
1654
            }
1655
            mov_write_uuidprof_tag(pb,s);
1656
        }
1657
    }
1658

    
1659
    for(i=0; i<s->nb_streams; i++){
1660
        AVStream *st= s->streams[i];
1661
        MOVTrack *track= &mov->tracks[i];
1662
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
1663

    
1664
        track->enc = st->codec;
1665
        track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
1666
        if (track->language < 0)
1667
            track->language = 0;
1668
        track->mode = mov->mode;
1669
        track->tag = mov_find_codec_tag(s, track);
1670
        if (!track->tag) {
1671
            av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
1672
                   "codec not currently supported in container\n", i);
1673
            return -1;
1674
        }
1675
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1676
            if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
1677
                track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
1678
                track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
1679
                if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
1680
                    av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
1681
                    return -1;
1682
                }
1683
                track->height = track->tag>>24 == 'n' ? 486 : 576;
1684
            }
1685
            track->timescale = st->codec->time_base.den;
1686
            av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1687
            if (track->mode == MODE_MOV && track->timescale > 100000)
1688
                av_log(s, AV_LOG_WARNING,
1689
                       "WARNING codec timebase is very high. If duration is too long,\n"
1690
                       "file may not be playable by quicktime. Specify a shorter timebase\n"
1691
                       "or choose different container.\n");
1692
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO){
1693
            track->timescale = st->codec->sample_rate;
1694
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1695
            if(!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
1696
                av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
1697
                return -1;
1698
            }else if(st->codec->frame_size > 1){ /* assume compressed audio */
1699
                track->audio_vbr = 1;
1700
            }else{
1701
                st->codec->frame_size = 1;
1702
                track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
1703
            }
1704
            if(track->mode != MODE_MOV &&
1705
               track->enc->codec_id == CODEC_ID_MP3 && track->enc->sample_rate < 16000){
1706
                av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
1707
                       i, track->enc->sample_rate);
1708
                return -1;
1709
            }
1710
        }else if(st->codec->codec_type == CODEC_TYPE_SUBTITLE){
1711
            track->timescale = st->codec->time_base.den;
1712
            av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1713
        }
1714
        if (!track->height)
1715
            track->height = st->codec->height;
1716
    }
1717

    
1718
    mov_write_mdat_tag(pb, mov);
1719
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1720
    mov->nb_streams = s->nb_streams;
1721

    
1722
    put_flush_packet(pb);
1723

    
1724
    return 0;
1725
}
1726

    
1727
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1728
{
1729
    MOVMuxContext *mov = s->priv_data;
1730
    ByteIOContext *pb = s->pb;
1731
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1732
    AVCodecContext *enc = trk->enc;
1733
    unsigned int samplesInChunk = 0;
1734
    int size= pkt->size;
1735

    
1736
    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1737
    if (!size) return 0; /* Discard 0 sized packets */
1738

    
1739
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1740
        /* We must find out how many AMR blocks there are in one packet */
1741
        static uint16_t packed_size[16] =
1742
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1743
        int len = 0;
1744

    
1745
        while (len < size && samplesInChunk < 100) {
1746
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1747
            samplesInChunk++;
1748
        }
1749
        if(samplesInChunk > 1){
1750
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
1751
            return -1;
1752
        }
1753
    } else if (trk->sampleSize)
1754
        samplesInChunk = size/trk->sampleSize;
1755
    else
1756
        samplesInChunk = 1;
1757

    
1758
    /* copy extradata if it exists */
1759
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1760
        trk->vosLen = enc->extradata_size;
1761
        trk->vosData = av_malloc(trk->vosLen);
1762
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1763
    }
1764

    
1765
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1766
        /* from x264 or from bytestream h264 */
1767
        /* nal reformating needed */
1768
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1769
    } else {
1770
        put_buffer(pb, pkt->data, size);
1771
    }
1772

    
1773
    if ((enc->codec_id == CODEC_ID_DNXHD ||
1774
                enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
1775
        /* copy frame to create needed atoms */
1776
        trk->vosLen = size;
1777
        trk->vosData = av_malloc(size);
1778
        if (!trk->vosData)
1779
            return AVERROR(ENOMEM);
1780
        memcpy(trk->vosData, pkt->data, size);
1781
    }
1782

    
1783
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1784
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1785
        if (!trk->cluster)
1786
            return -1;
1787
    }
1788

    
1789
    trk->cluster[trk->entry].pos = url_ftell(pb) - size;
1790
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1791
    trk->cluster[trk->entry].size = size;
1792
    trk->cluster[trk->entry].entries = samplesInChunk;
1793
    trk->cluster[trk->entry].dts = pkt->dts;
1794
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1795

    
1796
    if (pkt->pts == AV_NOPTS_VALUE) {
1797
        av_log(s, AV_LOG_WARNING, "pts has no value\n");
1798
        pkt->pts = pkt->dts;
1799
    }
1800
    if (pkt->dts != pkt->pts)
1801
        trk->hasBframes = 1;
1802
    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1803
    trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1804
    if(trk->cluster[trk->entry].key_frame)
1805
        trk->hasKeyframes++;
1806
    trk->entry++;
1807
    trk->sampleCount += samplesInChunk;
1808
    mov->mdat_size += size;
1809

    
1810
    put_flush_packet(pb);
1811
    return 0;
1812
}
1813

    
1814
static int mov_write_trailer(AVFormatContext *s)
1815
{
1816
    MOVMuxContext *mov = s->priv_data;
1817
    ByteIOContext *pb = s->pb;
1818
    int res = 0;
1819
    int i;
1820

    
1821
    int64_t moov_pos = url_ftell(pb);
1822

    
1823
    /* Write size of mdat tag */
1824
    if (mov->mdat_size+8 <= UINT32_MAX) {
1825
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
1826
        put_be32(pb, mov->mdat_size+8);
1827
    } else {
1828
        /* overwrite 'wide' placeholder atom */
1829
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1830
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1831
        put_tag(pb, "mdat");
1832
        put_be64(pb, mov->mdat_size+16);
1833
    }
1834
    url_fseek(pb, moov_pos, SEEK_SET);
1835

    
1836
    mov_write_moov_tag(pb, mov, s);
1837

    
1838
    for (i=0; i<mov->nb_streams; i++) {
1839
        av_freep(&mov->tracks[i].cluster);
1840

    
1841
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
1842

    
1843
    }
1844

    
1845
    put_flush_packet(pb);
1846

    
1847
    return res;
1848
}
1849

    
1850
#if CONFIG_MOV_MUXER
1851
AVOutputFormat mov_muxer = {
1852
    "mov",
1853
    NULL_IF_CONFIG_SMALL("MOV format"),
1854
    NULL,
1855
    "mov",
1856
    sizeof(MOVMuxContext),
1857
    CODEC_ID_AAC,
1858
    CODEC_ID_MPEG4,
1859
    mov_write_header,
1860
    mov_write_packet,
1861
    mov_write_trailer,
1862
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1863
    .codec_tag = (const AVCodecTag* const []){codec_movvideo_tags, codec_movaudio_tags, 0},
1864
};
1865
#endif
1866
#if CONFIG_TGP_MUXER
1867
AVOutputFormat tgp_muxer = {
1868
    "3gp",
1869
    NULL_IF_CONFIG_SMALL("3GP format"),
1870
    NULL,
1871
    "3gp",
1872
    sizeof(MOVMuxContext),
1873
    CODEC_ID_AMR_NB,
1874
    CODEC_ID_H263,
1875
    mov_write_header,
1876
    mov_write_packet,
1877
    mov_write_trailer,
1878
    .flags = AVFMT_GLOBALHEADER,
1879
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
1880
};
1881
#endif
1882
#if CONFIG_MP4_MUXER
1883
AVOutputFormat mp4_muxer = {
1884
    "mp4",
1885
    NULL_IF_CONFIG_SMALL("MP4 format"),
1886
    "application/mp4",
1887
    "mp4",
1888
    sizeof(MOVMuxContext),
1889
    CODEC_ID_AAC,
1890
    CODEC_ID_MPEG4,
1891
    mov_write_header,
1892
    mov_write_packet,
1893
    mov_write_trailer,
1894
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1895
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
1896
};
1897
#endif
1898
#if CONFIG_PSP_MUXER
1899
AVOutputFormat psp_muxer = {
1900
    "psp",
1901
    NULL_IF_CONFIG_SMALL("PSP MP4 format"),
1902
    NULL,
1903
    "mp4,psp",
1904
    sizeof(MOVMuxContext),
1905
    CODEC_ID_AAC,
1906
    CODEC_ID_MPEG4,
1907
    mov_write_header,
1908
    mov_write_packet,
1909
    mov_write_trailer,
1910
    .flags = AVFMT_GLOBALHEADER,
1911
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
1912
};
1913
#endif
1914
#if CONFIG_TG2_MUXER
1915
AVOutputFormat tg2_muxer = {
1916
    "3g2",
1917
    NULL_IF_CONFIG_SMALL("3GP2 format"),
1918
    NULL,
1919
    "3g2",
1920
    sizeof(MOVMuxContext),
1921
    CODEC_ID_AMR_NB,
1922
    CODEC_ID_H263,
1923
    mov_write_header,
1924
    mov_write_packet,
1925
    mov_write_trailer,
1926
    .flags = AVFMT_GLOBALHEADER,
1927
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
1928
};
1929
#endif
1930
#if CONFIG_IPOD_MUXER
1931
AVOutputFormat ipod_muxer = {
1932
    "ipod",
1933
    NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
1934
    "application/mp4",
1935
    "m4v,m4a",
1936
    sizeof(MOVMuxContext),
1937
    CODEC_ID_AAC,
1938
    CODEC_ID_H264,
1939
    mov_write_header,
1940
    mov_write_packet,
1941
    mov_write_trailer,
1942
    .flags = AVFMT_GLOBALHEADER,
1943
    .codec_tag = (const AVCodecTag* const []){codec_ipod_tags, 0},
1944
};
1945
#endif