Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ a7cc89e2

History | View | Annotate | Download (74 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_RGB24,   MKTAG('r','a','w',' '), 24 },
630
    { PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
631
    { PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
632
    { PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
633
    { PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
634
    { PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
635
};
636

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

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

    
650
    return tag;
651
}
652

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

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

    
687
    return tag;
688
}
689

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

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

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

    
714
    return tag;
715
}
716

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

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

    
742
    if (track->enc->extradata_size)
743
        put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
744

    
745
    return updateSize(pb, pos);
746
}
747

    
748
static int mov_write_video_tag(ByteIOContext *pb, MOVTrack *track)
749
{
750
    int64_t pos = url_ftell(pb);
751
    char compressor_name[32];
752

    
753
    put_be32(pb, 0); /* size */
754
    put_le32(pb, track->tag); // store it byteswapped
755
    put_be32(pb, 0); /* Reserved */
756
    put_be16(pb, 0); /* Reserved */
757
    put_be16(pb, 1); /* Data-reference index */
758

    
759
    put_be16(pb, 0); /* Codec stream version */
760
    put_be16(pb, 0); /* Codec stream revision (=0) */
761
    if (track->mode == MODE_MOV) {
762
        put_tag(pb, "FFMP"); /* Vendor */
763
        if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
764
            put_be32(pb, 0); /* Temporal Quality */
765
            put_be32(pb, 0x400); /* Spatial Quality = lossless*/
766
        } else {
767
            put_be32(pb, 0x200); /* Temporal Quality = normal */
768
            put_be32(pb, 0x200); /* Spatial Quality = normal */
769
        }
770
    } else {
771
        put_be32(pb, 0); /* Reserved */
772
        put_be32(pb, 0); /* Reserved */
773
        put_be32(pb, 0); /* Reserved */
774
    }
775
    put_be16(pb, track->enc->width); /* Video width */
776
    put_be16(pb, track->height); /* Video height */
777
    put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
778
    put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
779
    put_be32(pb, 0); /* Data size (= 0) */
780
    put_be16(pb, 1); /* Frame count (= 1) */
781

    
782
    memset(compressor_name,0,32);
783
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
784
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
785
        strncpy(compressor_name,track->enc->codec->name,31);
786
    put_byte(pb, strlen(compressor_name));
787
    put_buffer(pb, compressor_name, 31);
788

    
789
    if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
790
        put_be16(pb, track->enc->bits_per_coded_sample);
791
    else
792
        put_be16(pb, 0x18); /* Reserved */
793
    put_be16(pb, 0xffff); /* Reserved */
794
    if(track->tag == MKTAG('m','p','4','v'))
795
        mov_write_esds_tag(pb, track);
796
    else if(track->enc->codec_id == CODEC_ID_H263)
797
        mov_write_d263_tag(pb);
798
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
799
        mov_write_svq3_tag(pb);
800
    else if(track->enc->codec_id == CODEC_ID_DNXHD)
801
        mov_write_avid_tag(pb, track);
802
    else if(track->enc->codec_id == CODEC_ID_H264) {
803
        mov_write_avcc_tag(pb, track);
804
        if(track->mode == MODE_IPOD)
805
            mov_write_uuid_tag_ipod(pb);
806
    } else if(track->vosLen > 0)
807
        mov_write_glbl_tag(pb, track);
808

    
809
    return updateSize(pb, pos);
810
}
811

    
812
static int mov_write_rtp_tag(ByteIOContext *pb, MOVTrack *track)
813
{
814
    int64_t pos = url_ftell(pb);
815
    put_be32(pb, 0); /* size */
816
    put_tag(pb, "rtp ");
817
    put_be32(pb, 0); /* Reserved */
818
    put_be16(pb, 0); /* Reserved */
819
    put_be16(pb, 1); /* Data-reference index */
820

    
821
    put_be16(pb, 1); /* Hint track version */
822
    put_be16(pb, 1); /* Highest compatible version */
823
    put_be32(pb, track->max_packet_size); /* Max packet size */
824

    
825
    put_be32(pb, 12); /* size */
826
    put_tag(pb, "tims");
827
    put_be32(pb, track->timescale);
828

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

    
832
static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack *track)
833
{
834
    int64_t pos = url_ftell(pb);
835
    put_be32(pb, 0); /* size */
836
    put_tag(pb, "stsd");
837
    put_be32(pb, 0); /* version & flags */
838
    put_be32(pb, 1); /* entry count */
839
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
840
        mov_write_video_tag(pb, track);
841
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
842
        mov_write_audio_tag(pb, track);
843
    else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
844
        mov_write_subtitle_tag(pb, track);
845
    else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
846
        mov_write_rtp_tag(pb, track);
847
    return updateSize(pb, pos);
848
}
849

    
850
static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack *track)
851
{
852
    MOVStts *ctts_entries;
853
    uint32_t entries = 0;
854
    uint32_t atom_size;
855
    int i;
856

    
857
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
858
    ctts_entries[0].count = 1;
859
    ctts_entries[0].duration = track->cluster[0].cts;
860
    for (i=1; i<track->entry; i++) {
861
        if (track->cluster[i].cts == ctts_entries[entries].duration) {
862
            ctts_entries[entries].count++; /* compress */
863
        } else {
864
            entries++;
865
            ctts_entries[entries].duration = track->cluster[i].cts;
866
            ctts_entries[entries].count = 1;
867
        }
868
    }
869
    entries++; /* last one */
870
    atom_size = 16 + (entries * 8);
871
    put_be32(pb, atom_size); /* size */
872
    put_tag(pb, "ctts");
873
    put_be32(pb, 0); /* version & flags */
874
    put_be32(pb, entries); /* entry count */
875
    for (i=0; i<entries; i++) {
876
        put_be32(pb, ctts_entries[i].count);
877
        put_be32(pb, ctts_entries[i].duration);
878
    }
879
    av_free(ctts_entries);
880
    return atom_size;
881
}
882

    
883
/* Time to sample atom */
884
static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack *track)
885
{
886
    MOVStts *stts_entries;
887
    uint32_t entries = -1;
888
    uint32_t atom_size;
889
    int i;
890

    
891
    if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
892
        stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
893
        stts_entries[0].count = track->sampleCount;
894
        stts_entries[0].duration = 1;
895
        entries = 1;
896
    } else {
897
        stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
898
        for (i=0; i<track->entry; i++) {
899
            int64_t duration = i + 1 == track->entry ?
900
                track->trackDuration - track->cluster[i].dts + track->cluster[0].dts : /* readjusting */
901
                track->cluster[i+1].dts - track->cluster[i].dts;
902
            if (i && duration == stts_entries[entries].duration) {
903
                stts_entries[entries].count++; /* compress */
904
            } else {
905
                entries++;
906
                stts_entries[entries].duration = duration;
907
                stts_entries[entries].count = 1;
908
            }
909
        }
910
        entries++; /* last one */
911
    }
912
    atom_size = 16 + (entries * 8);
913
    put_be32(pb, atom_size); /* size */
914
    put_tag(pb, "stts");
915
    put_be32(pb, 0); /* version & flags */
916
    put_be32(pb, entries); /* entry count */
917
    for (i=0; i<entries; i++) {
918
        put_be32(pb, stts_entries[i].count);
919
        put_be32(pb, stts_entries[i].duration);
920
    }
921
    av_free(stts_entries);
922
    return atom_size;
923
}
924

    
925
static int mov_write_dref_tag(ByteIOContext *pb)
926
{
927
    put_be32(pb, 28); /* size */
928
    put_tag(pb, "dref");
929
    put_be32(pb, 0); /* version & flags */
930
    put_be32(pb, 1); /* entry count */
931

    
932
    put_be32(pb, 0xc); /* size */
933
    put_tag(pb, "url ");
934
    put_be32(pb, 1); /* version & flags */
935

    
936
    return 28;
937
}
938

    
939
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack *track)
940
{
941
    int64_t pos = url_ftell(pb);
942
    put_be32(pb, 0); /* size */
943
    put_tag(pb, "stbl");
944
    mov_write_stsd_tag(pb, track);
945
    mov_write_stts_tag(pb, track);
946
    if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
947
         track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
948
        track->hasKeyframes && track->hasKeyframes < track->entry)
949
        mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
950
    if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
951
        mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
952
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
953
        track->flags & MOV_TRACK_CTTS)
954
        mov_write_ctts_tag(pb, track);
955
    mov_write_stsc_tag(pb, track);
956
    mov_write_stsz_tag(pb, track);
957
    mov_write_stco_tag(pb, track);
958
    return updateSize(pb, pos);
959
}
960

    
961
static int mov_write_dinf_tag(ByteIOContext *pb)
962
{
963
    int64_t pos = url_ftell(pb);
964
    put_be32(pb, 0); /* size */
965
    put_tag(pb, "dinf");
966
    mov_write_dref_tag(pb);
967
    return updateSize(pb, pos);
968
}
969

    
970
static int mov_write_nmhd_tag(ByteIOContext *pb)
971
{
972
    put_be32(pb, 12);
973
    put_tag(pb, "nmhd");
974
    put_be32(pb, 0);
975
    return 12;
976
}
977

    
978
static int mov_write_gmhd_tag(ByteIOContext *pb)
979
{
980
    put_be32(pb, 0x20);   /* size */
981
    put_tag(pb, "gmhd");
982
    put_be32(pb, 0x18);   /* gmin size */
983
    put_tag(pb, "gmin");  /* generic media info */
984
    put_be32(pb, 0);      /* version & flags */
985
    put_be16(pb, 0x40);   /* graphics mode = */
986
    put_be16(pb, 0x8000); /* opColor (r?) */
987
    put_be16(pb, 0x8000); /* opColor (g?) */
988
    put_be16(pb, 0x8000); /* opColor (b?) */
989
    put_be16(pb, 0);      /* balance */
990
    put_be16(pb, 0);      /* reserved */
991
    return 0x20;
992
}
993

    
994
static int mov_write_smhd_tag(ByteIOContext *pb)
995
{
996
    put_be32(pb, 16); /* size */
997
    put_tag(pb, "smhd");
998
    put_be32(pb, 0); /* version & flags */
999
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
1000
    put_be16(pb, 0); /* reserved */
1001
    return 16;
1002
}
1003

    
1004
static int mov_write_vmhd_tag(ByteIOContext *pb)
1005
{
1006
    put_be32(pb, 0x14); /* size (always 0x14) */
1007
    put_tag(pb, "vmhd");
1008
    put_be32(pb, 0x01); /* version & flags */
1009
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
1010
    return 0x14;
1011
}
1012

    
1013
static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)
1014
{
1015
    const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1016
    int64_t pos = url_ftell(pb);
1017

    
1018
    if (!track) { /* no media --> data handler */
1019
        hdlr = "dhlr";
1020
        hdlr_type = "url ";
1021
        descr = "DataHandler";
1022
    } else {
1023
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1024
        if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1025
            hdlr_type = "vide";
1026
            descr = "VideoHandler";
1027
        } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1028
            hdlr_type = "soun";
1029
            descr = "SoundHandler";
1030
        } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1031
            if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
1032
            else                                      hdlr_type = "text";
1033
            descr = "SubtitleHandler";
1034
        } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1035
            hdlr_type = "hint";
1036
            descr = "HintHandler";
1037
        }
1038
    }
1039

    
1040
    put_be32(pb, 0); /* size */
1041
    put_tag(pb, "hdlr");
1042
    put_be32(pb, 0); /* Version & flags */
1043
    put_buffer(pb, hdlr, 4); /* handler */
1044
    put_tag(pb, hdlr_type); /* handler type */
1045
    put_be32(pb ,0); /* reserved */
1046
    put_be32(pb ,0); /* reserved */
1047
    put_be32(pb ,0); /* reserved */
1048
    if (!track || track->mode == MODE_MOV)
1049
        put_byte(pb, strlen(descr)); /* pascal string */
1050
    put_buffer(pb, descr, strlen(descr)); /* handler description */
1051
    if (track && track->mode != MODE_MOV)
1052
        put_byte(pb, 0); /* c string */
1053
    return updateSize(pb, pos);
1054
}
1055

    
1056
static int mov_write_hmhd_tag(ByteIOContext *pb)
1057
{
1058
    /* This atom must be present, but leaving the values at zero
1059
     * seems harmless. */
1060
    put_be32(pb, 28); /* size */
1061
    put_tag(pb, "hmhd");
1062
    put_be32(pb, 0); /* version, flags */
1063
    put_be16(pb, 0); /* maxPDUsize */
1064
    put_be16(pb, 0); /* avgPDUsize */
1065
    put_be32(pb, 0); /* maxbitrate */
1066
    put_be32(pb, 0); /* avgbitrate */
1067
    put_be32(pb, 0); /* reserved */
1068
    return 28;
1069
}
1070

    
1071
static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack *track)
1072
{
1073
    int64_t pos = url_ftell(pb);
1074
    put_be32(pb, 0); /* size */
1075
    put_tag(pb, "minf");
1076
    if(track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1077
        mov_write_vmhd_tag(pb);
1078
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1079
        mov_write_smhd_tag(pb);
1080
    else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1081
        if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb);
1082
        else                                      mov_write_nmhd_tag(pb);
1083
    } else if (track->tag == MKTAG('r','t','p',' ')) {
1084
        mov_write_hmhd_tag(pb);
1085
    }
1086
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1087
        mov_write_hdlr_tag(pb, NULL);
1088
    mov_write_dinf_tag(pb);
1089
    mov_write_stbl_tag(pb, track);
1090
    return updateSize(pb, pos);
1091
}
1092

    
1093
static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack *track)
1094
{
1095
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
1096

    
1097
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
1098
    put_tag(pb, "mdhd");
1099
    put_byte(pb, version);
1100
    put_be24(pb, 0); /* flags */
1101
    if (version == 1) {
1102
        put_be64(pb, track->time);
1103
        put_be64(pb, track->time);
1104
    } else {
1105
        put_be32(pb, track->time); /* creation time */
1106
        put_be32(pb, track->time); /* modification time */
1107
    }
1108
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
1109
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
1110
    put_be16(pb, track->language); /* language */
1111
    put_be16(pb, 0); /* reserved (quality) */
1112

    
1113
    if(version!=0 && track->mode == MODE_MOV){
1114
        av_log(NULL, AV_LOG_ERROR,
1115
            "FATAL error, file duration too long for timebase, this file will not be\n"
1116
            "playable with quicktime. Choose a different timebase or a different\n"
1117
            "container format\n");
1118
    }
1119

    
1120
    return 32;
1121
}
1122

    
1123
static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack *track)
1124
{
1125
    int64_t pos = url_ftell(pb);
1126
    put_be32(pb, 0); /* size */
1127
    put_tag(pb, "mdia");
1128
    mov_write_mdhd_tag(pb, track);
1129
    mov_write_hdlr_tag(pb, track);
1130
    mov_write_minf_tag(pb, track);
1131
    return updateSize(pb, pos);
1132
}
1133

    
1134
static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1135
{
1136
    int64_t duration = av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1137
                                      track->timescale, AV_ROUND_UP);
1138
    int version = duration < INT32_MAX ? 0 : 1;
1139

    
1140
    (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
1141
    put_tag(pb, "tkhd");
1142
    put_byte(pb, version);
1143
    put_be24(pb, 0xf); /* flags (track enabled) */
1144
    if (version == 1) {
1145
        put_be64(pb, track->time);
1146
        put_be64(pb, track->time);
1147
    } else {
1148
        put_be32(pb, track->time); /* creation time */
1149
        put_be32(pb, track->time); /* modification time */
1150
    }
1151
    put_be32(pb, track->trackID); /* track-id */
1152
    put_be32(pb, 0); /* reserved */
1153
    (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
1154

    
1155
    put_be32(pb, 0); /* reserved */
1156
    put_be32(pb, 0); /* reserved */
1157
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
1158
    /* Volume, only for audio */
1159
    if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1160
        put_be16(pb, 0x0100);
1161
    else
1162
        put_be16(pb, 0);
1163
    put_be16(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
    /* Track width and height, for visual only */
1177
    if(st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1178
              track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1179
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1180
        if(!sample_aspect_ratio || track->height != track->enc->height)
1181
            sample_aspect_ratio = 1;
1182
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1183
        put_be32(pb, track->height*0x10000);
1184
    }
1185
    else {
1186
        put_be32(pb, 0);
1187
        put_be32(pb, 0);
1188
    }
1189
    return 0x5c;
1190
}
1191

    
1192
// This box seems important for the psp playback ... without it the movie seems to hang
1193
static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
1194
{
1195
    put_be32(pb, 0x24); /* size  */
1196
    put_tag(pb, "edts");
1197
    put_be32(pb, 0x1c); /* size  */
1198
    put_tag(pb, "elst");
1199
    put_be32(pb, 0x0);
1200
    put_be32(pb, 0x1);
1201

    
1202
    /* duration   ... doesn't seem to effect psp */
1203
    put_be32(pb, av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1204
                                track->timescale, AV_ROUND_UP));
1205

    
1206
    put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
1207
    put_be32(pb, 0x00010000);
1208
    return 0x24;
1209
}
1210

    
1211
static int mov_write_tref_tag(ByteIOContext *pb, MOVTrack *track)
1212
{
1213
    put_be32(pb, 20);   // size
1214
    put_tag(pb, "tref");
1215
    put_be32(pb, 12);   // size (subatom)
1216
    put_le32(pb, track->tref_tag);
1217
    put_be32(pb, track->tref_id);
1218
    return 20;
1219
}
1220

    
1221
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1222
static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
1223
{
1224
    put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1225
    put_tag(pb, "uuid");
1226
    put_tag(pb, "USMT");
1227
    put_be32(pb, 0x21d24fce);
1228
    put_be32(pb, 0xbb88695c);
1229
    put_be32(pb, 0xfac9c740);
1230
    put_be32(pb, 0x1c);     // another size here!
1231
    put_tag(pb, "MTDT");
1232
    put_be32(pb, 0x00010012);
1233
    put_be32(pb, 0x0a);
1234
    put_be32(pb, 0x55c40000);
1235
    put_be32(pb, 0x1);
1236
    put_be32(pb, 0x0);
1237
    return 0x34;
1238
}
1239

    
1240
static int mov_write_udta_sdp(ByteIOContext *pb, AVCodecContext *ctx, int index)
1241
{
1242
    char buf[1000] = "";
1243
    int len;
1244

    
1245
    ff_sdp_write_media(buf, sizeof(buf), ctx, NULL, 0, 0);
1246
    av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", index);
1247
    len = strlen(buf);
1248

    
1249
    put_be32(pb, len + 24);
1250
    put_tag (pb, "udta");
1251
    put_be32(pb, len + 16);
1252
    put_tag (pb, "hnti");
1253
    put_be32(pb, len + 8);
1254
    put_tag (pb, "sdp ");
1255
    put_buffer(pb, buf, len);
1256
    return len + 24;
1257
}
1258

    
1259
static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack *track, AVStream *st)
1260
{
1261
    int64_t pos = url_ftell(pb);
1262
    put_be32(pb, 0); /* size */
1263
    put_tag(pb, "trak");
1264
    mov_write_tkhd_tag(pb, track, st);
1265
    if (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS)
1266
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1267
    if (track->tref_tag)
1268
        mov_write_tref_tag(pb, track);
1269
    mov_write_mdia_tag(pb, track);
1270
    if (track->mode == MODE_PSP)
1271
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1272
    if (track->tag == MKTAG('r','t','p',' '))
1273
        mov_write_udta_sdp(pb, track->rtp_ctx->streams[0]->codec, track->trackID);
1274
    return updateSize(pb, pos);
1275
}
1276

    
1277
#if 0
1278
/* TODO: Not sorted out, but not necessary either */
1279
static int mov_write_iods_tag(ByteIOContext *pb, MOVMuxContext *mov)
1280
{
1281
    put_be32(pb, 0x15); /* size */
1282
    put_tag(pb, "iods");
1283
    put_be32(pb, 0);    /* version & flags */
1284
    put_be16(pb, 0x1007);
1285
    put_byte(pb, 0);
1286
    put_be16(pb, 0x4fff);
1287
    put_be16(pb, 0xfffe);
1288
    put_be16(pb, 0x01ff);
1289
    return 0x15;
1290
}
1291
#endif
1292

    
1293
static int mov_write_mvhd_tag(ByteIOContext *pb, MOVMuxContext *mov)
1294
{
1295
    int maxTrackID = 1, i;
1296
    int64_t maxTrackLenTemp, maxTrackLen = 0;
1297
    int version;
1298

    
1299
    for (i=0; i<mov->nb_streams; i++) {
1300
        if(mov->tracks[i].entry > 0) {
1301
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration,
1302
                                             MOV_TIMESCALE,
1303
                                             mov->tracks[i].timescale,
1304
                                             AV_ROUND_UP);
1305
            if(maxTrackLen < maxTrackLenTemp)
1306
                maxTrackLen = maxTrackLenTemp;
1307
            if(maxTrackID < mov->tracks[i].trackID)
1308
                maxTrackID = mov->tracks[i].trackID;
1309
        }
1310
    }
1311

    
1312
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1313
    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1314
    put_tag(pb, "mvhd");
1315
    put_byte(pb, version);
1316
    put_be24(pb, 0); /* flags */
1317
    if (version == 1) {
1318
        put_be64(pb, mov->time);
1319
        put_be64(pb, mov->time);
1320
    } else {
1321
        put_be32(pb, mov->time); /* creation time */
1322
        put_be32(pb, mov->time); /* modification time */
1323
    }
1324
    put_be32(pb, MOV_TIMESCALE);
1325
    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1326

    
1327
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1328
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1329
    put_be16(pb, 0); /* reserved */
1330
    put_be32(pb, 0); /* reserved */
1331
    put_be32(pb, 0); /* reserved */
1332

    
1333
    /* Matrix structure */
1334
    put_be32(pb, 0x00010000); /* reserved */
1335
    put_be32(pb, 0x0); /* reserved */
1336
    put_be32(pb, 0x0); /* reserved */
1337
    put_be32(pb, 0x0); /* reserved */
1338
    put_be32(pb, 0x00010000); /* reserved */
1339
    put_be32(pb, 0x0); /* reserved */
1340
    put_be32(pb, 0x0); /* reserved */
1341
    put_be32(pb, 0x0); /* reserved */
1342
    put_be32(pb, 0x40000000); /* reserved */
1343

    
1344
    put_be32(pb, 0); /* reserved (preview time) */
1345
    put_be32(pb, 0); /* reserved (preview duration) */
1346
    put_be32(pb, 0); /* reserved (poster time) */
1347
    put_be32(pb, 0); /* reserved (selection time) */
1348
    put_be32(pb, 0); /* reserved (selection duration) */
1349
    put_be32(pb, 0); /* reserved (current time) */
1350
    put_be32(pb, maxTrackID+1); /* Next track id */
1351
    return 0x6c;
1352
}
1353

    
1354
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVMuxContext *mov,
1355
                                     AVFormatContext *s)
1356
{
1357
    put_be32(pb, 33); /* size */
1358
    put_tag(pb, "hdlr");
1359
    put_be32(pb, 0);
1360
    put_be32(pb, 0);
1361
    put_tag(pb, "mdir");
1362
    put_tag(pb, "appl");
1363
    put_be32(pb, 0);
1364
    put_be32(pb, 0);
1365
    put_byte(pb, 0);
1366
    return 33;
1367
}
1368

    
1369
/* helper function to write a data tag with the specified string as data */
1370
static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int lang, int long_style)
1371
{
1372
    if(long_style){
1373
        int size = 16 + strlen(data);
1374
        put_be32(pb, size); /* size */
1375
        put_tag(pb, "data");
1376
        put_be32(pb, 1);
1377
        put_be32(pb, 0);
1378
        put_buffer(pb, data, strlen(data));
1379
        return size;
1380
    }else{
1381
        if (!lang)
1382
            lang = ff_mov_iso639_to_lang("und", 1);
1383
        put_be16(pb, strlen(data)); /* string length */
1384
        put_be16(pb, lang);
1385
        put_buffer(pb, data, strlen(data));
1386
        return strlen(data) + 4;
1387
    }
1388
}
1389

    
1390
static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int lang, int long_style){
1391
    int size = 0;
1392
    if (value && value[0]) {
1393
        int64_t pos = url_ftell(pb);
1394
        put_be32(pb, 0); /* size */
1395
        put_tag(pb, name);
1396
        mov_write_string_data_tag(pb, value, lang, long_style);
1397
        size= updateSize(pb, pos);
1398
    }
1399
    return size;
1400
}
1401

    
1402
static int mov_write_string_metadata(AVFormatContext *s, ByteIOContext *pb,
1403
                                     const char *name, const char *tag,
1404
                                     int long_style)
1405
{
1406
    int l, lang = 0, len, len2;
1407
    AVMetadataTag *t, *t2 = NULL;
1408
    char tag2[16];
1409

    
1410
    if (!(t = av_metadata_get(s->metadata, tag, NULL, 0)))
1411
        return 0;
1412

    
1413
    len = strlen(t->key);
1414
    snprintf(tag2, sizeof(tag2), "%s-", tag);
1415
    while ((t2 = av_metadata_get(s->metadata, tag2, t2, AV_METADATA_IGNORE_SUFFIX))) {
1416
        len2 = strlen(t2->key);
1417
        if (len2 == len+4 && !strcmp(t->value, t2->value)
1418
            && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 1)) >= 0) {
1419
            lang = l;
1420
            break;
1421
        }
1422
    }
1423
    return mov_write_string_tag(pb, name, t->value, lang, long_style);
1424
}
1425

    
1426
/* iTunes track number */
1427
static int mov_write_trkn_tag(ByteIOContext *pb, MOVMuxContext *mov,
1428
                              AVFormatContext *s)
1429
{
1430
    AVMetadataTag *t = av_metadata_get(s->metadata, "track", NULL, 0);
1431
    int size = 0, track = t ? atoi(t->value) : 0;
1432
    if (track) {
1433
        put_be32(pb, 32); /* size */
1434
        put_tag(pb, "trkn");
1435
            put_be32(pb, 24); /* size */
1436
            put_tag(pb, "data");
1437
            put_be32(pb, 0);        // 8 bytes empty
1438
            put_be32(pb, 0);
1439
            put_be16(pb, 0);        // empty
1440
            put_be16(pb, track);    // track number
1441
            put_be16(pb, 0);        // total track number
1442
            put_be16(pb, 0);        // empty
1443
        size = 32;
1444
    }
1445
    return size;
1446
}
1447

    
1448
/* iTunes meta data list */
1449
static int mov_write_ilst_tag(ByteIOContext *pb, MOVMuxContext *mov,
1450
                              AVFormatContext *s)
1451
{
1452
    int64_t pos = url_ftell(pb);
1453
    put_be32(pb, 0); /* size */
1454
    put_tag(pb, "ilst");
1455
    mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1456
    mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
1457
    mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
1458
    mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1459
    mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1460
    mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
1461
    mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1462
    mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1463
    mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1464
    mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1465
    mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
1466
    mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
1467
    mov_write_string_metadata(s, pb, "desc",    "description",1);
1468
    mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
1469
    mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
1470
    mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
1471
    mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
1472
    mov_write_trkn_tag(pb, mov, s);
1473
    return updateSize(pb, pos);
1474
}
1475

    
1476
/* iTunes meta data tag */
1477
static int mov_write_meta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1478
                              AVFormatContext *s)
1479
{
1480
    int size = 0;
1481
    int64_t pos = url_ftell(pb);
1482
    put_be32(pb, 0); /* size */
1483
    put_tag(pb, "meta");
1484
    put_be32(pb, 0);
1485
    mov_write_itunes_hdlr_tag(pb, mov, s);
1486
    mov_write_ilst_tag(pb, mov, s);
1487
    size = updateSize(pb, pos);
1488
    return size;
1489
}
1490

    
1491
static int utf8len(const uint8_t *b)
1492
{
1493
    int len=0;
1494
    int val;
1495
    while(*b){
1496
        GET_UTF8(val, *b++, return -1;)
1497
        len++;
1498
    }
1499
    return len;
1500
}
1501

    
1502
static int ascii_to_wc(ByteIOContext *pb, const uint8_t *b)
1503
{
1504
    int val;
1505
    while(*b){
1506
        GET_UTF8(val, *b++, return -1;)
1507
        put_be16(pb, val);
1508
    }
1509
    put_be16(pb, 0x00);
1510
    return 0;
1511
}
1512

    
1513
static uint16_t language_code(const char *str)
1514
{
1515
    return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1516
}
1517

    
1518
static int mov_write_3gp_udta_tag(ByteIOContext *pb, AVFormatContext *s,
1519
                                  const char *tag, const char *str)
1520
{
1521
    int64_t pos = url_ftell(pb);
1522
    AVMetadataTag *t = av_metadata_get(s->metadata, str, NULL, 0);
1523
    if (!t || !utf8len(t->value))
1524
        return 0;
1525
    put_be32(pb, 0);   /* size */
1526
    put_tag (pb, tag); /* type */
1527
    put_be32(pb, 0);   /* version + flags */
1528
    if (!strcmp(tag, "yrrc"))
1529
        put_be16(pb, atoi(t->value));
1530
    else {
1531
        put_be16(pb, language_code("eng")); /* language */
1532
        put_buffer(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
1533
        if (!strcmp(tag, "albm") &&
1534
            (t = av_metadata_get(s->metadata, "track", NULL, 0)))
1535
            put_byte(pb, atoi(t->value));
1536
    }
1537
    return updateSize(pb, pos);
1538
}
1539

    
1540
static int mov_write_chpl_tag(ByteIOContext *pb, AVFormatContext *s)
1541
{
1542
    int64_t pos = url_ftell(pb);
1543
    int i, nb_chapters = FFMIN(s->nb_chapters, 255);
1544

    
1545
    put_be32(pb, 0);            // size
1546
    put_tag (pb, "chpl");
1547
    put_be32(pb, 0x01000000);   // version + flags
1548
    put_be32(pb, 0);            // unknown
1549
    put_byte(pb, nb_chapters);
1550

    
1551
    for (i = 0; i < nb_chapters; i++) {
1552
        AVChapter *c = s->chapters[i];
1553
        AVMetadataTag *t;
1554
        put_be64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
1555

    
1556
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
1557
            int len = FFMIN(strlen(t->value), 255);
1558
            put_byte(pb, len);
1559
            put_buffer(pb, t->value, len);
1560
        } else
1561
            put_byte(pb, 0);
1562
    }
1563
    return updateSize(pb, pos);
1564
}
1565

    
1566
static int mov_write_udta_tag(ByteIOContext *pb, MOVMuxContext *mov,
1567
                              AVFormatContext *s)
1568
{
1569
    ByteIOContext *pb_buf;
1570
    int i, ret, size;
1571
    uint8_t *buf;
1572

    
1573
    for (i = 0; i < s->nb_streams; i++)
1574
        if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1575
            return 0;
1576
        }
1577

    
1578
    ret = url_open_dyn_buf(&pb_buf);
1579
    if(ret < 0)
1580
        return ret;
1581

    
1582
        if (mov->mode & MODE_3GP) {
1583
            mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
1584
            mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1585
            mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1586
            mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1587
            mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1588
            mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1589
            mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1590
            mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
1591
        } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1592
            mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
1593
            mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
1594
            mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
1595
            mov_write_string_metadata(s, pb_buf, "\251day", "date"       , 0);
1596
            mov_write_string_tag(pb_buf, "\251enc", LIBAVFORMAT_IDENT, 0, 0);
1597
            mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
1598
            mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
1599
            mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
1600
        } else {
1601
            /* iTunes meta data */
1602
            mov_write_meta_tag(pb_buf, mov, s);
1603
        }
1604

    
1605
        if (s->nb_chapters)
1606
            mov_write_chpl_tag(pb_buf, s);
1607

    
1608
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1609
        put_be32(pb, size+8);
1610
        put_tag(pb, "udta");
1611
        put_buffer(pb, buf, size);
1612
        av_free(buf);
1613
    }
1614

    
1615
    return 0;
1616
}
1617

    
1618
static void mov_write_psp_udta_tag(ByteIOContext *pb,
1619
                                  const char *str, const char *lang, int type)
1620
{
1621
    int len = utf8len(str)+1;
1622
    if(len<=0)
1623
        return;
1624
    put_be16(pb, len*2+10);            /* size */
1625
    put_be32(pb, type);                /* type */
1626
    put_be16(pb, language_code(lang)); /* language */
1627
    put_be16(pb, 0x01);                /* ? */
1628
    ascii_to_wc(pb, str);
1629
}
1630

    
1631
static int mov_write_uuidusmt_tag(ByteIOContext *pb, AVFormatContext *s)
1632
{
1633
    AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
1634
    int64_t pos, pos2;
1635

    
1636
    if (title) {
1637
        pos = url_ftell(pb);
1638
        put_be32(pb, 0); /* size placeholder*/
1639
        put_tag(pb, "uuid");
1640
        put_tag(pb, "USMT");
1641
        put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1642
        put_be32(pb, 0xbb88695c);
1643
        put_be32(pb, 0xfac9c740);
1644

    
1645
        pos2 = url_ftell(pb);
1646
        put_be32(pb, 0); /* size placeholder*/
1647
        put_tag(pb, "MTDT");
1648
        put_be16(pb, 4);
1649

    
1650
        // ?
1651
        put_be16(pb, 0x0C);                 /* size */
1652
        put_be32(pb, 0x0B);                 /* type */
1653
        put_be16(pb, language_code("und")); /* language */
1654
        put_be16(pb, 0x0);                  /* ? */
1655
        put_be16(pb, 0x021C);               /* data */
1656

    
1657
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1658
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1659
//        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);
1660
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1661

    
1662
        updateSize(pb, pos2);
1663
        return updateSize(pb, pos);
1664
    }
1665

    
1666
    return 0;
1667
}
1668

    
1669
static int mov_write_moov_tag(ByteIOContext *pb, MOVMuxContext *mov,
1670
                              AVFormatContext *s)
1671
{
1672
    int i;
1673
    int64_t pos = url_ftell(pb);
1674
    put_be32(pb, 0); /* size placeholder*/
1675
    put_tag(pb, "moov");
1676

    
1677
    for (i=0; i<mov->nb_streams; i++) {
1678
        if(mov->tracks[i].entry <= 0) continue;
1679

    
1680
        mov->tracks[i].time = mov->time;
1681
        mov->tracks[i].trackID = i+1;
1682
    }
1683

    
1684
    if (mov->chapter_track)
1685
        for (i=0; i<s->nb_streams; i++) {
1686
            mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
1687
            mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].trackID;
1688
        }
1689
    for (i = 0; i < mov->nb_streams; i++) {
1690
        if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
1691
            mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
1692
            mov->tracks[i].tref_id =
1693
                mov->tracks[mov->tracks[i].src_track].trackID;
1694
        }
1695
    }
1696

    
1697
    mov_write_mvhd_tag(pb, mov);
1698
    //mov_write_iods_tag(pb, mov);
1699
    for (i=0; i<mov->nb_streams; i++) {
1700
        if(mov->tracks[i].entry > 0) {
1701
            mov_write_trak_tag(pb, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
1702
        }
1703
    }
1704

    
1705
    if (mov->mode == MODE_PSP)
1706
        mov_write_uuidusmt_tag(pb, s);
1707
    else
1708
        mov_write_udta_tag(pb, mov, s);
1709

    
1710
    return updateSize(pb, pos);
1711
}
1712

    
1713
static int mov_write_mdat_tag(ByteIOContext *pb, MOVMuxContext *mov)
1714
{
1715
    put_be32(pb, 8);    // placeholder for extended size field (64 bit)
1716
    put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1717

    
1718
    mov->mdat_pos = url_ftell(pb);
1719
    put_be32(pb, 0); /* size placeholder*/
1720
    put_tag(pb, "mdat");
1721
    return 0;
1722
}
1723

    
1724
/* TODO: This needs to be more general */
1725
static int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
1726
{
1727
    MOVMuxContext *mov = s->priv_data;
1728
    int64_t pos = url_ftell(pb);
1729
    int has_h264 = 0, has_video = 0;
1730
    int minor = 0x200;
1731
    int i;
1732

    
1733
    for (i = 0; i < s->nb_streams; i++) {
1734
        AVStream *st = s->streams[i];
1735
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1736
            has_video = 1;
1737
        if (st->codec->codec_id == CODEC_ID_H264)
1738
            has_h264 = 1;
1739
    }
1740

    
1741
    put_be32(pb, 0); /* size */
1742
    put_tag(pb, "ftyp");
1743

    
1744
    if (mov->mode == MODE_3GP) {
1745
        put_tag(pb, has_h264 ? "3gp6"  : "3gp4");
1746
        minor =     has_h264 ?   0x100 :   0x200;
1747
    } else if (mov->mode & MODE_3G2) {
1748
        put_tag(pb, has_h264 ? "3g2b"  : "3g2a");
1749
        minor =     has_h264 ? 0x20000 : 0x10000;
1750
    }else if (mov->mode == MODE_PSP)
1751
        put_tag(pb, "MSNV");
1752
    else if (mov->mode == MODE_MP4)
1753
        put_tag(pb, "isom");
1754
    else if (mov->mode == MODE_IPOD)
1755
        put_tag(pb, has_video ? "M4V ":"M4A ");
1756
    else
1757
        put_tag(pb, "qt  ");
1758

    
1759
    put_be32(pb, minor);
1760

    
1761
    if(mov->mode == MODE_MOV)
1762
        put_tag(pb, "qt  ");
1763
    else{
1764
        put_tag(pb, "isom");
1765
        put_tag(pb, "iso2");
1766
        if(has_h264)
1767
            put_tag(pb, "avc1");
1768
    }
1769

    
1770
    if (mov->mode == MODE_3GP)
1771
        put_tag(pb, has_h264 ? "3gp6":"3gp4");
1772
    else if (mov->mode & MODE_3G2)
1773
        put_tag(pb, has_h264 ? "3g2b":"3g2a");
1774
    else if (mov->mode == MODE_PSP)
1775
        put_tag(pb, "MSNV");
1776
    else if (mov->mode == MODE_MP4)
1777
        put_tag(pb, "mp41");
1778
    return updateSize(pb, pos);
1779
}
1780

    
1781
static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1782
{
1783
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1784
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1785
    int AudioRate = AudioCodec->sample_rate;
1786
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1787
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1788
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1789

    
1790
    put_be32(pb, 0x94); /* size */
1791
    put_tag(pb, "uuid");
1792
    put_tag(pb, "PROF");
1793

    
1794
    put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1795
    put_be32(pb, 0xbb88695c);
1796
    put_be32(pb, 0xfac9c740);
1797

    
1798
    put_be32(pb, 0x0);  /* ? */
1799
    put_be32(pb, 0x3);  /* 3 sections ? */
1800

    
1801
    put_be32(pb, 0x14); /* size */
1802
    put_tag(pb, "FPRF");
1803
    put_be32(pb, 0x0);  /* ? */
1804
    put_be32(pb, 0x0);  /* ? */
1805
    put_be32(pb, 0x0);  /* ? */
1806

    
1807
    put_be32(pb, 0x2c);  /* size */
1808
    put_tag(pb, "APRF");   /* audio */
1809
    put_be32(pb, 0x0);
1810
    put_be32(pb, 0x2);   /* TrackID */
1811
    put_tag(pb, "mp4a");
1812
    put_be32(pb, 0x20f);
1813
    put_be32(pb, 0x0);
1814
    put_be32(pb, audio_kbitrate);
1815
    put_be32(pb, audio_kbitrate);
1816
    put_be32(pb, AudioRate);
1817
    put_be32(pb, AudioCodec->channels);
1818

    
1819
    put_be32(pb, 0x34);  /* size */
1820
    put_tag(pb, "VPRF");   /* video */
1821
    put_be32(pb, 0x0);
1822
    put_be32(pb, 0x1);    /* TrackID */
1823
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1824
        put_tag(pb, "avc1");
1825
        put_be16(pb, 0x014D);
1826
        put_be16(pb, 0x0015);
1827
    } else {
1828
        put_tag(pb, "mp4v");
1829
        put_be16(pb, 0x0000);
1830
        put_be16(pb, 0x0103);
1831
    }
1832
    put_be32(pb, 0x0);
1833
    put_be32(pb, video_kbitrate);
1834
    put_be32(pb, video_kbitrate);
1835
    put_be32(pb, FrameRate);
1836
    put_be32(pb, FrameRate);
1837
    put_be16(pb, VideoCodec->width);
1838
    put_be16(pb, VideoCodec->height);
1839
    put_be32(pb, 0x010001); /* ? */
1840
}
1841

    
1842
static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
1843
{
1844
    uint32_t c = -1;
1845
    int i, closed_gop = 0;
1846

    
1847
    for (i = 0; i < pkt->size - 4; i++) {
1848
        c = (c<<8) + pkt->data[i];
1849
        if (c == 0x1b8) { // gop
1850
            closed_gop = pkt->data[i+4]>>6 & 0x01;
1851
        } else if (c == 0x100) { // pic
1852
            int temp_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
1853
            if (!temp_ref || closed_gop) // I picture is not reordered
1854
                *flags = MOV_SYNC_SAMPLE;
1855
            else
1856
                *flags = MOV_PARTIAL_SYNC_SAMPLE;
1857
            break;
1858
        }
1859
    }
1860
    return 0;
1861
}
1862

    
1863
int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1864
{
1865
    MOVMuxContext *mov = s->priv_data;
1866
    ByteIOContext *pb = s->pb;
1867
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1868
    AVCodecContext *enc = trk->enc;
1869
    unsigned int samplesInChunk = 0;
1870
    int size= pkt->size;
1871

    
1872
    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1873
    if (!size) return 0; /* Discard 0 sized packets */
1874

    
1875
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1876
        /* We must find out how many AMR blocks there are in one packet */
1877
        static uint16_t packed_size[16] =
1878
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1879
        int len = 0;
1880

    
1881
        while (len < size && samplesInChunk < 100) {
1882
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1883
            samplesInChunk++;
1884
        }
1885
        if(samplesInChunk > 1){
1886
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
1887
            return -1;
1888
        }
1889
    } else if (trk->sampleSize)
1890
        samplesInChunk = size/trk->sampleSize;
1891
    else
1892
        samplesInChunk = 1;
1893

    
1894
    /* copy extradata if it exists */
1895
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1896
        trk->vosLen = enc->extradata_size;
1897
        trk->vosData = av_malloc(trk->vosLen);
1898
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1899
    }
1900

    
1901
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1902
        /* from x264 or from bytestream h264 */
1903
        /* nal reformating needed */
1904
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1905
    } else {
1906
        put_buffer(pb, pkt->data, size);
1907
    }
1908

    
1909
    if ((enc->codec_id == CODEC_ID_DNXHD ||
1910
         enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
1911
        /* copy frame to create needed atoms */
1912
        trk->vosLen = size;
1913
        trk->vosData = av_malloc(size);
1914
        if (!trk->vosData)
1915
            return AVERROR(ENOMEM);
1916
        memcpy(trk->vosData, pkt->data, size);
1917
    }
1918

    
1919
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1920
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1921
        if (!trk->cluster)
1922
            return -1;
1923
    }
1924

    
1925
    trk->cluster[trk->entry].pos = url_ftell(pb) - size;
1926
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1927
    trk->cluster[trk->entry].size = size;
1928
    trk->cluster[trk->entry].entries = samplesInChunk;
1929
    trk->cluster[trk->entry].dts = pkt->dts;
1930
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1931

    
1932
    if (pkt->pts == AV_NOPTS_VALUE) {
1933
        av_log(s, AV_LOG_WARNING, "pts has no value\n");
1934
        pkt->pts = pkt->dts;
1935
    }
1936
    if (pkt->dts != pkt->pts)
1937
        trk->flags |= MOV_TRACK_CTTS;
1938
    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1939
    trk->cluster[trk->entry].flags = 0;
1940
    if (pkt->flags & AV_PKT_FLAG_KEY) {
1941
        if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO) {
1942
            mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
1943
            if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
1944
                trk->flags |= MOV_TRACK_STPS;
1945
        } else {
1946
            trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
1947
        }
1948
        if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
1949
            trk->hasKeyframes++;
1950
    }
1951
    trk->entry++;
1952
    trk->sampleCount += samplesInChunk;
1953
    mov->mdat_size += size;
1954

    
1955
    put_flush_packet(pb);
1956

    
1957
    if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
1958
        ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry);
1959
    return 0;
1960
}
1961

    
1962
// QuickTime chapters involve an additional text track with the chapter names
1963
// as samples, and a tref pointing from the other tracks to the chapter one.
1964
static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
1965
{
1966
    MOVMuxContext *mov = s->priv_data;
1967
    MOVTrack *track = &mov->tracks[tracknum];
1968
    AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
1969
    int i, len;
1970

    
1971
    track->mode = mov->mode;
1972
    track->tag = MKTAG('t','e','x','t');
1973
    track->timescale = MOV_TIMESCALE;
1974
    track->enc = avcodec_alloc_context();
1975
    track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
1976

    
1977
    for (i = 0; i < s->nb_chapters; i++) {
1978
        AVChapter *c = s->chapters[i];
1979
        AVMetadataTag *t;
1980

    
1981
        int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
1982
        pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
1983
        pkt.duration = end - pkt.dts;
1984

    
1985
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
1986
            len = strlen(t->value);
1987
            pkt.size = len+2;
1988
            pkt.data = av_malloc(pkt.size);
1989
            AV_WB16(pkt.data, len);
1990
            memcpy(pkt.data+2, t->value, len);
1991
            ff_mov_write_packet(s, &pkt);
1992
            av_freep(&pkt.data);
1993
        }
1994
    }
1995
}
1996

    
1997
static int mov_write_header(AVFormatContext *s)
1998
{
1999
    ByteIOContext *pb = s->pb;
2000
    MOVMuxContext *mov = s->priv_data;
2001
    int i, hint_track = 0;
2002

    
2003
    if (url_is_streamed(s->pb)) {
2004
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
2005
        return -1;
2006
    }
2007

    
2008
    /* Default mode == MP4 */
2009
    mov->mode = MODE_MP4;
2010

    
2011
    if (s->oformat != NULL) {
2012
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
2013
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
2014
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
2015
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
2016
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
2017

    
2018
        mov_write_ftyp_tag(pb,s);
2019
        if (mov->mode == MODE_PSP) {
2020
            if (s->nb_streams != 2) {
2021
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
2022
                return -1;
2023
            }
2024
            mov_write_uuidprof_tag(pb,s);
2025
        }
2026
    }
2027

    
2028
    mov->nb_streams = s->nb_streams;
2029
    if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
2030
        mov->chapter_track = mov->nb_streams++;
2031

    
2032
    if (s->flags & AVFMT_FLAG_RTP_HINT) {
2033
        /* Add hint tracks for each audio and video stream */
2034
        hint_track = mov->nb_streams;
2035
        for (i = 0; i < s->nb_streams; i++) {
2036
            AVStream *st = s->streams[i];
2037
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2038
                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2039
                mov->nb_streams++;
2040
            }
2041
        }
2042
    }
2043

    
2044
    mov->tracks = av_mallocz(mov->nb_streams*sizeof(*mov->tracks));
2045
    if (!mov->tracks)
2046
        return AVERROR(ENOMEM);
2047

    
2048
    for(i=0; i<s->nb_streams; i++){
2049
        AVStream *st= s->streams[i];
2050
        MOVTrack *track= &mov->tracks[i];
2051
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
2052

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

    
2112
        av_set_pts_info(st, 64, 1, track->timescale);
2113
    }
2114

    
2115
    mov_write_mdat_tag(pb, mov);
2116
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
2117

    
2118
    if (mov->chapter_track)
2119
        mov_create_chapter_track(s, mov->chapter_track);
2120

    
2121
    if (s->flags & AVFMT_FLAG_RTP_HINT) {
2122
        /* Initialize the hint tracks for each audio and video stream */
2123
        for (i = 0; i < s->nb_streams; i++) {
2124
            AVStream *st = s->streams[i];
2125
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2126
                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2127
                ff_mov_init_hinting(s, hint_track, i);
2128
                hint_track++;
2129
            }
2130
        }
2131
    }
2132

    
2133
    put_flush_packet(pb);
2134

    
2135
    return 0;
2136
 error:
2137
    av_freep(&mov->tracks);
2138
    return -1;
2139
}
2140

    
2141
static int mov_write_trailer(AVFormatContext *s)
2142
{
2143
    MOVMuxContext *mov = s->priv_data;
2144
    ByteIOContext *pb = s->pb;
2145
    int res = 0;
2146
    int i;
2147

    
2148
    int64_t moov_pos = url_ftell(pb);
2149

    
2150
    /* Write size of mdat tag */
2151
    if (mov->mdat_size+8 <= UINT32_MAX) {
2152
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
2153
        put_be32(pb, mov->mdat_size+8);
2154
    } else {
2155
        /* overwrite 'wide' placeholder atom */
2156
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
2157
        put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
2158
        put_tag(pb, "mdat");
2159
        put_be64(pb, mov->mdat_size+16);
2160
    }
2161
    url_fseek(pb, moov_pos, SEEK_SET);
2162

    
2163
    mov_write_moov_tag(pb, mov, s);
2164

    
2165
    if (mov->chapter_track)
2166
        av_freep(&mov->tracks[mov->chapter_track].enc);
2167

    
2168
    for (i=0; i<mov->nb_streams; i++) {
2169
        if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
2170
            ff_mov_close_hinting(&mov->tracks[i]);
2171
        av_freep(&mov->tracks[i].cluster);
2172

    
2173
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2174

    
2175
    }
2176

    
2177
    put_flush_packet(pb);
2178

    
2179
    av_freep(&mov->tracks);
2180

    
2181
    return res;
2182
}
2183

    
2184
#if CONFIG_MOV_MUXER
2185
AVOutputFormat mov_muxer = {
2186
    "mov",
2187
    NULL_IF_CONFIG_SMALL("MOV format"),
2188
    NULL,
2189
    "mov",
2190
    sizeof(MOVMuxContext),
2191
    CODEC_ID_AAC,
2192
    CODEC_ID_MPEG4,
2193
    mov_write_header,
2194
    ff_mov_write_packet,
2195
    mov_write_trailer,
2196
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
2197
    .codec_tag = (const AVCodecTag* const []){codec_movvideo_tags, codec_movaudio_tags, 0},
2198
};
2199
#endif
2200
#if CONFIG_TGP_MUXER
2201
AVOutputFormat tgp_muxer = {
2202
    "3gp",
2203
    NULL_IF_CONFIG_SMALL("3GP format"),
2204
    NULL,
2205
    "3gp",
2206
    sizeof(MOVMuxContext),
2207
    CODEC_ID_AMR_NB,
2208
    CODEC_ID_H263,
2209
    mov_write_header,
2210
    ff_mov_write_packet,
2211
    mov_write_trailer,
2212
    .flags = AVFMT_GLOBALHEADER,
2213
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2214
};
2215
#endif
2216
#if CONFIG_MP4_MUXER
2217
AVOutputFormat mp4_muxer = {
2218
    "mp4",
2219
    NULL_IF_CONFIG_SMALL("MP4 format"),
2220
    "application/mp4",
2221
    "mp4",
2222
    sizeof(MOVMuxContext),
2223
    CODEC_ID_AAC,
2224
    CODEC_ID_MPEG4,
2225
    mov_write_header,
2226
    ff_mov_write_packet,
2227
    mov_write_trailer,
2228
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
2229
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2230
};
2231
#endif
2232
#if CONFIG_PSP_MUXER
2233
AVOutputFormat psp_muxer = {
2234
    "psp",
2235
    NULL_IF_CONFIG_SMALL("PSP MP4 format"),
2236
    NULL,
2237
    "mp4,psp",
2238
    sizeof(MOVMuxContext),
2239
    CODEC_ID_AAC,
2240
    CODEC_ID_MPEG4,
2241
    mov_write_header,
2242
    ff_mov_write_packet,
2243
    mov_write_trailer,
2244
    .flags = AVFMT_GLOBALHEADER,
2245
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2246
};
2247
#endif
2248
#if CONFIG_TG2_MUXER
2249
AVOutputFormat tg2_muxer = {
2250
    "3g2",
2251
    NULL_IF_CONFIG_SMALL("3GP2 format"),
2252
    NULL,
2253
    "3g2",
2254
    sizeof(MOVMuxContext),
2255
    CODEC_ID_AMR_NB,
2256
    CODEC_ID_H263,
2257
    mov_write_header,
2258
    ff_mov_write_packet,
2259
    mov_write_trailer,
2260
    .flags = AVFMT_GLOBALHEADER,
2261
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2262
};
2263
#endif
2264
#if CONFIG_IPOD_MUXER
2265
AVOutputFormat ipod_muxer = {
2266
    "ipod",
2267
    NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
2268
    "application/mp4",
2269
    "m4v,m4a",
2270
    sizeof(MOVMuxContext),
2271
    CODEC_ID_AAC,
2272
    CODEC_ID_H264,
2273
    mov_write_header,
2274
    ff_mov_write_packet,
2275
    mov_write_trailer,
2276
    .flags = AVFMT_GLOBALHEADER,
2277
    .codec_tag = (const AVCodecTag* const []){codec_ipod_tags, 0},
2278
};
2279
#endif