Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ edd33cb6

History | View | Annotate | Download (74.7 KB)

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

    
24
#include "movenc.h"
25
#include "avformat.h"
26
#include "riff.h"
27
#include "avio.h"
28
#include "isom.h"
29
#include "avc.h"
30
#include "libavcodec/get_bits.h"
31
#include "libavcodec/put_bits.h"
32
#include "internal.h"
33
#include "libavutil/avstring.h"
34

    
35
#undef NDEBUG
36
#include <assert.h>
37

    
38
//FIXME support 64 bit variant with wide placeholders
39
static int64_t updateSize(ByteIOContext *pb, int64_t pos)
40
{
41
    int64_t curpos = url_ftell(pb);
42
    url_fseek(pb, pos, SEEK_SET);
43
    put_be32(pb, curpos - pos); /* rewrite size */
44
    url_fseek(pb, curpos, SEEK_SET);
45

    
46
    return curpos - pos;
47
}
48

    
49
/* Chunk offset atom */
50
static int mov_write_stco_tag(ByteIOContext *pb, MOVTrack *track)
51
{
52
    int i;
53
    int mode64 = 0; //   use 32 bit size variant if possible
54
    int64_t pos = url_ftell(pb);
55
    put_be32(pb, 0); /* size */
56
    if (pos > UINT32_MAX) {
57
        mode64 = 1;
58
        put_tag(pb, "co64");
59
    } else
60
        put_tag(pb, "stco");
61
    put_be32(pb, 0); /* version & flags */
62
    put_be32(pb, track->entry); /* entry count */
63
    for (i=0; i<track->entry; i++) {
64
        if(mode64 == 1)
65
            put_be64(pb, track->cluster[i].pos);
66
        else
67
            put_be32(pb, track->cluster[i].pos);
68
    }
69
    return updateSize(pb, pos);
70
}
71

    
72
/* Sample size atom */
73
static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack *track)
74
{
75
    int equalChunks = 1;
76
    int i, j, entries = 0, tst = -1, oldtst = -1;
77

    
78
    int64_t pos = url_ftell(pb);
79
    put_be32(pb, 0); /* size */
80
    put_tag(pb, "stsz");
81
    put_be32(pb, 0); /* version & flags */
82

    
83
    for (i=0; i<track->entry; i++) {
84
        tst = track->cluster[i].size/track->cluster[i].entries;
85
        if(oldtst != -1 && tst != oldtst) {
86
            equalChunks = 0;
87
        }
88
        oldtst = tst;
89
        entries += track->cluster[i].entries;
90
    }
91
    if (equalChunks) {
92
        int sSize = track->cluster[0].size/track->cluster[0].entries;
93
        put_be32(pb, sSize); // sample size
94
        put_be32(pb, entries); // sample count
95
    }
96
    else {
97
        put_be32(pb, 0); // sample size
98
        put_be32(pb, entries); // sample count
99
        for (i=0; i<track->entry; i++) {
100
            for (j=0; j<track->cluster[i].entries; j++) {
101
                put_be32(pb, track->cluster[i].size /
102
                         track->cluster[i].entries);
103
            }
104
        }
105
    }
106
    return updateSize(pb, pos);
107
}
108

    
109
/* Sample to chunk atom */
110
static int mov_write_stsc_tag(ByteIOContext *pb, MOVTrack *track)
111
{
112
    int index = 0, oldval = -1, i;
113
    int64_t entryPos, curpos;
114

    
115
    int64_t pos = url_ftell(pb);
116
    put_be32(pb, 0); /* size */
117
    put_tag(pb, "stsc");
118
    put_be32(pb, 0); // version & flags
119
    entryPos = url_ftell(pb);
120
    put_be32(pb, track->entry); // entry count
121
    for (i=0; i<track->entry; i++) {
122
        if(oldval != track->cluster[i].samplesInChunk)
123
        {
124
            put_be32(pb, i+1); // first chunk
125
            put_be32(pb, track->cluster[i].samplesInChunk); // samples per chunk
126
            put_be32(pb, 0x1); // sample description index
127
            oldval = track->cluster[i].samplesInChunk;
128
            index++;
129
        }
130
    }
131
    curpos = url_ftell(pb);
132
    url_fseek(pb, entryPos, SEEK_SET);
133
    put_be32(pb, index); // rewrite size
134
    url_fseek(pb, curpos, SEEK_SET);
135

    
136
    return updateSize(pb, pos);
137
}
138

    
139
/* Sync sample atom */
140
static int mov_write_stss_tag(ByteIOContext *pb, MOVTrack *track, uint32_t flag)
141
{
142
    int64_t curpos, entryPos;
143
    int i, index = 0;
144
    int64_t pos = url_ftell(pb);
145
    put_be32(pb, 0); // size
146
    put_tag(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
147
    put_be32(pb, 0); // version & flags
148
    entryPos = url_ftell(pb);
149
    put_be32(pb, track->entry); // entry count
150
    for (i=0; i<track->entry; i++) {
151
        if (track->cluster[i].flags & flag) {
152
            put_be32(pb, i+1);
153
            index++;
154
        }
155
    }
156
    curpos = url_ftell(pb);
157
    url_fseek(pb, entryPos, SEEK_SET);
158
    put_be32(pb, index); // rewrite size
159
    url_fseek(pb, curpos, SEEK_SET);
160
    return updateSize(pb, pos);
161
}
162

    
163
static int mov_write_amr_tag(ByteIOContext *pb, MOVTrack *track)
164
{
165
    put_be32(pb, 0x11); /* size */
166
    if (track->mode == MODE_MOV) put_tag(pb, "samr");
167
    else                         put_tag(pb, "damr");
168
    put_tag(pb, "FFMP");
169
    put_byte(pb, 0); /* decoder version */
170

    
171
    put_be16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
172
    put_byte(pb, 0x00); /* Mode change period (no restriction) */
173
    put_byte(pb, 0x01); /* Frames per sample */
174
    return 0x11;
175
}
176

    
177
static int mov_write_ac3_tag(ByteIOContext *pb, MOVTrack *track)
178
{
179
    GetBitContext gbc;
180
    PutBitContext pbc;
181
    uint8_t buf[3];
182
    int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
183

    
184
    if (track->vosLen < 7)
185
        return -1;
186

    
187
    put_be32(pb, 11);
188
    put_tag(pb, "dac3");
189

    
190
    init_get_bits(&gbc, track->vosData+4, track->vosLen-4);
191
    fscod      = get_bits(&gbc, 2);
192
    frmsizecod = get_bits(&gbc, 6);
193
    bsid       = get_bits(&gbc, 5);
194
    bsmod      = get_bits(&gbc, 3);
195
    acmod      = get_bits(&gbc, 3);
196
    if (acmod == 2) {
197
        skip_bits(&gbc, 2); // dsurmod
198
    } else {
199
        if ((acmod & 1) && acmod != 1)
200
            skip_bits(&gbc, 2); // cmixlev
201
        if (acmod & 4)
202
            skip_bits(&gbc, 2); // surmixlev
203
    }
204
    lfeon = get_bits1(&gbc);
205

    
206
    init_put_bits(&pbc, buf, sizeof(buf));
207
    put_bits(&pbc, 2, fscod);
208
    put_bits(&pbc, 5, bsid);
209
    put_bits(&pbc, 3, bsmod);
210
    put_bits(&pbc, 3, acmod);
211
    put_bits(&pbc, 1, lfeon);
212
    put_bits(&pbc, 5, frmsizecod>>1); // bit_rate_code
213
    put_bits(&pbc, 5, 0); // reserved
214

    
215
    flush_put_bits(&pbc);
216
    put_buffer(pb, buf, sizeof(buf));
217

    
218
    return 11;
219
}
220

    
221
/**
222
 * This function writes extradata "as is".
223
 * Extradata must be formated like a valid atom (with size and tag)
224
 */
225
static int mov_write_extradata_tag(ByteIOContext *pb, MOVTrack *track)
226
{
227
    put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
228
    return track->enc->extradata_size;
229
}
230

    
231
static int mov_write_enda_tag(ByteIOContext *pb)
232
{
233
    put_be32(pb, 10);
234
    put_tag(pb, "enda");
235
    put_be16(pb, 1); /* little endian */
236
    return 10;
237
}
238

    
239
static unsigned int descrLength(unsigned int len)
240
{
241
    int i;
242
    for(i=1; len>>(7*i); i++);
243
    return len + 1 + i;
244
}
245

    
246
static void putDescr(ByteIOContext *pb, int tag, unsigned int size)
247
{
248
    int i= descrLength(size) - size - 2;
249
    put_byte(pb, tag);
250
    for(; i>0; i--)
251
        put_byte(pb, (size>>(7*i)) | 0x80);
252
    put_byte(pb, size & 0x7F);
253
}
254

    
255
static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack *track) // Basic
256
{
257
    int64_t pos = url_ftell(pb);
258
    int decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
259

    
260
    put_be32(pb, 0); // size
261
    put_tag(pb, "esds");
262
    put_be32(pb, 0); // Version
263

    
264
    // ES descriptor
265
    putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
266
             descrLength(1));
267
    put_be16(pb, track->trackID);
268
    put_byte(pb, 0x00); // flags (= no flags)
269

    
270
    // DecoderConfig descriptor
271
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
272

    
273
    // Object type indication
274
    if ((track->enc->codec_id == CODEC_ID_MP2 ||
275
         track->enc->codec_id == CODEC_ID_MP3) &&
276
        track->enc->sample_rate > 24000)
277
        put_byte(pb, 0x6B); // 11172-3
278
    else
279
        put_byte(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
280

    
281
    // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
282
    // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
283
    if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
284
        put_byte(pb, 0x15); // flags (= Audiostream)
285
    else
286
        put_byte(pb, 0x11); // flags (= Visualstream)
287

    
288
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));    // Buffersize DB (24 bits)
289
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
290

    
291
    put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
292
    if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
293
        put_be32(pb, 0); // vbr
294
    else
295
        put_be32(pb, track->enc->rc_max_rate); // avg bitrate
296

    
297
    if (track->vosLen) {
298
        // DecoderSpecific info descriptor
299
        putDescr(pb, 0x05, track->vosLen);
300
        put_buffer(pb, track->vosData, track->vosLen);
301
    }
302

    
303
    // SL descriptor
304
    putDescr(pb, 0x06, 1);
305
    put_byte(pb, 0x02);
306
    return updateSize(pb, pos);
307
}
308

    
309
static int mov_pcm_le_gt16(enum CodecID codec_id)
310
{
311
    return codec_id == CODEC_ID_PCM_S24LE ||
312
           codec_id == CODEC_ID_PCM_S32LE ||
313
           codec_id == CODEC_ID_PCM_F32LE ||
314
           codec_id == CODEC_ID_PCM_F64LE;
315
}
316

    
317
static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack *track)
318
{
319
    int64_t pos = url_ftell(pb);
320

    
321
    put_be32(pb, 0);     /* size */
322
    put_tag(pb, "wave");
323

    
324
    put_be32(pb, 12);    /* size */
325
    put_tag(pb, "frma");
326
    put_le32(pb, track->tag);
327

    
328
    if (track->enc->codec_id == CODEC_ID_AAC) {
329
        /* useless atom needed by mplayer, ipod, not needed by quicktime */
330
        put_be32(pb, 12); /* size */
331
        put_tag(pb, "mp4a");
332
        put_be32(pb, 0);
333
        mov_write_esds_tag(pb, track);
334
    } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
335
        mov_write_enda_tag(pb);
336
    } else if (track->enc->codec_id == CODEC_ID_AMR_NB) {
337
        mov_write_amr_tag(pb, track);
338
    } else if (track->enc->codec_id == CODEC_ID_AC3) {
339
        mov_write_ac3_tag(pb, track);
340
    } else if (track->enc->codec_id == CODEC_ID_ALAC) {
341
        mov_write_extradata_tag(pb, track);
342
    }
343

    
344
    put_be32(pb, 8);     /* size */
345
    put_be32(pb, 0);     /* null tag */
346

    
347
    return updateSize(pb, pos);
348
}
349

    
350
static int mov_write_glbl_tag(ByteIOContext *pb, MOVTrack *track)
351
{
352
    put_be32(pb, track->vosLen+8);
353
    put_tag(pb, "glbl");
354
    put_buffer(pb, track->vosData, track->vosLen);
355
    return 8+track->vosLen;
356
}
357

    
358
/**
359
 * Compute flags for 'lpcm' tag.
360
 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
361
 */
362
static int mov_get_lpcm_flags(enum CodecID codec_id)
363
{
364
    switch (codec_id) {
365
    case CODEC_ID_PCM_F32BE:
366
    case CODEC_ID_PCM_F64BE:
367
        return 11;
368
    case CODEC_ID_PCM_F32LE:
369
    case CODEC_ID_PCM_F64LE:
370
        return 9;
371
    case CODEC_ID_PCM_U8:
372
        return 10;
373
    case CODEC_ID_PCM_S16BE:
374
    case CODEC_ID_PCM_S24BE:
375
    case CODEC_ID_PCM_S32BE:
376
        return 14;
377
    case CODEC_ID_PCM_S8:
378
    case CODEC_ID_PCM_S16LE:
379
    case CODEC_ID_PCM_S24LE:
380
    case CODEC_ID_PCM_S32LE:
381
        return 12;
382
    default:
383
        return 0;
384
    }
385
}
386

    
387
static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack *track)
388
{
389
    int64_t pos = url_ftell(pb);
390
    int version = 0;
391
    uint32_t tag = track->tag;
392

    
393
    if (track->mode == MODE_MOV) {
394
        if (track->timescale > UINT16_MAX) {
395
            if (mov_get_lpcm_flags(track->enc->codec_id))
396
                tag = AV_RL32("lpcm");
397
            version = 2;
398
        } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id)) {
399
            version = 1;
400
        }
401
    }
402

    
403
    put_be32(pb, 0); /* size */
404
    put_le32(pb, tag); // store it byteswapped
405
    put_be32(pb, 0); /* Reserved */
406
    put_be16(pb, 0); /* Reserved */
407
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
408

    
409
    /* SoundDescription */
410
    put_be16(pb, version); /* Version */
411
    put_be16(pb, 0); /* Revision level */
412
    put_be32(pb, 0); /* Reserved */
413

    
414
    if (version == 2) {
415
        put_be16(pb, 3);
416
        put_be16(pb, 16);
417
        put_be16(pb, 0xfffe);
418
        put_be16(pb, 0);
419
        put_be32(pb, 0x00010000);
420
        put_be32(pb, 72);
421
        put_be64(pb, av_dbl2int(track->timescale));
422
        put_be32(pb, track->enc->channels);
423
        put_be32(pb, 0x7F000000);
424
        put_be32(pb, av_get_bits_per_sample(track->enc->codec_id));
425
        put_be32(pb, mov_get_lpcm_flags(track->enc->codec_id));
426
        put_be32(pb, track->sampleSize);
427
        put_be32(pb, track->enc->frame_size);
428
    } else {
429
        if (track->mode == MODE_MOV) {
430
            put_be16(pb, track->enc->channels);
431
            if (track->enc->codec_id == CODEC_ID_PCM_U8 ||
432
                track->enc->codec_id == CODEC_ID_PCM_S8)
433
                put_be16(pb, 8); /* bits per sample */
434
            else
435
                put_be16(pb, 16);
436
            put_be16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
437
        } else { /* reserved for mp4/3gp */
438
            put_be16(pb, 2);
439
            put_be16(pb, 16);
440
            put_be16(pb, 0);
441
        }
442

    
443
        put_be16(pb, 0); /* packet size (= 0) */
444
        put_be16(pb, track->timescale); /* Time scale */
445
        put_be16(pb, 0); /* Reserved */
446
    }
447

    
448
    if(version == 1) { /* SoundDescription V1 extended info */
449
        put_be32(pb, track->enc->frame_size); /* Samples per packet */
450
        put_be32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
451
        put_be32(pb, track->sampleSize); /* Bytes per frame */
452
        put_be32(pb, 2); /* Bytes per sample */
453
    }
454

    
455
    if(track->mode == MODE_MOV &&
456
       (track->enc->codec_id == CODEC_ID_AAC ||
457
        track->enc->codec_id == CODEC_ID_AC3 ||
458
        track->enc->codec_id == CODEC_ID_AMR_NB ||
459
        track->enc->codec_id == CODEC_ID_ALAC ||
460
        mov_pcm_le_gt16(track->enc->codec_id)))
461
        mov_write_wave_tag(pb, track);
462
    else if(track->tag == MKTAG('m','p','4','a'))
463
        mov_write_esds_tag(pb, track);
464
    else if(track->enc->codec_id == CODEC_ID_AMR_NB)
465
        mov_write_amr_tag(pb, track);
466
    else if(track->enc->codec_id == CODEC_ID_AC3)
467
        mov_write_ac3_tag(pb, track);
468
    else if(track->enc->codec_id == CODEC_ID_ALAC)
469
        mov_write_extradata_tag(pb, track);
470
    else if(track->vosLen > 0)
471
        mov_write_glbl_tag(pb, track);
472

    
473
    return updateSize(pb, pos);
474
}
475

    
476
static int mov_write_d263_tag(ByteIOContext *pb)
477
{
478
    put_be32(pb, 0xf); /* size */
479
    put_tag(pb, "d263");
480
    put_tag(pb, "FFMP");
481
    put_byte(pb, 0); /* decoder version */
482
    /* FIXME use AVCodecContext level/profile, when encoder will set values */
483
    put_byte(pb, 0xa); /* level */
484
    put_byte(pb, 0); /* profile */
485
    return 0xf;
486
}
487

    
488
/* TODO: No idea about these values */
489
static int mov_write_svq3_tag(ByteIOContext *pb)
490
{
491
    put_be32(pb, 0x15);
492
    put_tag(pb, "SMI ");
493
    put_tag(pb, "SEQH");
494
    put_be32(pb, 0x5);
495
    put_be32(pb, 0xe2c0211d);
496
    put_be32(pb, 0xc0000000);
497
    put_byte(pb, 0);
498
    return 0x15;
499
}
500

    
501
static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
502
{
503
    int64_t pos = url_ftell(pb);
504

    
505
    put_be32(pb, 0);
506
    put_tag(pb, "avcC");
507
    ff_isom_write_avcc(pb, track->vosData, track->vosLen);
508
    return updateSize(pb, pos);
509
}
510

    
511
/* also used by all avid codecs (dv, imx, meridien) and their variants */
512
static int mov_write_avid_tag(ByteIOContext *pb, MOVTrack *track)
513
{
514
    int i;
515
    put_be32(pb, 24); /* size */
516
    put_tag(pb, "ACLR");
517
    put_tag(pb, "ACLR");
518
    put_tag(pb, "0001");
519
    put_be32(pb, 1); /* yuv 1 / rgb 2 ? */
520
    put_be32(pb, 0); /* unknown */
521

    
522
    put_be32(pb, 24); /* size */
523
    put_tag(pb, "APRG");
524
    put_tag(pb, "APRG");
525
    put_tag(pb, "0001");
526
    put_be32(pb, 1); /* unknown */
527
    put_be32(pb, 0); /* unknown */
528

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

    
554
    /* extra padding for stsd needed */
555
    put_be32(pb, 0);
556
    return 0;
557
}
558

    
559
static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
560
{
561
    int tag = track->enc->codec_tag;
562

    
563
    if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
564
        return 0;
565

    
566
    if      (track->enc->codec_id == CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
567
    else if (track->enc->codec_id == CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
568
    else if (track->enc->codec_id == CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
569
    else if (track->enc->codec_id == CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
570
    else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
571
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
572

    
573
    return tag;
574
}
575

    
576
static const AVCodecTag codec_ipod_tags[] = {
577
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
578
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
579
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
580
    { CODEC_ID_ALAC,   MKTAG('a','l','a','c') },
581
    { CODEC_ID_AC3,    MKTAG('a','c','-','3') },
582
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
583
    { CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
584
    { CODEC_ID_NONE, 0 },
585
};
586

    
587
static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
588
{
589
    int tag = track->enc->codec_tag;
590

    
591
    // keep original tag for subs, ipod supports both formats
592
    if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
593
        (tag == MKTAG('t','x','3','g') ||
594
         tag == MKTAG('t','e','x','t'))))
595
        tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
596

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

    
601
    return tag;
602
}
603

    
604
static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
605
{
606
    int tag;
607

    
608
    if (track->enc->height == 480) /* NTSC */
609
        if  (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
610
        else                                         tag = MKTAG('d','v','c',' ');
611
    else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
612
    else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
613
    else                                             tag = MKTAG('d','v','p','p');
614

    
615
    return tag;
616
}
617

    
618
static const struct {
619
    enum PixelFormat pix_fmt;
620
    uint32_t tag;
621
    unsigned bps;
622
} mov_pix_fmt_tags[] = {
623
    { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
624
    { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
625
    { PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
626
    { PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
627
    { PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
628
    { PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
629
    { PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
630
    { PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
631
    { PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
632
    { PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
633
    { PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
634
    { PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
635
    { PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
636
    { PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
637
};
638

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

    
644
    for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
645
        if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
646
            tag = mov_pix_fmt_tags[i].tag;
647
            track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
648
            break;
649
        }
650
    }
651

    
652
    return tag;
653
}
654

    
655
static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
656
{
657
    int tag = track->enc->codec_tag;
658

    
659
    if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
660
                 (tag == MKTAG('d','v','c','p') ||
661
                  track->enc->codec_id == CODEC_ID_RAWVIDEO ||
662
                  av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
663
        if (track->enc->codec_id == CODEC_ID_DVVIDEO)
664
            tag = mov_get_dv_codec_tag(s, track);
665
        else if (track->enc->codec_id == CODEC_ID_RAWVIDEO)
666
            tag = mov_get_rawvideo_codec_tag(s, track);
667
        else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
668
            tag = ff_codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
669
            if (!tag) { // if no mac fcc found, try with Microsoft tags
670
                tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
671
                if (tag)
672
                    av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, "
673
                           "the file may be unplayable!\n");
674
            }
675
        } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
676
            tag = ff_codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
677
            if (!tag) { // if no mac fcc found, try with Microsoft tags
678
                int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
679
                if (ms_tag) {
680
                    tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
681
                    av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, "
682
                           "the file may be unplayable!\n");
683
                }
684
            }
685
        } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
686
            tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
687
    }
688

    
689
    return tag;
690
}
691

    
692
static const AVCodecTag codec_3gp_tags[] = {
693
    { CODEC_ID_H263,   MKTAG('s','2','6','3') },
694
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
695
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
696
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
697
    { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
698
    { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
699
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
700
    { CODEC_ID_NONE, 0 },
701
};
702

    
703
static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
704
{
705
    int tag = track->enc->codec_tag;
706

    
707
    if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
708
        tag = mp4_get_codec_tag(s, track);
709
    else if (track->mode == MODE_IPOD)
710
        tag = ipod_get_codec_tag(s, track);
711
    else if (track->mode & MODE_3GP)
712
        tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
713
    else
714
        tag = mov_get_codec_tag(s, track);
715

    
716
    return tag;
717
}
718

    
719
/** Write uuid atom.
720
 * Needed to make file play in iPods running newest firmware
721
 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
722
 */
723
static int mov_write_uuid_tag_ipod(ByteIOContext *pb)
724
{
725
    put_be32(pb, 28);
726
    put_tag(pb, "uuid");
727
    put_be32(pb, 0x6b6840f2);
728
    put_be32(pb, 0x5f244fc5);
729
    put_be32(pb, 0xba39a51b);
730
    put_be32(pb, 0xcf0323f3);
731
    put_be32(pb, 0x0);
732
    return 28;
733
}
734

    
735
static int mov_write_subtitle_tag(ByteIOContext *pb, MOVTrack *track)
736
{
737
    int64_t pos = url_ftell(pb);
738
    put_be32(pb, 0);    /* size */
739
    put_le32(pb, track->tag); // store it byteswapped
740
    put_be32(pb, 0);    /* Reserved */
741
    put_be16(pb, 0);    /* Reserved */
742
    put_be16(pb, 1);    /* Data-reference index */
743

    
744
    if (track->enc->extradata_size)
745
        put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
746

    
747
    return updateSize(pb, pos);
748
}
749

    
750
static int mov_write_pasp_tag(ByteIOContext *pb, MOVTrack *track)
751
{
752
    AVRational sar;
753
    av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
754
              track->enc->sample_aspect_ratio.den, INT_MAX);
755

    
756
    put_be32(pb, 16);
757
    put_tag(pb, "pasp");
758
    put_be32(pb, sar.num);
759
    put_be32(pb, sar.den);
760
    return 16;
761
}
762

    
763
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack *track)
764
{
765
    int64_t pos = url_ftell(pb);
766
    char compressor_name[32];
767

    
768
    put_be32(pb, 0); /* size */
769
    put_le32(pb, track->tag); // store it byteswapped
770
    put_be32(pb, 0); /* Reserved */
771
    put_be16(pb, 0); /* Reserved */
772
    put_be16(pb, 1); /* Data-reference index */
773

    
774
    put_be16(pb, 0); /* Codec stream version */
775
    put_be16(pb, 0); /* Codec stream revision (=0) */
776
    if (track->mode == MODE_MOV) {
777
        put_tag(pb, "FFMP"); /* Vendor */
778
        if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
779
            put_be32(pb, 0); /* Temporal Quality */
780
            put_be32(pb, 0x400); /* Spatial Quality = lossless*/
781
        } else {
782
            put_be32(pb, 0x200); /* Temporal Quality = normal */
783
            put_be32(pb, 0x200); /* Spatial Quality = normal */
784
        }
785
    } else {
786
        put_be32(pb, 0); /* Reserved */
787
        put_be32(pb, 0); /* Reserved */
788
        put_be32(pb, 0); /* Reserved */
789
    }
790
    put_be16(pb, track->enc->width); /* Video width */
791
    put_be16(pb, track->height); /* Video height */
792
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
793
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
794
    put_be32(pb, 0); /* Data size (= 0) */
795
    put_be16(pb, 1); /* Frame count (= 1) */
796

    
797
    memset(compressor_name,0,32);
798
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
799
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
800
        strncpy(compressor_name,track->enc->codec->name,31);
801
    put_byte(pb, strlen(compressor_name));
802
    put_buffer(pb, compressor_name, 31);
803

    
804
    if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
805
        put_be16(pb, track->enc->bits_per_coded_sample);
806
    else
807
        put_be16(pb, 0x18); /* Reserved */
808
    put_be16(pb, 0xffff); /* Reserved */
809
    if(track->tag == MKTAG('m','p','4','v'))
810
        mov_write_esds_tag(pb, track);
811
    else if(track->enc->codec_id == CODEC_ID_H263)
812
        mov_write_d263_tag(pb);
813
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
814
        mov_write_svq3_tag(pb);
815
    else if(track->enc->codec_id == CODEC_ID_DNXHD)
816
        mov_write_avid_tag(pb, track);
817
    else if(track->enc->codec_id == CODEC_ID_H264) {
818
        mov_write_avcc_tag(pb, track);
819
        if(track->mode == MODE_IPOD)
820
            mov_write_uuid_tag_ipod(pb);
821
    } else if(track->vosLen > 0)
822
        mov_write_glbl_tag(pb, track);
823

    
824
    if (track->mode == MODE_MOV &&
825
        track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
826
        track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
827
        mov_write_pasp_tag(pb, track);
828
    }
829

    
830
    return updateSize(pb, pos);
831
}
832

    
833
static int mov_write_rtp_tag(ByteIOContext *pb, MOVTrack *track)
834
{
835
    int64_t pos = url_ftell(pb);
836
    put_be32(pb, 0); /* size */
837
    put_tag(pb, "rtp ");
838
    put_be32(pb, 0); /* Reserved */
839
    put_be16(pb, 0); /* Reserved */
840
    put_be16(pb, 1); /* Data-reference index */
841

    
842
    put_be16(pb, 1); /* Hint track version */
843
    put_be16(pb, 1); /* Highest compatible version */
844
    put_be32(pb, track->max_packet_size); /* Max packet size */
845

    
846
    put_be32(pb, 12); /* size */
847
    put_tag(pb, "tims");
848
    put_be32(pb, track->timescale);
849

    
850
    return updateSize(pb, pos);
851
}
852

    
853
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack *track)
854
{
855
    int64_t pos = url_ftell(pb);
856
    put_be32(pb, 0); /* size */
857
    put_tag(pb, "stsd");
858
    put_be32(pb, 0); /* version & flags */
859
    put_be32(pb, 1); /* entry count */
860
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
861
        mov_write_video_tag(pb, track);
862
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
863
        mov_write_audio_tag(pb, track);
864
    else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
865
        mov_write_subtitle_tag(pb, track);
866
    else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
867
        mov_write_rtp_tag(pb, track);
868
    return updateSize(pb, pos);
869
}
870

    
871
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack *track)
872
{
873
    MOVStts *ctts_entries;
874
    uint32_t entries = 0;
875
    uint32_t atom_size;
876
    int i;
877

    
878
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
879
    ctts_entries[0].count = 1;
880
    ctts_entries[0].duration = track->cluster[0].cts;
881
    for (i=1; i<track->entry; i++) {
882
        if (track->cluster[i].cts == ctts_entries[entries].duration) {
883
            ctts_entries[entries].count++; /* compress */
884
        } else {
885
            entries++;
886
            ctts_entries[entries].duration = track->cluster[i].cts;
887
            ctts_entries[entries].count = 1;
888
        }
889
    }
890
    entries++; /* last one */
891
    atom_size = 16 + (entries * 8);
892
    put_be32(pb, atom_size); /* size */
893
    put_tag(pb, "ctts");
894
    put_be32(pb, 0); /* version & flags */
895
    put_be32(pb, entries); /* entry count */
896
    for (i=0; i<entries; i++) {
897
        put_be32(pb, ctts_entries[i].count);
898
        put_be32(pb, ctts_entries[i].duration);
899
    }
900
    av_free(ctts_entries);
901
    return atom_size;
902
}
903

    
904
/* Time to sample atom */
905
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack *track)
906
{
907
    MOVStts *stts_entries;
908
    uint32_t entries = -1;
909
    uint32_t atom_size;
910
    int i;
911

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

    
946
static int mov_write_dref_tag(ByteIOContext *pb)
947
{
948
    put_be32(pb, 28); /* size */
949
    put_tag(pb, "dref");
950
    put_be32(pb, 0); /* version & flags */
951
    put_be32(pb, 1); /* entry count */
952

    
953
    put_be32(pb, 0xc); /* size */
954
    put_tag(pb, "url ");
955
    put_be32(pb, 1); /* version & flags */
956

    
957
    return 28;
958
}
959

    
960
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack *track)
961
{
962
    int64_t pos = url_ftell(pb);
963
    put_be32(pb, 0); /* size */
964
    put_tag(pb, "stbl");
965
    mov_write_stsd_tag(pb, track);
966
    mov_write_stts_tag(pb, track);
967
    if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
968
         track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
969
        track->hasKeyframes && track->hasKeyframes < track->entry)
970
        mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
971
    if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
972
        mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
973
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
974
        track->flags & MOV_TRACK_CTTS)
975
        mov_write_ctts_tag(pb, track);
976
    mov_write_stsc_tag(pb, track);
977
    mov_write_stsz_tag(pb, track);
978
    mov_write_stco_tag(pb, track);
979
    return updateSize(pb, pos);
980
}
981

    
982
static int mov_write_dinf_tag(ByteIOContext *pb)
983
{
984
    int64_t pos = url_ftell(pb);
985
    put_be32(pb, 0); /* size */
986
    put_tag(pb, "dinf");
987
    mov_write_dref_tag(pb);
988
    return updateSize(pb, pos);
989
}
990

    
991
static int mov_write_nmhd_tag(ByteIOContext *pb)
992
{
993
    put_be32(pb, 12);
994
    put_tag(pb, "nmhd");
995
    put_be32(pb, 0);
996
    return 12;
997
}
998

    
999
static int mov_write_gmhd_tag(ByteIOContext *pb)
1000
{
1001
    put_be32(pb, 0x20);   /* size */
1002
    put_tag(pb, "gmhd");
1003
    put_be32(pb, 0x18);   /* gmin size */
1004
    put_tag(pb, "gmin");  /* generic media info */
1005
    put_be32(pb, 0);      /* version & flags */
1006
    put_be16(pb, 0x40);   /* graphics mode = */
1007
    put_be16(pb, 0x8000); /* opColor (r?) */
1008
    put_be16(pb, 0x8000); /* opColor (g?) */
1009
    put_be16(pb, 0x8000); /* opColor (b?) */
1010
    put_be16(pb, 0);      /* balance */
1011
    put_be16(pb, 0);      /* reserved */
1012
    return 0x20;
1013
}
1014

    
1015
static int mov_write_smhd_tag(ByteIOContext *pb)
1016
{
1017
    put_be32(pb, 16); /* size */
1018
    put_tag(pb, "smhd");
1019
    put_be32(pb, 0); /* version & flags */
1020
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
1021
    put_be16(pb, 0); /* reserved */
1022
    return 16;
1023
}
1024

    
1025
static int mov_write_vmhd_tag(ByteIOContext *pb)
1026
{
1027
    put_be32(pb, 0x14); /* size (always 0x14) */
1028
    put_tag(pb, "vmhd");
1029
    put_be32(pb, 0x01); /* version & flags */
1030
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
1031
    return 0x14;
1032
}
1033

    
1034
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)
1035
{
1036
    const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1037
    int64_t pos = url_ftell(pb);
1038

    
1039
    if (!track) { /* no media --> data handler */
1040
        hdlr = "dhlr";
1041
        hdlr_type = "url ";
1042
        descr = "DataHandler";
1043
    } else {
1044
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1045
        if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1046
            hdlr_type = "vide";
1047
            descr = "VideoHandler";
1048
        } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1049
            hdlr_type = "soun";
1050
            descr = "SoundHandler";
1051
        } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1052
            if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
1053
            else                                      hdlr_type = "text";
1054
            descr = "SubtitleHandler";
1055
        } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1056
            hdlr_type = "hint";
1057
            descr = "HintHandler";
1058
        }
1059
    }
1060

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

    
1077
static int mov_write_hmhd_tag(ByteIOContext *pb)
1078
{
1079
    /* This atom must be present, but leaving the values at zero
1080
     * seems harmless. */
1081
    put_be32(pb, 28); /* size */
1082
    put_tag(pb, "hmhd");
1083
    put_be32(pb, 0); /* version, flags */
1084
    put_be16(pb, 0); /* maxPDUsize */
1085
    put_be16(pb, 0); /* avgPDUsize */
1086
    put_be32(pb, 0); /* maxbitrate */
1087
    put_be32(pb, 0); /* avgbitrate */
1088
    put_be32(pb, 0); /* reserved */
1089
    return 28;
1090
}
1091

    
1092
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack *track)
1093
{
1094
    int64_t pos = url_ftell(pb);
1095
    put_be32(pb, 0); /* size */
1096
    put_tag(pb, "minf");
1097
    if(track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1098
        mov_write_vmhd_tag(pb);
1099
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1100
        mov_write_smhd_tag(pb);
1101
    else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1102
        if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb);
1103
        else                                      mov_write_nmhd_tag(pb);
1104
    } else if (track->tag == MKTAG('r','t','p',' ')) {
1105
        mov_write_hmhd_tag(pb);
1106
    }
1107
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1108
        mov_write_hdlr_tag(pb, NULL);
1109
    mov_write_dinf_tag(pb);
1110
    mov_write_stbl_tag(pb, track);
1111
    return updateSize(pb, pos);
1112
}
1113

    
1114
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack *track)
1115
{
1116
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
1117

    
1118
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
1119
    put_tag(pb, "mdhd");
1120
    put_byte(pb, version);
1121
    put_be24(pb, 0); /* flags */
1122
    if (version == 1) {
1123
        put_be64(pb, track->time);
1124
        put_be64(pb, track->time);
1125
    } else {
1126
        put_be32(pb, track->time); /* creation time */
1127
        put_be32(pb, track->time); /* modification time */
1128
    }
1129
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
1130
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
1131
    put_be16(pb, track->language); /* language */
1132
    put_be16(pb, 0); /* reserved (quality) */
1133

    
1134
    if(version!=0 && track->mode == MODE_MOV){
1135
        av_log(NULL, AV_LOG_ERROR,
1136
            "FATAL error, file duration too long for timebase, this file will not be\n"
1137
            "playable with quicktime. Choose a different timebase or a different\n"
1138
            "container format\n");
1139
    }
1140

    
1141
    return 32;
1142
}
1143

    
1144
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack *track)
1145
{
1146
    int64_t pos = url_ftell(pb);
1147
    put_be32(pb, 0); /* size */
1148
    put_tag(pb, "mdia");
1149
    mov_write_mdhd_tag(pb, track);
1150
    mov_write_hdlr_tag(pb, track);
1151
    mov_write_minf_tag(pb, track);
1152
    return updateSize(pb, pos);
1153
}
1154

    
1155
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1156
{
1157
    int64_t duration = av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1158
                                      track->timescale, AV_ROUND_UP);
1159
    int version = duration < INT32_MAX ? 0 : 1;
1160

    
1161
    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
1162
    put_tag(pb, "tkhd");
1163
    put_byte(pb, version);
1164
    put_be24(pb, 0xf); /* flags (track enabled) */
1165
    if (version == 1) {
1166
        put_be64(pb, track->time);
1167
        put_be64(pb, track->time);
1168
    } else {
1169
        put_be32(pb, track->time); /* creation time */
1170
        put_be32(pb, track->time); /* modification time */
1171
    }
1172
    put_be32(pb, track->trackID); /* track-id */
1173
    put_be32(pb, 0); /* reserved */
1174
    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
1175

    
1176
    put_be32(pb, 0); /* reserved */
1177
    put_be32(pb, 0); /* reserved */
1178
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
1179
    /* Volume, only for audio */
1180
    if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1181
        put_be16(pb, 0x0100);
1182
    else
1183
        put_be16(pb, 0);
1184
    put_be16(pb, 0); /* reserved */
1185

    
1186
    /* Matrix structure */
1187
    put_be32(pb, 0x00010000); /* reserved */
1188
    put_be32(pb, 0x0); /* reserved */
1189
    put_be32(pb, 0x0); /* reserved */
1190
    put_be32(pb, 0x0); /* reserved */
1191
    put_be32(pb, 0x00010000); /* reserved */
1192
    put_be32(pb, 0x0); /* reserved */
1193
    put_be32(pb, 0x0); /* reserved */
1194
    put_be32(pb, 0x0); /* reserved */
1195
    put_be32(pb, 0x40000000); /* reserved */
1196

    
1197
    /* Track width and height, for visual only */
1198
    if(st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1199
              track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1200
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1201
        if(!sample_aspect_ratio || track->height != track->enc->height)
1202
            sample_aspect_ratio = 1;
1203
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1204
        put_be32(pb, track->height*0x10000);
1205
    }
1206
    else {
1207
        put_be32(pb, 0);
1208
        put_be32(pb, 0);
1209
    }
1210
    return 0x5c;
1211
}
1212

    
1213
// This box seems important for the psp playback ... without it the movie seems to hang
1214
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
1215
{
1216
    put_be32(pb, 0x24); /* size  */
1217
    put_tag(pb, "edts");
1218
    put_be32(pb, 0x1c); /* size  */
1219
    put_tag(pb, "elst");
1220
    put_be32(pb, 0x0);
1221
    put_be32(pb, 0x1);
1222

    
1223
    /* duration   ... doesn't seem to effect psp */
1224
    put_be32(pb, av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1225
                                track->timescale, AV_ROUND_UP));
1226

    
1227
    put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
1228
    put_be32(pb, 0x00010000);
1229
    return 0x24;
1230
}
1231

    
1232
static int mov_write_tref_tag(ByteIOContext *pb, MOVTrack *track)
1233
{
1234
    put_be32(pb, 20);   // size
1235
    put_tag(pb, "tref");
1236
    put_be32(pb, 12);   // size (subatom)
1237
    put_le32(pb, track->tref_tag);
1238
    put_be32(pb, track->tref_id);
1239
    return 20;
1240
}
1241

    
1242
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1243
static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
1244
{
1245
    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1246
    put_tag(pb, "uuid");
1247
    put_tag(pb, "USMT");
1248
    put_be32(pb, 0x21d24fce);
1249
    put_be32(pb, 0xbb88695c);
1250
    put_be32(pb, 0xfac9c740);
1251
    put_be32(pb, 0x1c);     // another size here!
1252
    put_tag(pb, "MTDT");
1253
    put_be32(pb, 0x00010012);
1254
    put_be32(pb, 0x0a);
1255
    put_be32(pb, 0x55c40000);
1256
    put_be32(pb, 0x1);
1257
    put_be32(pb, 0x0);
1258
    return 0x34;
1259
}
1260

    
1261
static int mov_write_udta_sdp(ByteIOContext *pb, AVCodecContext *ctx, int index)
1262
{
1263
    char buf[1000] = "";
1264
    int len;
1265

    
1266
    ff_sdp_write_media(buf, sizeof(buf), ctx, NULL, NULL, 0, 0);
1267
    av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", index);
1268
    len = strlen(buf);
1269

    
1270
    put_be32(pb, len + 24);
1271
    put_tag (pb, "udta");
1272
    put_be32(pb, len + 16);
1273
    put_tag (pb, "hnti");
1274
    put_be32(pb, len + 8);
1275
    put_tag (pb, "sdp ");
1276
    put_buffer(pb, buf, len);
1277
    return len + 24;
1278
}
1279

    
1280
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1281
{
1282
    int64_t pos = url_ftell(pb);
1283
    put_be32(pb, 0); /* size */
1284
    put_tag(pb, "trak");
1285
    mov_write_tkhd_tag(pb, track, st);
1286
    if (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS)
1287
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1288
    if (track->tref_tag)
1289
        mov_write_tref_tag(pb, track);
1290
    mov_write_mdia_tag(pb, track);
1291
    if (track->mode == MODE_PSP)
1292
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1293
    if (track->tag == MKTAG('r','t','p',' '))
1294
        mov_write_udta_sdp(pb, track->rtp_ctx->streams[0]->codec, track->trackID);
1295
    return updateSize(pb, pos);
1296
}
1297

    
1298
#if 0
1299
/* TODO: Not sorted out, but not necessary either */
1300
static int mov_write_iods_tag(ByteIOContext *pb, MOVMuxContext *mov)
1301
{
1302
    put_be32(pb, 0x15); /* size */
1303
    put_tag(pb, "iods");
1304
    put_be32(pb, 0);    /* version & flags */
1305
    put_be16(pb, 0x1007);
1306
    put_byte(pb, 0);
1307
    put_be16(pb, 0x4fff);
1308
    put_be16(pb, 0xfffe);
1309
    put_be16(pb, 0x01ff);
1310
    return 0x15;
1311
}
1312
#endif
1313

    
1314
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVMuxContext *mov)
1315
{
1316
    int maxTrackID = 1, i;
1317
    int64_t maxTrackLenTemp, maxTrackLen = 0;
1318
    int version;
1319

    
1320
    for (i=0; i<mov->nb_streams; i++) {
1321
        if(mov->tracks[i].entry > 0) {
1322
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration,
1323
                                             MOV_TIMESCALE,
1324
                                             mov->tracks[i].timescale,
1325
                                             AV_ROUND_UP);
1326
            if(maxTrackLen < maxTrackLenTemp)
1327
                maxTrackLen = maxTrackLenTemp;
1328
            if(maxTrackID < mov->tracks[i].trackID)
1329
                maxTrackID = mov->tracks[i].trackID;
1330
        }
1331
    }
1332

    
1333
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1334
    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1335
    put_tag(pb, "mvhd");
1336
    put_byte(pb, version);
1337
    put_be24(pb, 0); /* flags */
1338
    if (version == 1) {
1339
        put_be64(pb, mov->time);
1340
        put_be64(pb, mov->time);
1341
    } else {
1342
        put_be32(pb, mov->time); /* creation time */
1343
        put_be32(pb, mov->time); /* modification time */
1344
    }
1345
    put_be32(pb, MOV_TIMESCALE);
1346
    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1347

    
1348
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1349
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1350
    put_be16(pb, 0); /* reserved */
1351
    put_be32(pb, 0); /* reserved */
1352
    put_be32(pb, 0); /* reserved */
1353

    
1354
    /* Matrix structure */
1355
    put_be32(pb, 0x00010000); /* reserved */
1356
    put_be32(pb, 0x0); /* reserved */
1357
    put_be32(pb, 0x0); /* reserved */
1358
    put_be32(pb, 0x0); /* reserved */
1359
    put_be32(pb, 0x00010000); /* reserved */
1360
    put_be32(pb, 0x0); /* reserved */
1361
    put_be32(pb, 0x0); /* reserved */
1362
    put_be32(pb, 0x0); /* reserved */
1363
    put_be32(pb, 0x40000000); /* reserved */
1364

    
1365
    put_be32(pb, 0); /* reserved (preview time) */
1366
    put_be32(pb, 0); /* reserved (preview duration) */
1367
    put_be32(pb, 0); /* reserved (poster time) */
1368
    put_be32(pb, 0); /* reserved (selection time) */
1369
    put_be32(pb, 0); /* reserved (selection duration) */
1370
    put_be32(pb, 0); /* reserved (current time) */
1371
    put_be32(pb, maxTrackID+1); /* Next track id */
1372
    return 0x6c;
1373
}
1374

    
1375
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVMuxContext *mov,
1376
                                     AVFormatContext *s)
1377
{
1378
    put_be32(pb, 33); /* size */
1379
    put_tag(pb, "hdlr");
1380
    put_be32(pb, 0);
1381
    put_be32(pb, 0);
1382
    put_tag(pb, "mdir");
1383
    put_tag(pb, "appl");
1384
    put_be32(pb, 0);
1385
    put_be32(pb, 0);
1386
    put_byte(pb, 0);
1387
    return 33;
1388
}
1389

    
1390
/* helper function to write a data tag with the specified string as data */
1391
static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int lang, int long_style)
1392
{
1393
    if(long_style){
1394
        int size = 16 + strlen(data);
1395
        put_be32(pb, size); /* size */
1396
        put_tag(pb, "data");
1397
        put_be32(pb, 1);
1398
        put_be32(pb, 0);
1399
        put_buffer(pb, data, strlen(data));
1400
        return size;
1401
    }else{
1402
        if (!lang)
1403
            lang = ff_mov_iso639_to_lang("und", 1);
1404
        put_be16(pb, strlen(data)); /* string length */
1405
        put_be16(pb, lang);
1406
        put_buffer(pb, data, strlen(data));
1407
        return strlen(data) + 4;
1408
    }
1409
}
1410

    
1411
static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int lang, int long_style){
1412
    int size = 0;
1413
    if (value && value[0]) {
1414
        int64_t pos = url_ftell(pb);
1415
        put_be32(pb, 0); /* size */
1416
        put_tag(pb, name);
1417
        mov_write_string_data_tag(pb, value, lang, long_style);
1418
        size= updateSize(pb, pos);
1419
    }
1420
    return size;
1421
}
1422

    
1423
static int mov_write_string_metadata(AVFormatContext *s, ByteIOContext *pb,
1424
                                     const char *name, const char *tag,
1425
                                     int long_style)
1426
{
1427
    int l, lang = 0, len, len2;
1428
    AVMetadataTag *t, *t2 = NULL;
1429
    char tag2[16];
1430

    
1431
    if (!(t = av_metadata_get(s->metadata, tag, NULL, 0)))
1432
        return 0;
1433

    
1434
    len = strlen(t->key);
1435
    snprintf(tag2, sizeof(tag2), "%s-", tag);
1436
    while ((t2 = av_metadata_get(s->metadata, tag2, t2, AV_METADATA_IGNORE_SUFFIX))) {
1437
        len2 = strlen(t2->key);
1438
        if (len2 == len+4 && !strcmp(t->value, t2->value)
1439
            && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 1)) >= 0) {
1440
            lang = l;
1441
            break;
1442
        }
1443
    }
1444
    return mov_write_string_tag(pb, name, t->value, lang, long_style);
1445
}
1446

    
1447
/* iTunes track number */
1448
static int mov_write_trkn_tag(ByteIOContext *pb, MOVMuxContext *mov,
1449
                              AVFormatContext *s)
1450
{
1451
    AVMetadataTag *t = av_metadata_get(s->metadata, "track", NULL, 0);
1452
    int size = 0, track = t ? atoi(t->value) : 0;
1453
    if (track) {
1454
        put_be32(pb, 32); /* size */
1455
        put_tag(pb, "trkn");
1456
            put_be32(pb, 24); /* size */
1457
            put_tag(pb, "data");
1458
            put_be32(pb, 0);        // 8 bytes empty
1459
            put_be32(pb, 0);
1460
            put_be16(pb, 0);        // empty
1461
            put_be16(pb, track);    // track number
1462
            put_be16(pb, 0);        // total track number
1463
            put_be16(pb, 0);        // empty
1464
        size = 32;
1465
    }
1466
    return size;
1467
}
1468

    
1469
/* iTunes meta data list */
1470
static int mov_write_ilst_tag(ByteIOContext *pb, MOVMuxContext *mov,
1471
                              AVFormatContext *s)
1472
{
1473
    int64_t pos = url_ftell(pb);
1474
    put_be32(pb, 0); /* size */
1475
    put_tag(pb, "ilst");
1476
    mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1477
    mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
1478
    mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
1479
    mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1480
    mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1481
    mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
1482
    mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1483
    mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1484
    mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1485
    mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1486
    mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
1487
    mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
1488
    mov_write_string_metadata(s, pb, "desc",    "description",1);
1489
    mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
1490
    mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
1491
    mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
1492
    mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
1493
    mov_write_trkn_tag(pb, mov, s);
1494
    return updateSize(pb, pos);
1495
}
1496

    
1497
/* iTunes meta data tag */
1498
static int mov_write_meta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1499
                              AVFormatContext *s)
1500
{
1501
    int size = 0;
1502
    int64_t pos = url_ftell(pb);
1503
    put_be32(pb, 0); /* size */
1504
    put_tag(pb, "meta");
1505
    put_be32(pb, 0);
1506
    mov_write_itunes_hdlr_tag(pb, mov, s);
1507
    mov_write_ilst_tag(pb, mov, s);
1508
    size = updateSize(pb, pos);
1509
    return size;
1510
}
1511

    
1512
static int utf8len(const uint8_t *b)
1513
{
1514
    int len=0;
1515
    int val;
1516
    while(*b){
1517
        GET_UTF8(val, *b++, return -1;)
1518
        len++;
1519
    }
1520
    return len;
1521
}
1522

    
1523
static int ascii_to_wc(ByteIOContext *pb, const uint8_t *b)
1524
{
1525
    int val;
1526
    while(*b){
1527
        GET_UTF8(val, *b++, return -1;)
1528
        put_be16(pb, val);
1529
    }
1530
    put_be16(pb, 0x00);
1531
    return 0;
1532
}
1533

    
1534
static uint16_t language_code(const char *str)
1535
{
1536
    return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1537
}
1538

    
1539
static int mov_write_3gp_udta_tag(ByteIOContext *pb, AVFormatContext *s,
1540
                                  const char *tag, const char *str)
1541
{
1542
    int64_t pos = url_ftell(pb);
1543
    AVMetadataTag *t = av_metadata_get(s->metadata, str, NULL, 0);
1544
    if (!t || !utf8len(t->value))
1545
        return 0;
1546
    put_be32(pb, 0);   /* size */
1547
    put_tag (pb, tag); /* type */
1548
    put_be32(pb, 0);   /* version + flags */
1549
    if (!strcmp(tag, "yrrc"))
1550
        put_be16(pb, atoi(t->value));
1551
    else {
1552
        put_be16(pb, language_code("eng")); /* language */
1553
        put_buffer(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
1554
        if (!strcmp(tag, "albm") &&
1555
            (t = av_metadata_get(s->metadata, "track", NULL, 0)))
1556
            put_byte(pb, atoi(t->value));
1557
    }
1558
    return updateSize(pb, pos);
1559
}
1560

    
1561
static int mov_write_chpl_tag(ByteIOContext *pb, AVFormatContext *s)
1562
{
1563
    int64_t pos = url_ftell(pb);
1564
    int i, nb_chapters = FFMIN(s->nb_chapters, 255);
1565

    
1566
    put_be32(pb, 0);            // size
1567
    put_tag (pb, "chpl");
1568
    put_be32(pb, 0x01000000);   // version + flags
1569
    put_be32(pb, 0);            // unknown
1570
    put_byte(pb, nb_chapters);
1571

    
1572
    for (i = 0; i < nb_chapters; i++) {
1573
        AVChapter *c = s->chapters[i];
1574
        AVMetadataTag *t;
1575
        put_be64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
1576

    
1577
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
1578
            int len = FFMIN(strlen(t->value), 255);
1579
            put_byte(pb, len);
1580
            put_buffer(pb, t->value, len);
1581
        } else
1582
            put_byte(pb, 0);
1583
    }
1584
    return updateSize(pb, pos);
1585
}
1586

    
1587
static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1588
                              AVFormatContext *s)
1589
{
1590
    ByteIOContext *pb_buf;
1591
    int i, ret, size;
1592
    uint8_t *buf;
1593

    
1594
    for (i = 0; i < s->nb_streams; i++)
1595
        if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1596
            return 0;
1597
        }
1598

    
1599
    ret = url_open_dyn_buf(&pb_buf);
1600
    if(ret < 0)
1601
        return ret;
1602

    
1603
        if (mov->mode & MODE_3GP) {
1604
            mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
1605
            mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1606
            mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1607
            mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1608
            mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1609
            mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1610
            mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1611
            mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
1612
        } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1613
            mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
1614
            mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
1615
            mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
1616
            mov_write_string_metadata(s, pb_buf, "\251day", "date"       , 0);
1617
            mov_write_string_metadata(s, pb_buf, "\251swr", "encoder"    , 0);
1618
            mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
1619
            mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
1620
            mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
1621
        } else {
1622
            /* iTunes meta data */
1623
            mov_write_meta_tag(pb_buf, mov, s);
1624
        }
1625

    
1626
        if (s->nb_chapters)
1627
            mov_write_chpl_tag(pb_buf, s);
1628

    
1629
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1630
        put_be32(pb, size+8);
1631
        put_tag(pb, "udta");
1632
        put_buffer(pb, buf, size);
1633
    }
1634
    av_free(buf);
1635

    
1636
    return 0;
1637
}
1638

    
1639
static void mov_write_psp_udta_tag(ByteIOContext *pb,
1640
                                  const char *str, const char *lang, int type)
1641
{
1642
    int len = utf8len(str)+1;
1643
    if(len<=0)
1644
        return;
1645
    put_be16(pb, len*2+10);            /* size */
1646
    put_be32(pb, type);                /* type */
1647
    put_be16(pb, language_code(lang)); /* language */
1648
    put_be16(pb, 0x01);                /* ? */
1649
    ascii_to_wc(pb, str);
1650
}
1651

    
1652
static int mov_write_uuidusmt_tag(ByteIOContext *pb, AVFormatContext *s)
1653
{
1654
    AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
1655
    int64_t pos, pos2;
1656

    
1657
    if (title) {
1658
        pos = url_ftell(pb);
1659
        put_be32(pb, 0); /* size placeholder*/
1660
        put_tag(pb, "uuid");
1661
        put_tag(pb, "USMT");
1662
        put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1663
        put_be32(pb, 0xbb88695c);
1664
        put_be32(pb, 0xfac9c740);
1665

    
1666
        pos2 = url_ftell(pb);
1667
        put_be32(pb, 0); /* size placeholder*/
1668
        put_tag(pb, "MTDT");
1669
        put_be16(pb, 4);
1670

    
1671
        // ?
1672
        put_be16(pb, 0x0C);                 /* size */
1673
        put_be32(pb, 0x0B);                 /* type */
1674
        put_be16(pb, language_code("und")); /* language */
1675
        put_be16(pb, 0x0);                  /* ? */
1676
        put_be16(pb, 0x021C);               /* data */
1677

    
1678
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1679
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1680
//        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);
1681
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1682

    
1683
        updateSize(pb, pos2);
1684
        return updateSize(pb, pos);
1685
    }
1686

    
1687
    return 0;
1688
}
1689

    
1690
static int mov_write_moov_tag(ByteIOContext *pb, MOVMuxContext *mov,
1691
                              AVFormatContext *s)
1692
{
1693
    int i;
1694
    int64_t pos = url_ftell(pb);
1695
    put_be32(pb, 0); /* size placeholder*/
1696
    put_tag(pb, "moov");
1697

    
1698
    for (i=0; i<mov->nb_streams; i++) {
1699
        if(mov->tracks[i].entry <= 0) continue;
1700

    
1701
        mov->tracks[i].time = mov->time;
1702
        mov->tracks[i].trackID = i+1;
1703
    }
1704

    
1705
    if (mov->chapter_track)
1706
        for (i=0; i<s->nb_streams; i++) {
1707
            mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
1708
            mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].trackID;
1709
        }
1710
    for (i = 0; i < mov->nb_streams; i++) {
1711
        if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
1712
            mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
1713
            mov->tracks[i].tref_id =
1714
                mov->tracks[mov->tracks[i].src_track].trackID;
1715
        }
1716
    }
1717

    
1718
    mov_write_mvhd_tag(pb, mov);
1719
    //mov_write_iods_tag(pb, mov);
1720
    for (i=0; i<mov->nb_streams; i++) {
1721
        if(mov->tracks[i].entry > 0) {
1722
            mov_write_trak_tag(pb, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
1723
        }
1724
    }
1725

    
1726
    if (mov->mode == MODE_PSP)
1727
        mov_write_uuidusmt_tag(pb, s);
1728
    else
1729
        mov_write_udta_tag(pb, mov, s);
1730

    
1731
    return updateSize(pb, pos);
1732
}
1733

    
1734
static int mov_write_mdat_tag(ByteIOContext *pb, MOVMuxContext *mov)
1735
{
1736
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1737
    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1738

    
1739
    mov->mdat_pos = url_ftell(pb);
1740
    put_be32(pb, 0); /* size placeholder*/
1741
    put_tag(pb, "mdat");
1742
    return 0;
1743
}
1744

    
1745
/* TODO: This needs to be more general */
1746
static int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
1747
{
1748
    MOVMuxContext *mov = s->priv_data;
1749
    int64_t pos = url_ftell(pb);
1750
    int has_h264 = 0, has_video = 0;
1751
    int minor = 0x200;
1752
    int i;
1753

    
1754
    for (i = 0; i < s->nb_streams; i++) {
1755
        AVStream *st = s->streams[i];
1756
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1757
            has_video = 1;
1758
        if (st->codec->codec_id == CODEC_ID_H264)
1759
            has_h264 = 1;
1760
    }
1761

    
1762
    put_be32(pb, 0); /* size */
1763
    put_tag(pb, "ftyp");
1764

    
1765
    if (mov->mode == MODE_3GP) {
1766
        put_tag(pb, has_h264 ? "3gp6"  : "3gp4");
1767
        minor =     has_h264 ?   0x100 :   0x200;
1768
    } else if (mov->mode & MODE_3G2) {
1769
        put_tag(pb, has_h264 ? "3g2b"  : "3g2a");
1770
        minor =     has_h264 ? 0x20000 : 0x10000;
1771
    }else if (mov->mode == MODE_PSP)
1772
        put_tag(pb, "MSNV");
1773
    else if (mov->mode == MODE_MP4)
1774
        put_tag(pb, "isom");
1775
    else if (mov->mode == MODE_IPOD)
1776
        put_tag(pb, has_video ? "M4V ":"M4A ");
1777
    else
1778
        put_tag(pb, "qt  ");
1779

    
1780
    put_be32(pb, minor);
1781

    
1782
    if(mov->mode == MODE_MOV)
1783
        put_tag(pb, "qt  ");
1784
    else{
1785
        put_tag(pb, "isom");
1786
        put_tag(pb, "iso2");
1787
        if(has_h264)
1788
            put_tag(pb, "avc1");
1789
    }
1790

    
1791
    if (mov->mode == MODE_3GP)
1792
        put_tag(pb, has_h264 ? "3gp6":"3gp4");
1793
    else if (mov->mode & MODE_3G2)
1794
        put_tag(pb, has_h264 ? "3g2b":"3g2a");
1795
    else if (mov->mode == MODE_PSP)
1796
        put_tag(pb, "MSNV");
1797
    else if (mov->mode == MODE_MP4)
1798
        put_tag(pb, "mp41");
1799
    return updateSize(pb, pos);
1800
}
1801

    
1802
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1803
{
1804
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1805
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1806
    int AudioRate = AudioCodec->sample_rate;
1807
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1808
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1809
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1810

    
1811
    put_be32(pb, 0x94); /* size */
1812
    put_tag(pb, "uuid");
1813
    put_tag(pb, "PROF");
1814

    
1815
    put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1816
    put_be32(pb, 0xbb88695c);
1817
    put_be32(pb, 0xfac9c740);
1818

    
1819
    put_be32(pb, 0x0);  /* ? */
1820
    put_be32(pb, 0x3);  /* 3 sections ? */
1821

    
1822
    put_be32(pb, 0x14); /* size */
1823
    put_tag(pb, "FPRF");
1824
    put_be32(pb, 0x0);  /* ? */
1825
    put_be32(pb, 0x0);  /* ? */
1826
    put_be32(pb, 0x0);  /* ? */
1827

    
1828
    put_be32(pb, 0x2c);  /* size */
1829
    put_tag(pb, "APRF");   /* audio */
1830
    put_be32(pb, 0x0);
1831
    put_be32(pb, 0x2);   /* TrackID */
1832
    put_tag(pb, "mp4a");
1833
    put_be32(pb, 0x20f);
1834
    put_be32(pb, 0x0);
1835
    put_be32(pb, audio_kbitrate);
1836
    put_be32(pb, audio_kbitrate);
1837
    put_be32(pb, AudioRate);
1838
    put_be32(pb, AudioCodec->channels);
1839

    
1840
    put_be32(pb, 0x34);  /* size */
1841
    put_tag(pb, "VPRF");   /* video */
1842
    put_be32(pb, 0x0);
1843
    put_be32(pb, 0x1);    /* TrackID */
1844
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1845
        put_tag(pb, "avc1");
1846
        put_be16(pb, 0x014D);
1847
        put_be16(pb, 0x0015);
1848
    } else {
1849
        put_tag(pb, "mp4v");
1850
        put_be16(pb, 0x0000);
1851
        put_be16(pb, 0x0103);
1852
    }
1853
    put_be32(pb, 0x0);
1854
    put_be32(pb, video_kbitrate);
1855
    put_be32(pb, video_kbitrate);
1856
    put_be32(pb, FrameRate);
1857
    put_be32(pb, FrameRate);
1858
    put_be16(pb, VideoCodec->width);
1859
    put_be16(pb, VideoCodec->height);
1860
    put_be32(pb, 0x010001); /* ? */
1861
}
1862

    
1863
static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
1864
{
1865
    uint32_t c = -1;
1866
    int i, closed_gop = 0;
1867

    
1868
    for (i = 0; i < pkt->size - 4; i++) {
1869
        c = (c<<8) + pkt->data[i];
1870
        if (c == 0x1b8) { // gop
1871
            closed_gop = pkt->data[i+4]>>6 & 0x01;
1872
        } else if (c == 0x100) { // pic
1873
            int temp_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
1874
            if (!temp_ref || closed_gop) // I picture is not reordered
1875
                *flags = MOV_SYNC_SAMPLE;
1876
            else
1877
                *flags = MOV_PARTIAL_SYNC_SAMPLE;
1878
            break;
1879
        }
1880
    }
1881
    return 0;
1882
}
1883

    
1884
int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1885
{
1886
    MOVMuxContext *mov = s->priv_data;
1887
    ByteIOContext *pb = s->pb;
1888
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1889
    AVCodecContext *enc = trk->enc;
1890
    unsigned int samplesInChunk = 0;
1891
    int size= pkt->size;
1892

    
1893
    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1894
    if (!size) return 0; /* Discard 0 sized packets */
1895

    
1896
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1897
        /* We must find out how many AMR blocks there are in one packet */
1898
        static uint16_t packed_size[16] =
1899
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1900
        int len = 0;
1901

    
1902
        while (len < size && samplesInChunk < 100) {
1903
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1904
            samplesInChunk++;
1905
        }
1906
        if(samplesInChunk > 1){
1907
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
1908
            return -1;
1909
        }
1910
    } else if (trk->sampleSize)
1911
        samplesInChunk = size/trk->sampleSize;
1912
    else
1913
        samplesInChunk = 1;
1914

    
1915
    /* copy extradata if it exists */
1916
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1917
        trk->vosLen = enc->extradata_size;
1918
        trk->vosData = av_malloc(trk->vosLen);
1919
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1920
    }
1921

    
1922
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1923
        /* from x264 or from bytestream h264 */
1924
        /* nal reformating needed */
1925
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1926
    } else {
1927
        put_buffer(pb, pkt->data, size);
1928
    }
1929

    
1930
    if ((enc->codec_id == CODEC_ID_DNXHD ||
1931
         enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
1932
        /* copy frame to create needed atoms */
1933
        trk->vosLen = size;
1934
        trk->vosData = av_malloc(size);
1935
        if (!trk->vosData)
1936
            return AVERROR(ENOMEM);
1937
        memcpy(trk->vosData, pkt->data, size);
1938
    }
1939

    
1940
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1941
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1942
        if (!trk->cluster)
1943
            return -1;
1944
    }
1945

    
1946
    trk->cluster[trk->entry].pos = url_ftell(pb) - size;
1947
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1948
    trk->cluster[trk->entry].size = size;
1949
    trk->cluster[trk->entry].entries = samplesInChunk;
1950
    trk->cluster[trk->entry].dts = pkt->dts;
1951
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1952

    
1953
    if (pkt->pts == AV_NOPTS_VALUE) {
1954
        av_log(s, AV_LOG_WARNING, "pts has no value\n");
1955
        pkt->pts = pkt->dts;
1956
    }
1957
    if (pkt->dts != pkt->pts)
1958
        trk->flags |= MOV_TRACK_CTTS;
1959
    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1960
    trk->cluster[trk->entry].flags = 0;
1961
    if (pkt->flags & AV_PKT_FLAG_KEY) {
1962
        if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO) {
1963
            mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
1964
            if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
1965
                trk->flags |= MOV_TRACK_STPS;
1966
        } else {
1967
            trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
1968
        }
1969
        if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
1970
            trk->hasKeyframes++;
1971
    }
1972
    trk->entry++;
1973
    trk->sampleCount += samplesInChunk;
1974
    mov->mdat_size += size;
1975

    
1976
    put_flush_packet(pb);
1977

    
1978
    if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
1979
        ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry);
1980
    return 0;
1981
}
1982

    
1983
// QuickTime chapters involve an additional text track with the chapter names
1984
// as samples, and a tref pointing from the other tracks to the chapter one.
1985
static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
1986
{
1987
    MOVMuxContext *mov = s->priv_data;
1988
    MOVTrack *track = &mov->tracks[tracknum];
1989
    AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
1990
    int i, len;
1991

    
1992
    track->mode = mov->mode;
1993
    track->tag = MKTAG('t','e','x','t');
1994
    track->timescale = MOV_TIMESCALE;
1995
    track->enc = avcodec_alloc_context();
1996
    track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
1997

    
1998
    for (i = 0; i < s->nb_chapters; i++) {
1999
        AVChapter *c = s->chapters[i];
2000
        AVMetadataTag *t;
2001

    
2002
        int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
2003
        pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
2004
        pkt.duration = end - pkt.dts;
2005

    
2006
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
2007
            len = strlen(t->value);
2008
            pkt.size = len+2;
2009
            pkt.data = av_malloc(pkt.size);
2010
            AV_WB16(pkt.data, len);
2011
            memcpy(pkt.data+2, t->value, len);
2012
            ff_mov_write_packet(s, &pkt);
2013
            av_freep(&pkt.data);
2014
        }
2015
    }
2016
}
2017

    
2018
static int mov_write_header(AVFormatContext *s)
2019
{
2020
    ByteIOContext *pb = s->pb;
2021
    MOVMuxContext *mov = s->priv_data;
2022
    int i, hint_track = 0;
2023

    
2024
    if (url_is_streamed(s->pb)) {
2025
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
2026
        return -1;
2027
    }
2028

    
2029
    /* Default mode == MP4 */
2030
    mov->mode = MODE_MP4;
2031

    
2032
    if (s->oformat != NULL) {
2033
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
2034
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
2035
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
2036
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
2037
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
2038

    
2039
        mov_write_ftyp_tag(pb,s);
2040
        if (mov->mode == MODE_PSP) {
2041
            if (s->nb_streams != 2) {
2042
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
2043
                return -1;
2044
            }
2045
            mov_write_uuidprof_tag(pb,s);
2046
        }
2047
    }
2048

    
2049
    mov->nb_streams = s->nb_streams;
2050
    if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
2051
        mov->chapter_track = mov->nb_streams++;
2052

    
2053
    if (s->flags & AVFMT_FLAG_RTP_HINT) {
2054
        /* Add hint tracks for each audio and video stream */
2055
        hint_track = mov->nb_streams;
2056
        for (i = 0; i < s->nb_streams; i++) {
2057
            AVStream *st = s->streams[i];
2058
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2059
                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2060
                mov->nb_streams++;
2061
            }
2062
        }
2063
    }
2064

    
2065
    mov->tracks = av_mallocz(mov->nb_streams*sizeof(*mov->tracks));
2066
    if (!mov->tracks)
2067
        return AVERROR(ENOMEM);
2068

    
2069
    for(i=0; i<s->nb_streams; i++){
2070
        AVStream *st= s->streams[i];
2071
        MOVTrack *track= &mov->tracks[i];
2072
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
2073

    
2074
        track->enc = st->codec;
2075
        track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
2076
        if (track->language < 0)
2077
            track->language = 0;
2078
        track->mode = mov->mode;
2079
        track->tag = mov_find_codec_tag(s, track);
2080
        if (!track->tag) {
2081
            av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
2082
                   "codec not currently supported in container\n", i);
2083
            goto error;
2084
        }
2085
        /* If hinting of this track is enabled by a later hint track,
2086
         * this is updated. */
2087
        track->hint_track = -1;
2088
        if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2089
            if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
2090
                track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
2091
                track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
2092
                if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
2093
                    av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
2094
                    goto error;
2095
                }
2096
                track->height = track->tag>>24 == 'n' ? 486 : 576;
2097
            }
2098
            track->timescale = st->codec->time_base.den;
2099
            if (track->mode == MODE_MOV && track->timescale > 100000)
2100
                av_log(s, AV_LOG_WARNING,
2101
                       "WARNING codec timebase is very high. If duration is too long,\n"
2102
                       "file may not be playable by quicktime. Specify a shorter timebase\n"
2103
                       "or choose different container.\n");
2104
        }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO){
2105
            track->timescale = st->codec->sample_rate;
2106
            if(!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
2107
                av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
2108
                goto error;
2109
            }else if(st->codec->frame_size > 1){ /* assume compressed audio */
2110
                track->audio_vbr = 1;
2111
            }else{
2112
                st->codec->frame_size = 1;
2113
                track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
2114
            }
2115
            if (track->mode != MODE_MOV) {
2116
                if (track->timescale > UINT16_MAX) {
2117
                    av_log(s, AV_LOG_ERROR, "track %d: output format does not support "
2118
                           "sample rate %dhz\n", i, track->timescale);
2119
                    goto error;
2120
                }
2121
                if (track->enc->codec_id == CODEC_ID_MP3 && track->timescale < 16000) {
2122
                    av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
2123
                           i, track->enc->sample_rate);
2124
                    goto error;
2125
                }
2126
            }
2127
        }else if(st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE){
2128
            track->timescale = st->codec->time_base.den;
2129
        }
2130
        if (!track->height)
2131
            track->height = st->codec->height;
2132

    
2133
        av_set_pts_info(st, 64, 1, track->timescale);
2134
    }
2135

    
2136
    mov_write_mdat_tag(pb, mov);
2137
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
2138

    
2139
    if (mov->chapter_track)
2140
        mov_create_chapter_track(s, mov->chapter_track);
2141

    
2142
    if (s->flags & AVFMT_FLAG_RTP_HINT) {
2143
        /* Initialize the hint tracks for each audio and video stream */
2144
        for (i = 0; i < s->nb_streams; i++) {
2145
            AVStream *st = s->streams[i];
2146
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2147
                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2148
                ff_mov_init_hinting(s, hint_track, i);
2149
                hint_track++;
2150
            }
2151
        }
2152
    }
2153

    
2154
    put_flush_packet(pb);
2155

    
2156
    return 0;
2157
 error:
2158
    av_freep(&mov->tracks);
2159
    return -1;
2160
}
2161

    
2162
static int mov_write_trailer(AVFormatContext *s)
2163
{
2164
    MOVMuxContext *mov = s->priv_data;
2165
    ByteIOContext *pb = s->pb;
2166
    int res = 0;
2167
    int i;
2168

    
2169
    int64_t moov_pos = url_ftell(pb);
2170

    
2171
    /* Write size of mdat tag */
2172
    if (mov->mdat_size+8 <= UINT32_MAX) {
2173
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
2174
        put_be32(pb, mov->mdat_size+8);
2175
    } else {
2176
        /* overwrite 'wide' placeholder atom */
2177
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
2178
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
2179
        put_tag(pb, "mdat");
2180
        put_be64(pb, mov->mdat_size+16);
2181
    }
2182
    url_fseek(pb, moov_pos, SEEK_SET);
2183

    
2184
    mov_write_moov_tag(pb, mov, s);
2185

    
2186
    if (mov->chapter_track)
2187
        av_freep(&mov->tracks[mov->chapter_track].enc);
2188

    
2189
    for (i=0; i<mov->nb_streams; i++) {
2190
        if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
2191
            ff_mov_close_hinting(&mov->tracks[i]);
2192
        av_freep(&mov->tracks[i].cluster);
2193

    
2194
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2195

    
2196
    }
2197

    
2198
    put_flush_packet(pb);
2199

    
2200
    av_freep(&mov->tracks);
2201

    
2202
    return res;
2203
}
2204

    
2205
#if CONFIG_MOV_MUXER
2206
AVOutputFormat mov_muxer = {
2207
    "mov",
2208
    NULL_IF_CONFIG_SMALL("MOV format"),
2209
    NULL,
2210
    "mov",
2211
    sizeof(MOVMuxContext),
2212
    CODEC_ID_AAC,
2213
    CODEC_ID_MPEG4,
2214
    mov_write_header,
2215
    ff_mov_write_packet,
2216
    mov_write_trailer,
2217
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
2218
    .codec_tag = (const AVCodecTag* const []){codec_movvideo_tags, codec_movaudio_tags, 0},
2219
};
2220
#endif
2221
#if CONFIG_TGP_MUXER
2222
AVOutputFormat tgp_muxer = {
2223
    "3gp",
2224
    NULL_IF_CONFIG_SMALL("3GP format"),
2225
    NULL,
2226
    "3gp",
2227
    sizeof(MOVMuxContext),
2228
    CODEC_ID_AMR_NB,
2229
    CODEC_ID_H263,
2230
    mov_write_header,
2231
    ff_mov_write_packet,
2232
    mov_write_trailer,
2233
    .flags = AVFMT_GLOBALHEADER,
2234
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2235
};
2236
#endif
2237
#if CONFIG_MP4_MUXER
2238
AVOutputFormat mp4_muxer = {
2239
    "mp4",
2240
    NULL_IF_CONFIG_SMALL("MP4 format"),
2241
    "application/mp4",
2242
    "mp4",
2243
    sizeof(MOVMuxContext),
2244
    CODEC_ID_AAC,
2245
    CODEC_ID_MPEG4,
2246
    mov_write_header,
2247
    ff_mov_write_packet,
2248
    mov_write_trailer,
2249
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
2250
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2251
};
2252
#endif
2253
#if CONFIG_PSP_MUXER
2254
AVOutputFormat psp_muxer = {
2255
    "psp",
2256
    NULL_IF_CONFIG_SMALL("PSP MP4 format"),
2257
    NULL,
2258
    "mp4,psp",
2259
    sizeof(MOVMuxContext),
2260
    CODEC_ID_AAC,
2261
    CODEC_ID_MPEG4,
2262
    mov_write_header,
2263
    ff_mov_write_packet,
2264
    mov_write_trailer,
2265
    .flags = AVFMT_GLOBALHEADER,
2266
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2267
};
2268
#endif
2269
#if CONFIG_TG2_MUXER
2270
AVOutputFormat tg2_muxer = {
2271
    "3g2",
2272
    NULL_IF_CONFIG_SMALL("3GP2 format"),
2273
    NULL,
2274
    "3g2",
2275
    sizeof(MOVMuxContext),
2276
    CODEC_ID_AMR_NB,
2277
    CODEC_ID_H263,
2278
    mov_write_header,
2279
    ff_mov_write_packet,
2280
    mov_write_trailer,
2281
    .flags = AVFMT_GLOBALHEADER,
2282
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2283
};
2284
#endif
2285
#if CONFIG_IPOD_MUXER
2286
AVOutputFormat ipod_muxer = {
2287
    "ipod",
2288
    NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
2289
    "application/mp4",
2290
    "m4v,m4a",
2291
    sizeof(MOVMuxContext),
2292
    CODEC_ID_AAC,
2293
    CODEC_ID_H264,
2294
    mov_write_header,
2295
    ff_mov_write_packet,
2296
    mov_write_trailer,
2297
    .flags = AVFMT_GLOBALHEADER,
2298
    .codec_tag = (const AVCodecTag* const []){codec_ipod_tags, 0},
2299
};
2300
#endif