Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 9a191b3a

History | View | Annotate | Download (74.1 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_video_tag(ByteIOContext *pb, MOVTrack *track)
751
{
752
    int64_t pos = url_ftell(pb);
753
    char compressor_name[32];
754

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

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

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

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

    
811
    return updateSize(pb, pos);
812
}
813

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

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

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

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

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

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

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

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

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

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

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

    
938
    return 28;
939
}
940

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1122
    return 32;
1123
}
1124

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

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

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

    
1157
    put_be32(pb, 0); /* reserved */
1158
    put_be32(pb, 0); /* reserved */
1159
    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
1160
    /* Volume, only for audio */
1161
    if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1162
        put_be16(pb, 0x0100);
1163
    else
1164
        put_be16(pb, 0);
1165
    put_be16(pb, 0); /* reserved */
1166

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

    
1178
    /* Track width and height, for visual only */
1179
    if(st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1180
              track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1181
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1182
        if(!sample_aspect_ratio || track->height != track->enc->height)
1183
            sample_aspect_ratio = 1;
1184
        put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1185
        put_be32(pb, track->height*0x10000);
1186
    }
1187
    else {
1188
        put_be32(pb, 0);
1189
        put_be32(pb, 0);
1190
    }
1191
    return 0x5c;
1192
}
1193

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1580
    ret = url_open_dyn_buf(&pb_buf);
1581
    if(ret < 0)
1582
        return ret;
1583

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

    
1607
        if (s->nb_chapters)
1608
            mov_write_chpl_tag(pb_buf, s);
1609

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

    
1617
    return 0;
1618
}
1619

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

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

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

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

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

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

    
1664
        updateSize(pb, pos2);
1665
        return updateSize(pb, pos);
1666
    }
1667

    
1668
    return 0;
1669
}
1670

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

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

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

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

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

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

    
1712
    return updateSize(pb, pos);
1713
}
1714

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

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

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

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

    
1743
    put_be32(pb, 0); /* size */
1744
    put_tag(pb, "ftyp");
1745

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

    
1761
    put_be32(pb, minor);
1762

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

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

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

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

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

    
1800
    put_be32(pb, 0x0);  /* ? */
1801
    put_be32(pb, 0x3);  /* 3 sections ? */
1802

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1957
    put_flush_packet(pb);
1958

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

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

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

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

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

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

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

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

    
2010
    /* Default mode == MP4 */
2011
    mov->mode = MODE_MP4;
2012

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

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

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

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

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

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

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

    
2114
        av_set_pts_info(st, 64, 1, track->timescale);
2115
    }
2116

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

    
2120
    if (mov->chapter_track)
2121
        mov_create_chapter_track(s, mov->chapter_track);
2122

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

    
2135
    put_flush_packet(pb);
2136

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

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

    
2150
    int64_t moov_pos = url_ftell(pb);
2151

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

    
2165
    mov_write_moov_tag(pb, mov, s);
2166

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

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

    
2175
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2176

    
2177
    }
2178

    
2179
    put_flush_packet(pb);
2180

    
2181
    av_freep(&mov->tracks);
2182

    
2183
    return res;
2184
}
2185

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