Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ f59d8ff8

History | View | Annotate | Download (78.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 "avio_internal.h"
27
#include "riff.h"
28
#include "avio.h"
29
#include "isom.h"
30
#include "avc.h"
31
#include "libavcodec/get_bits.h"
32
#include "libavcodec/put_bits.h"
33
#include "internal.h"
34
#include "libavutil/avstring.h"
35

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

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

    
47
    return curpos - pos;
48
}
49

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

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

    
79
    int64_t pos = url_ftell(pb);
80
    avio_wb32(pb, 0); /* size */
81
    ffio_wfourcc(pb, "stsz");
82
    avio_wb32(pb, 0); /* version & flags */
83

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

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

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

    
138
    return updateSize(pb, pos);
139
}
140

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

    
165
static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
166
{
167
    avio_wb32(pb, 0x11); /* size */
168
    if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
169
    else                         ffio_wfourcc(pb, "damr");
170
    ffio_wfourcc(pb, "FFMP");
171
    avio_w8(pb, 0); /* decoder version */
172

    
173
    avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
174
    avio_w8(pb, 0x00); /* Mode change period (no restriction) */
175
    avio_w8(pb, 0x01); /* Frames per sample */
176
    return 0x11;
177
}
178

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

    
186
    if (track->vosLen < 7)
187
        return -1;
188

    
189
    avio_wb32(pb, 11);
190
    ffio_wfourcc(pb, "dac3");
191

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

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

    
217
    flush_put_bits(&pbc);
218
    avio_write(pb, buf, sizeof(buf));
219

    
220
    return 11;
221
}
222

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

    
233
static int mov_write_enda_tag(AVIOContext *pb)
234
{
235
    avio_wb32(pb, 10);
236
    ffio_wfourcc(pb, "enda");
237
    avio_wb16(pb, 1); /* little endian */
238
    return 10;
239
}
240

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

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

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

    
262
    avio_wb32(pb, 0); // size
263
    ffio_wfourcc(pb, "esds");
264
    avio_wb32(pb, 0); // Version
265

    
266
    // ES descriptor
267
    putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
268
             descrLength(1));
269
    avio_wb16(pb, track->trackID);
270
    avio_w8(pb, 0x00); // flags (= no flags)
271

    
272
    // DecoderConfig descriptor
273
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
274

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

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

    
290
    avio_w8(pb,  track->enc->rc_buffer_size>>(3+16));      // Buffersize DB (24 bits)
291
    avio_wb16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
292

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

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

    
305
    // SL descriptor
306
    putDescr(pb, 0x06, 1);
307
    avio_w8(pb, 0x02);
308
    return updateSize(pb, pos);
309
}
310

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

    
319
static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
320
{
321
    int64_t pos = url_ftell(pb);
322
    avio_wb32(pb, 0);
323
    avio_wl32(pb, track->tag); // store it byteswapped
324
    track->enc->codec_tag = av_bswap16(track->tag >> 16);
325
    ff_put_wav_header(pb, track->enc);
326
    return updateSize(pb, pos);
327
}
328

    
329
static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
330
{
331
    int64_t pos = url_ftell(pb);
332

    
333
    avio_wb32(pb, 0);     /* size */
334
    ffio_wfourcc(pb, "wave");
335

    
336
    avio_wb32(pb, 12);    /* size */
337
    ffio_wfourcc(pb, "frma");
338
    avio_wl32(pb, track->tag);
339

    
340
    if (track->enc->codec_id == CODEC_ID_AAC) {
341
        /* useless atom needed by mplayer, ipod, not needed by quicktime */
342
        avio_wb32(pb, 12); /* size */
343
        ffio_wfourcc(pb, "mp4a");
344
        avio_wb32(pb, 0);
345
        mov_write_esds_tag(pb, track);
346
    } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
347
        mov_write_enda_tag(pb);
348
    } else if (track->enc->codec_id == CODEC_ID_AMR_NB) {
349
        mov_write_amr_tag(pb, track);
350
    } else if (track->enc->codec_id == CODEC_ID_AC3) {
351
        mov_write_ac3_tag(pb, track);
352
    } else if (track->enc->codec_id == CODEC_ID_ALAC) {
353
        mov_write_extradata_tag(pb, track);
354
    } else if (track->enc->codec_id == CODEC_ID_ADPCM_MS ||
355
               track->enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
356
        mov_write_ms_tag(pb, track);
357
    }
358

    
359
    avio_wb32(pb, 8);     /* size */
360
    avio_wb32(pb, 0);     /* null tag */
361

    
362
    return updateSize(pb, pos);
363
}
364

    
365
static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
366
{
367
    avio_wb32(pb, track->vosLen+8);
368
    ffio_wfourcc(pb, "glbl");
369
    avio_write(pb, track->vosData, track->vosLen);
370
    return 8+track->vosLen;
371
}
372

    
373
/**
374
 * Compute flags for 'lpcm' tag.
375
 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
376
 */
377
static int mov_get_lpcm_flags(enum CodecID codec_id)
378
{
379
    switch (codec_id) {
380
    case CODEC_ID_PCM_F32BE:
381
    case CODEC_ID_PCM_F64BE:
382
        return 11;
383
    case CODEC_ID_PCM_F32LE:
384
    case CODEC_ID_PCM_F64LE:
385
        return 9;
386
    case CODEC_ID_PCM_U8:
387
        return 10;
388
    case CODEC_ID_PCM_S16BE:
389
    case CODEC_ID_PCM_S24BE:
390
    case CODEC_ID_PCM_S32BE:
391
        return 14;
392
    case CODEC_ID_PCM_S8:
393
    case CODEC_ID_PCM_S16LE:
394
    case CODEC_ID_PCM_S24LE:
395
    case CODEC_ID_PCM_S32LE:
396
        return 12;
397
    default:
398
        return 0;
399
    }
400
}
401

    
402
static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
403
{
404
    int64_t pos = url_ftell(pb);
405
    int version = 0;
406
    uint32_t tag = track->tag;
407

    
408
    if (track->mode == MODE_MOV) {
409
        if (track->timescale > UINT16_MAX) {
410
            if (mov_get_lpcm_flags(track->enc->codec_id))
411
                tag = AV_RL32("lpcm");
412
            version = 2;
413
        } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
414
                   track->enc->codec_id == CODEC_ID_ADPCM_MS ||
415
                   track->enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
416
            version = 1;
417
        }
418
    }
419

    
420
    avio_wb32(pb, 0); /* size */
421
    avio_wl32(pb, tag); // store it byteswapped
422
    avio_wb32(pb, 0); /* Reserved */
423
    avio_wb16(pb, 0); /* Reserved */
424
    avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */
425

    
426
    /* SoundDescription */
427
    avio_wb16(pb, version); /* Version */
428
    avio_wb16(pb, 0); /* Revision level */
429
    avio_wb32(pb, 0); /* Reserved */
430

    
431
    if (version == 2) {
432
        avio_wb16(pb, 3);
433
        avio_wb16(pb, 16);
434
        avio_wb16(pb, 0xfffe);
435
        avio_wb16(pb, 0);
436
        avio_wb32(pb, 0x00010000);
437
        avio_wb32(pb, 72);
438
        avio_wb64(pb, av_dbl2int(track->timescale));
439
        avio_wb32(pb, track->enc->channels);
440
        avio_wb32(pb, 0x7F000000);
441
        avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
442
        avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
443
        avio_wb32(pb, track->sampleSize);
444
        avio_wb32(pb, track->enc->frame_size);
445
    } else {
446
        if (track->mode == MODE_MOV) {
447
            avio_wb16(pb, track->enc->channels);
448
            if (track->enc->codec_id == CODEC_ID_PCM_U8 ||
449
                track->enc->codec_id == CODEC_ID_PCM_S8)
450
                avio_wb16(pb, 8); /* bits per sample */
451
            else
452
                avio_wb16(pb, 16);
453
            avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
454
        } else { /* reserved for mp4/3gp */
455
            avio_wb16(pb, 2);
456
            avio_wb16(pb, 16);
457
            avio_wb16(pb, 0);
458
        }
459

    
460
        avio_wb16(pb, 0); /* packet size (= 0) */
461
        avio_wb16(pb, track->timescale); /* Time scale */
462
        avio_wb16(pb, 0); /* Reserved */
463
    }
464

    
465
    if(version == 1) { /* SoundDescription V1 extended info */
466
        avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
467
        avio_wb32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
468
        avio_wb32(pb, track->sampleSize); /* Bytes per frame */
469
        avio_wb32(pb, 2); /* Bytes per sample */
470
    }
471

    
472
    if(track->mode == MODE_MOV &&
473
       (track->enc->codec_id == CODEC_ID_AAC ||
474
        track->enc->codec_id == CODEC_ID_AC3 ||
475
        track->enc->codec_id == CODEC_ID_AMR_NB ||
476
        track->enc->codec_id == CODEC_ID_ALAC ||
477
        track->enc->codec_id == CODEC_ID_ADPCM_MS ||
478
        track->enc->codec_id == CODEC_ID_ADPCM_IMA_WAV ||
479
        mov_pcm_le_gt16(track->enc->codec_id)))
480
        mov_write_wave_tag(pb, track);
481
    else if(track->tag == MKTAG('m','p','4','a'))
482
        mov_write_esds_tag(pb, track);
483
    else if(track->enc->codec_id == CODEC_ID_AMR_NB)
484
        mov_write_amr_tag(pb, track);
485
    else if(track->enc->codec_id == CODEC_ID_AC3)
486
        mov_write_ac3_tag(pb, track);
487
    else if(track->enc->codec_id == CODEC_ID_ALAC)
488
        mov_write_extradata_tag(pb, track);
489
    else if(track->vosLen > 0)
490
        mov_write_glbl_tag(pb, track);
491

    
492
    return updateSize(pb, pos);
493
}
494

    
495
static int mov_write_d263_tag(AVIOContext *pb)
496
{
497
    avio_wb32(pb, 0xf); /* size */
498
    ffio_wfourcc(pb, "d263");
499
    ffio_wfourcc(pb, "FFMP");
500
    avio_w8(pb, 0); /* decoder version */
501
    /* FIXME use AVCodecContext level/profile, when encoder will set values */
502
    avio_w8(pb, 0xa); /* level */
503
    avio_w8(pb, 0); /* profile */
504
    return 0xf;
505
}
506

    
507
/* TODO: No idea about these values */
508
static int mov_write_svq3_tag(AVIOContext *pb)
509
{
510
    avio_wb32(pb, 0x15);
511
    ffio_wfourcc(pb, "SMI ");
512
    ffio_wfourcc(pb, "SEQH");
513
    avio_wb32(pb, 0x5);
514
    avio_wb32(pb, 0xe2c0211d);
515
    avio_wb32(pb, 0xc0000000);
516
    avio_w8(pb, 0);
517
    return 0x15;
518
}
519

    
520
static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
521
{
522
    int64_t pos = url_ftell(pb);
523

    
524
    avio_wb32(pb, 0);
525
    ffio_wfourcc(pb, "avcC");
526
    ff_isom_write_avcc(pb, track->vosData, track->vosLen);
527
    return updateSize(pb, pos);
528
}
529

    
530
/* also used by all avid codecs (dv, imx, meridien) and their variants */
531
static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
532
{
533
    int i;
534
    avio_wb32(pb, 24); /* size */
535
    ffio_wfourcc(pb, "ACLR");
536
    ffio_wfourcc(pb, "ACLR");
537
    ffio_wfourcc(pb, "0001");
538
    avio_wb32(pb, 1); /* yuv 1 / rgb 2 ? */
539
    avio_wb32(pb, 0); /* unknown */
540

    
541
    avio_wb32(pb, 24); /* size */
542
    ffio_wfourcc(pb, "APRG");
543
    ffio_wfourcc(pb, "APRG");
544
    ffio_wfourcc(pb, "0001");
545
    avio_wb32(pb, 1); /* unknown */
546
    avio_wb32(pb, 0); /* unknown */
547

    
548
    avio_wb32(pb, 120); /* size */
549
    ffio_wfourcc(pb, "ARES");
550
    ffio_wfourcc(pb, "ARES");
551
    ffio_wfourcc(pb, "0001");
552
    avio_wb32(pb, AV_RB32(track->vosData + 0x28)); /* dnxhd cid, some id ? */
553
    avio_wb32(pb, track->enc->width);
554
    /* values below are based on samples created with quicktime and avid codecs */
555
    if (track->vosData[5] & 2) { // interlaced
556
        avio_wb32(pb, track->enc->height/2);
557
        avio_wb32(pb, 2); /* unknown */
558
        avio_wb32(pb, 0); /* unknown */
559
        avio_wb32(pb, 4); /* unknown */
560
    } else {
561
        avio_wb32(pb, track->enc->height);
562
        avio_wb32(pb, 1); /* unknown */
563
        avio_wb32(pb, 0); /* unknown */
564
        if (track->enc->height == 1080)
565
            avio_wb32(pb, 5); /* unknown */
566
        else
567
            avio_wb32(pb, 6); /* unknown */
568
    }
569
    /* padding */
570
    for (i = 0; i < 10; i++)
571
        avio_wb64(pb, 0);
572

    
573
    /* extra padding for stsd needed */
574
    avio_wb32(pb, 0);
575
    return 0;
576
}
577

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

    
582
    if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
583
        return 0;
584

    
585
    if      (track->enc->codec_id == CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
586
    else if (track->enc->codec_id == CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
587
    else if (track->enc->codec_id == CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
588
    else if (track->enc->codec_id == CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
589
    else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
590
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
591

    
592
    return tag;
593
}
594

    
595
static const AVCodecTag codec_ipod_tags[] = {
596
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
597
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
598
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
599
    { CODEC_ID_ALAC,   MKTAG('a','l','a','c') },
600
    { CODEC_ID_AC3,    MKTAG('a','c','-','3') },
601
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
602
    { CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
603
    { CODEC_ID_NONE, 0 },
604
};
605

    
606
static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
607
{
608
    int tag = track->enc->codec_tag;
609

    
610
    // keep original tag for subs, ipod supports both formats
611
    if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
612
        (tag == MKTAG('t','x','3','g') ||
613
         tag == MKTAG('t','e','x','t'))))
614
        tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
615

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

    
620
    return tag;
621
}
622

    
623
static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
624
{
625
    int tag;
626

    
627
    if (track->enc->height == 480) /* NTSC */
628
        if  (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
629
        else                                         tag = MKTAG('d','v','c',' ');
630
    else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
631
    else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
632
    else                                             tag = MKTAG('d','v','p','p');
633

    
634
    return tag;
635
}
636

    
637
static const struct {
638
    enum PixelFormat pix_fmt;
639
    uint32_t tag;
640
    unsigned bps;
641
} mov_pix_fmt_tags[] = {
642
    { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
643
    { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
644
    { PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
645
    { PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
646
    { PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
647
    { PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
648
    { PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
649
    { PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
650
    { PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
651
    { PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
652
    { PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
653
    { PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
654
    { PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
655
    { PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
656
};
657

    
658
static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
659
{
660
    int tag = track->enc->codec_tag;
661
    int i;
662

    
663
    for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
664
        if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
665
            tag = mov_pix_fmt_tags[i].tag;
666
            track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
667
            break;
668
        }
669
    }
670

    
671
    return tag;
672
}
673

    
674
static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
675
{
676
    int tag = track->enc->codec_tag;
677

    
678
    if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
679
                 (track->enc->codec_id == CODEC_ID_DVVIDEO ||
680
                  track->enc->codec_id == CODEC_ID_RAWVIDEO ||
681
                  track->enc->codec_id == CODEC_ID_H263 ||
682
                  av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
683
        if (track->enc->codec_id == CODEC_ID_DVVIDEO)
684
            tag = mov_get_dv_codec_tag(s, track);
685
        else if (track->enc->codec_id == CODEC_ID_RAWVIDEO)
686
            tag = mov_get_rawvideo_codec_tag(s, track);
687
        else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
688
            tag = ff_codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
689
            if (!tag) { // if no mac fcc found, try with Microsoft tags
690
                tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
691
                if (tag)
692
                    av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, "
693
                           "the file may be unplayable!\n");
694
            }
695
        } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
696
            tag = ff_codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
697
            if (!tag) { // if no mac fcc found, try with Microsoft tags
698
                int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
699
                if (ms_tag) {
700
                    tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
701
                    av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, "
702
                           "the file may be unplayable!\n");
703
                }
704
            }
705
        } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
706
            tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
707
    }
708

    
709
    return tag;
710
}
711

    
712
static const AVCodecTag codec_3gp_tags[] = {
713
    { CODEC_ID_H263,   MKTAG('s','2','6','3') },
714
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
715
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
716
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
717
    { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
718
    { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
719
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
720
    { CODEC_ID_NONE, 0 },
721
};
722

    
723
static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
724
{
725
    int tag = track->enc->codec_tag;
726

    
727
    if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
728
        tag = mp4_get_codec_tag(s, track);
729
    else if (track->mode == MODE_IPOD)
730
        tag = ipod_get_codec_tag(s, track);
731
    else if (track->mode & MODE_3GP)
732
        tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
733
    else
734
        tag = mov_get_codec_tag(s, track);
735

    
736
    return tag;
737
}
738

    
739
/** Write uuid atom.
740
 * Needed to make file play in iPods running newest firmware
741
 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
742
 */
743
static int mov_write_uuid_tag_ipod(AVIOContext *pb)
744
{
745
    avio_wb32(pb, 28);
746
    ffio_wfourcc(pb, "uuid");
747
    avio_wb32(pb, 0x6b6840f2);
748
    avio_wb32(pb, 0x5f244fc5);
749
    avio_wb32(pb, 0xba39a51b);
750
    avio_wb32(pb, 0xcf0323f3);
751
    avio_wb32(pb, 0x0);
752
    return 28;
753
}
754

    
755
static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
756
{
757
    int64_t pos = url_ftell(pb);
758
    avio_wb32(pb, 0);    /* size */
759
    avio_wl32(pb, track->tag); // store it byteswapped
760
    avio_wb32(pb, 0);    /* Reserved */
761
    avio_wb16(pb, 0);    /* Reserved */
762
    avio_wb16(pb, 1);    /* Data-reference index */
763

    
764
    if (track->enc->extradata_size)
765
        avio_write(pb, track->enc->extradata, track->enc->extradata_size);
766

    
767
    return updateSize(pb, pos);
768
}
769

    
770
static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
771
{
772
    AVRational sar;
773
    av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
774
              track->enc->sample_aspect_ratio.den, INT_MAX);
775

    
776
    avio_wb32(pb, 16);
777
    ffio_wfourcc(pb, "pasp");
778
    avio_wb32(pb, sar.num);
779
    avio_wb32(pb, sar.den);
780
    return 16;
781
}
782

    
783
static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
784
{
785
    int64_t pos = url_ftell(pb);
786
    char compressor_name[32];
787

    
788
    avio_wb32(pb, 0); /* size */
789
    avio_wl32(pb, track->tag); // store it byteswapped
790
    avio_wb32(pb, 0); /* Reserved */
791
    avio_wb16(pb, 0); /* Reserved */
792
    avio_wb16(pb, 1); /* Data-reference index */
793

    
794
    avio_wb16(pb, 0); /* Codec stream version */
795
    avio_wb16(pb, 0); /* Codec stream revision (=0) */
796
    if (track->mode == MODE_MOV) {
797
        ffio_wfourcc(pb, "FFMP"); /* Vendor */
798
        if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
799
            avio_wb32(pb, 0); /* Temporal Quality */
800
            avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
801
        } else {
802
            avio_wb32(pb, 0x200); /* Temporal Quality = normal */
803
            avio_wb32(pb, 0x200); /* Spatial Quality = normal */
804
        }
805
    } else {
806
        avio_wb32(pb, 0); /* Reserved */
807
        avio_wb32(pb, 0); /* Reserved */
808
        avio_wb32(pb, 0); /* Reserved */
809
    }
810
    avio_wb16(pb, track->enc->width); /* Video width */
811
    avio_wb16(pb, track->height); /* Video height */
812
    avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
813
    avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
814
    avio_wb32(pb, 0); /* Data size (= 0) */
815
    avio_wb16(pb, 1); /* Frame count (= 1) */
816

    
817
    memset(compressor_name,0,32);
818
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
819
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
820
        strncpy(compressor_name,track->enc->codec->name,31);
821
    avio_w8(pb, strlen(compressor_name));
822
    avio_write(pb, compressor_name, 31);
823

    
824
    if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
825
        avio_wb16(pb, track->enc->bits_per_coded_sample);
826
    else
827
        avio_wb16(pb, 0x18); /* Reserved */
828
    avio_wb16(pb, 0xffff); /* Reserved */
829
    if(track->tag == MKTAG('m','p','4','v'))
830
        mov_write_esds_tag(pb, track);
831
    else if(track->enc->codec_id == CODEC_ID_H263)
832
        mov_write_d263_tag(pb);
833
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
834
        mov_write_svq3_tag(pb);
835
    else if(track->enc->codec_id == CODEC_ID_DNXHD)
836
        mov_write_avid_tag(pb, track);
837
    else if(track->enc->codec_id == CODEC_ID_H264) {
838
        mov_write_avcc_tag(pb, track);
839
        if(track->mode == MODE_IPOD)
840
            mov_write_uuid_tag_ipod(pb);
841
    } else if(track->vosLen > 0)
842
        mov_write_glbl_tag(pb, track);
843

    
844
    if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
845
        track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
846
        mov_write_pasp_tag(pb, track);
847
    }
848

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

    
852
static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
853
{
854
    int64_t pos = url_ftell(pb);
855
    avio_wb32(pb, 0); /* size */
856
    ffio_wfourcc(pb, "rtp ");
857
    avio_wb32(pb, 0); /* Reserved */
858
    avio_wb16(pb, 0); /* Reserved */
859
    avio_wb16(pb, 1); /* Data-reference index */
860

    
861
    avio_wb16(pb, 1); /* Hint track version */
862
    avio_wb16(pb, 1); /* Highest compatible version */
863
    avio_wb32(pb, track->max_packet_size); /* Max packet size */
864

    
865
    avio_wb32(pb, 12); /* size */
866
    ffio_wfourcc(pb, "tims");
867
    avio_wb32(pb, track->timescale);
868

    
869
    return updateSize(pb, pos);
870
}
871

    
872
static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
873
{
874
    int64_t pos = url_ftell(pb);
875
    avio_wb32(pb, 0); /* size */
876
    ffio_wfourcc(pb, "stsd");
877
    avio_wb32(pb, 0); /* version & flags */
878
    avio_wb32(pb, 1); /* entry count */
879
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
880
        mov_write_video_tag(pb, track);
881
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
882
        mov_write_audio_tag(pb, track);
883
    else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
884
        mov_write_subtitle_tag(pb, track);
885
    else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
886
        mov_write_rtp_tag(pb, track);
887
    return updateSize(pb, pos);
888
}
889

    
890
static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
891
{
892
    MOVStts *ctts_entries;
893
    uint32_t entries = 0;
894
    uint32_t atom_size;
895
    int i;
896

    
897
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
898
    ctts_entries[0].count = 1;
899
    ctts_entries[0].duration = track->cluster[0].cts;
900
    for (i=1; i<track->entry; i++) {
901
        if (track->cluster[i].cts == ctts_entries[entries].duration) {
902
            ctts_entries[entries].count++; /* compress */
903
        } else {
904
            entries++;
905
            ctts_entries[entries].duration = track->cluster[i].cts;
906
            ctts_entries[entries].count = 1;
907
        }
908
    }
909
    entries++; /* last one */
910
    atom_size = 16 + (entries * 8);
911
    avio_wb32(pb, atom_size); /* size */
912
    ffio_wfourcc(pb, "ctts");
913
    avio_wb32(pb, 0); /* version & flags */
914
    avio_wb32(pb, entries); /* entry count */
915
    for (i=0; i<entries; i++) {
916
        avio_wb32(pb, ctts_entries[i].count);
917
        avio_wb32(pb, ctts_entries[i].duration);
918
    }
919
    av_free(ctts_entries);
920
    return atom_size;
921
}
922

    
923
/* Time to sample atom */
924
static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
925
{
926
    MOVStts *stts_entries;
927
    uint32_t entries = -1;
928
    uint32_t atom_size;
929
    int i;
930

    
931
    if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
932
        stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
933
        stts_entries[0].count = track->sampleCount;
934
        stts_entries[0].duration = 1;
935
        entries = 1;
936
    } else {
937
        stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
938
        for (i=0; i<track->entry; i++) {
939
            int64_t duration = i + 1 == track->entry ?
940
                track->trackDuration - track->cluster[i].dts + track->cluster[0].dts : /* readjusting */
941
                track->cluster[i+1].dts - track->cluster[i].dts;
942
            if (i && duration == stts_entries[entries].duration) {
943
                stts_entries[entries].count++; /* compress */
944
            } else {
945
                entries++;
946
                stts_entries[entries].duration = duration;
947
                stts_entries[entries].count = 1;
948
            }
949
        }
950
        entries++; /* last one */
951
    }
952
    atom_size = 16 + (entries * 8);
953
    avio_wb32(pb, atom_size); /* size */
954
    ffio_wfourcc(pb, "stts");
955
    avio_wb32(pb, 0); /* version & flags */
956
    avio_wb32(pb, entries); /* entry count */
957
    for (i=0; i<entries; i++) {
958
        avio_wb32(pb, stts_entries[i].count);
959
        avio_wb32(pb, stts_entries[i].duration);
960
    }
961
    av_free(stts_entries);
962
    return atom_size;
963
}
964

    
965
static int mov_write_dref_tag(AVIOContext *pb)
966
{
967
    avio_wb32(pb, 28); /* size */
968
    ffio_wfourcc(pb, "dref");
969
    avio_wb32(pb, 0); /* version & flags */
970
    avio_wb32(pb, 1); /* entry count */
971

    
972
    avio_wb32(pb, 0xc); /* size */
973
    ffio_wfourcc(pb, "url ");
974
    avio_wb32(pb, 1); /* version & flags */
975

    
976
    return 28;
977
}
978

    
979
static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
980
{
981
    int64_t pos = url_ftell(pb);
982
    avio_wb32(pb, 0); /* size */
983
    ffio_wfourcc(pb, "stbl");
984
    mov_write_stsd_tag(pb, track);
985
    mov_write_stts_tag(pb, track);
986
    if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
987
         track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
988
        track->hasKeyframes && track->hasKeyframes < track->entry)
989
        mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
990
    if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
991
        mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
992
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
993
        track->flags & MOV_TRACK_CTTS)
994
        mov_write_ctts_tag(pb, track);
995
    mov_write_stsc_tag(pb, track);
996
    mov_write_stsz_tag(pb, track);
997
    mov_write_stco_tag(pb, track);
998
    return updateSize(pb, pos);
999
}
1000

    
1001
static int mov_write_dinf_tag(AVIOContext *pb)
1002
{
1003
    int64_t pos = url_ftell(pb);
1004
    avio_wb32(pb, 0); /* size */
1005
    ffio_wfourcc(pb, "dinf");
1006
    mov_write_dref_tag(pb);
1007
    return updateSize(pb, pos);
1008
}
1009

    
1010
static int mov_write_nmhd_tag(AVIOContext *pb)
1011
{
1012
    avio_wb32(pb, 12);
1013
    ffio_wfourcc(pb, "nmhd");
1014
    avio_wb32(pb, 0);
1015
    return 12;
1016
}
1017

    
1018
static int mov_write_gmhd_tag(AVIOContext *pb)
1019
{
1020
    avio_wb32(pb, 0x20);   /* size */
1021
    ffio_wfourcc(pb, "gmhd");
1022
    avio_wb32(pb, 0x18);   /* gmin size */
1023
    ffio_wfourcc(pb, "gmin");/* generic media info */
1024
    avio_wb32(pb, 0);      /* version & flags */
1025
    avio_wb16(pb, 0x40);   /* graphics mode = */
1026
    avio_wb16(pb, 0x8000); /* opColor (r?) */
1027
    avio_wb16(pb, 0x8000); /* opColor (g?) */
1028
    avio_wb16(pb, 0x8000); /* opColor (b?) */
1029
    avio_wb16(pb, 0);      /* balance */
1030
    avio_wb16(pb, 0);      /* reserved */
1031
    return 0x20;
1032
}
1033

    
1034
static int mov_write_smhd_tag(AVIOContext *pb)
1035
{
1036
    avio_wb32(pb, 16); /* size */
1037
    ffio_wfourcc(pb, "smhd");
1038
    avio_wb32(pb, 0); /* version & flags */
1039
    avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1040
    avio_wb16(pb, 0); /* reserved */
1041
    return 16;
1042
}
1043

    
1044
static int mov_write_vmhd_tag(AVIOContext *pb)
1045
{
1046
    avio_wb32(pb, 0x14); /* size (always 0x14) */
1047
    ffio_wfourcc(pb, "vmhd");
1048
    avio_wb32(pb, 0x01); /* version & flags */
1049
    avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1050
    return 0x14;
1051
}
1052

    
1053
static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1054
{
1055
    const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1056
    int64_t pos = url_ftell(pb);
1057

    
1058
    if (!track) { /* no media --> data handler */
1059
        hdlr = "dhlr";
1060
        hdlr_type = "url ";
1061
        descr = "DataHandler";
1062
    } else {
1063
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1064
        if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1065
            hdlr_type = "vide";
1066
            descr = "VideoHandler";
1067
        } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1068
            hdlr_type = "soun";
1069
            descr = "SoundHandler";
1070
        } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1071
            if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
1072
            else                                      hdlr_type = "text";
1073
            descr = "SubtitleHandler";
1074
        } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1075
            hdlr_type = "hint";
1076
            descr = "HintHandler";
1077
        }
1078
    }
1079

    
1080
    avio_wb32(pb, 0); /* size */
1081
    ffio_wfourcc(pb, "hdlr");
1082
    avio_wb32(pb, 0); /* Version & flags */
1083
    avio_write(pb, hdlr, 4); /* handler */
1084
    ffio_wfourcc(pb, hdlr_type); /* handler type */
1085
    avio_wb32(pb ,0); /* reserved */
1086
    avio_wb32(pb ,0); /* reserved */
1087
    avio_wb32(pb ,0); /* reserved */
1088
    if (!track || track->mode == MODE_MOV)
1089
        avio_w8(pb, strlen(descr)); /* pascal string */
1090
    avio_write(pb, descr, strlen(descr)); /* handler description */
1091
    if (track && track->mode != MODE_MOV)
1092
        avio_w8(pb, 0); /* c string */
1093
    return updateSize(pb, pos);
1094
}
1095

    
1096
static int mov_write_hmhd_tag(AVIOContext *pb)
1097
{
1098
    /* This atom must be present, but leaving the values at zero
1099
     * seems harmless. */
1100
    avio_wb32(pb, 28); /* size */
1101
    ffio_wfourcc(pb, "hmhd");
1102
    avio_wb32(pb, 0); /* version, flags */
1103
    avio_wb16(pb, 0); /* maxPDUsize */
1104
    avio_wb16(pb, 0); /* avgPDUsize */
1105
    avio_wb32(pb, 0); /* maxbitrate */
1106
    avio_wb32(pb, 0); /* avgbitrate */
1107
    avio_wb32(pb, 0); /* reserved */
1108
    return 28;
1109
}
1110

    
1111
static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1112
{
1113
    int64_t pos = url_ftell(pb);
1114
    avio_wb32(pb, 0); /* size */
1115
    ffio_wfourcc(pb, "minf");
1116
    if(track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1117
        mov_write_vmhd_tag(pb);
1118
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1119
        mov_write_smhd_tag(pb);
1120
    else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1121
        if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb);
1122
        else                                      mov_write_nmhd_tag(pb);
1123
    } else if (track->tag == MKTAG('r','t','p',' ')) {
1124
        mov_write_hmhd_tag(pb);
1125
    }
1126
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1127
        mov_write_hdlr_tag(pb, NULL);
1128
    mov_write_dinf_tag(pb);
1129
    mov_write_stbl_tag(pb, track);
1130
    return updateSize(pb, pos);
1131
}
1132

    
1133
static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1134
{
1135
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
1136

    
1137
    (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1138
    ffio_wfourcc(pb, "mdhd");
1139
    avio_w8(pb, version);
1140
    avio_wb24(pb, 0); /* flags */
1141
    if (version == 1) {
1142
        avio_wb64(pb, track->time);
1143
        avio_wb64(pb, track->time);
1144
    } else {
1145
        avio_wb32(pb, track->time); /* creation time */
1146
        avio_wb32(pb, track->time); /* modification time */
1147
    }
1148
    avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1149
    (version == 1) ? avio_wb64(pb, track->trackDuration) : avio_wb32(pb, track->trackDuration); /* duration */
1150
    avio_wb16(pb, track->language); /* language */
1151
    avio_wb16(pb, 0); /* reserved (quality) */
1152

    
1153
    if(version!=0 && track->mode == MODE_MOV){
1154
        av_log(NULL, AV_LOG_ERROR,
1155
            "FATAL error, file duration too long for timebase, this file will not be\n"
1156
            "playable with quicktime. Choose a different timebase or a different\n"
1157
            "container format\n");
1158
    }
1159

    
1160
    return 32;
1161
}
1162

    
1163
static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1164
{
1165
    int64_t pos = url_ftell(pb);
1166
    avio_wb32(pb, 0); /* size */
1167
    ffio_wfourcc(pb, "mdia");
1168
    mov_write_mdhd_tag(pb, track);
1169
    mov_write_hdlr_tag(pb, track);
1170
    mov_write_minf_tag(pb, track);
1171
    return updateSize(pb, pos);
1172
}
1173

    
1174
static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1175
{
1176
    int64_t duration = av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1177
                                      track->timescale, AV_ROUND_UP);
1178
    int version = duration < INT32_MAX ? 0 : 1;
1179

    
1180
    (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1181
    ffio_wfourcc(pb, "tkhd");
1182
    avio_w8(pb, version);
1183
    avio_wb24(pb, 0xf); /* flags (track enabled) */
1184
    if (version == 1) {
1185
        avio_wb64(pb, track->time);
1186
        avio_wb64(pb, track->time);
1187
    } else {
1188
        avio_wb32(pb, track->time); /* creation time */
1189
        avio_wb32(pb, track->time); /* modification time */
1190
    }
1191
    avio_wb32(pb, track->trackID); /* track-id */
1192
    avio_wb32(pb, 0); /* reserved */
1193
    (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1194

    
1195
    avio_wb32(pb, 0); /* reserved */
1196
    avio_wb32(pb, 0); /* reserved */
1197
    avio_wb32(pb, 0x0); /* reserved (Layer & Alternate group) */
1198
    /* Volume, only for audio */
1199
    if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1200
        avio_wb16(pb, 0x0100);
1201
    else
1202
        avio_wb16(pb, 0);
1203
    avio_wb16(pb, 0); /* reserved */
1204

    
1205
    /* Matrix structure */
1206
    avio_wb32(pb, 0x00010000); /* reserved */
1207
    avio_wb32(pb, 0x0); /* reserved */
1208
    avio_wb32(pb, 0x0); /* reserved */
1209
    avio_wb32(pb, 0x0); /* reserved */
1210
    avio_wb32(pb, 0x00010000); /* reserved */
1211
    avio_wb32(pb, 0x0); /* reserved */
1212
    avio_wb32(pb, 0x0); /* reserved */
1213
    avio_wb32(pb, 0x0); /* reserved */
1214
    avio_wb32(pb, 0x40000000); /* reserved */
1215

    
1216
    /* Track width and height, for visual only */
1217
    if(st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1218
              track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1219
        if(track->mode == MODE_MOV) {
1220
            avio_wb32(pb, track->enc->width << 16);
1221
            avio_wb32(pb, track->enc->height << 16);
1222
        } else {
1223
            double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1224
            if(!sample_aspect_ratio || track->height != track->enc->height)
1225
                sample_aspect_ratio = 1;
1226
            avio_wb32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1227
            avio_wb32(pb, track->height*0x10000);
1228
        }
1229
    }
1230
    else {
1231
        avio_wb32(pb, 0);
1232
        avio_wb32(pb, 0);
1233
    }
1234
    return 0x5c;
1235
}
1236

    
1237
static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1238
{
1239
    int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1240
                               track->enc->sample_aspect_ratio.den);
1241

    
1242
    int64_t pos = url_ftell(pb);
1243

    
1244
    avio_wb32(pb, 0); /* size */
1245
    ffio_wfourcc(pb, "tapt");
1246

    
1247
    avio_wb32(pb, 20);
1248
    ffio_wfourcc(pb, "clef");
1249
    avio_wb32(pb, 0);
1250
    avio_wb32(pb, width << 16);
1251
    avio_wb32(pb, track->enc->height << 16);
1252

    
1253
    avio_wb32(pb, 20);
1254
    ffio_wfourcc(pb, "enof");
1255
    avio_wb32(pb, 0);
1256
    avio_wb32(pb, track->enc->width << 16);
1257
    avio_wb32(pb, track->enc->height << 16);
1258

    
1259
    return updateSize(pb, pos);
1260
};
1261

    
1262
// This box seems important for the psp playback ... without it the movie seems to hang
1263
static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1264
{
1265
    avio_wb32(pb, 0x24); /* size  */
1266
    ffio_wfourcc(pb, "edts");
1267
    avio_wb32(pb, 0x1c); /* size  */
1268
    ffio_wfourcc(pb, "elst");
1269
    avio_wb32(pb, 0x0);
1270
    avio_wb32(pb, 0x1);
1271

    
1272
    /* duration   ... doesn't seem to effect psp */
1273
    avio_wb32(pb, av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1274
                                track->timescale, AV_ROUND_UP));
1275

    
1276
    avio_wb32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
1277
    avio_wb32(pb, 0x00010000);
1278
    return 0x24;
1279
}
1280

    
1281
static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1282
{
1283
    avio_wb32(pb, 20);   // size
1284
    ffio_wfourcc(pb, "tref");
1285
    avio_wb32(pb, 12);   // size (subatom)
1286
    avio_wl32(pb, track->tref_tag);
1287
    avio_wb32(pb, track->tref_id);
1288
    return 20;
1289
}
1290

    
1291
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1292
static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1293
{
1294
    avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1295
    ffio_wfourcc(pb, "uuid");
1296
    ffio_wfourcc(pb, "USMT");
1297
    avio_wb32(pb, 0x21d24fce);
1298
    avio_wb32(pb, 0xbb88695c);
1299
    avio_wb32(pb, 0xfac9c740);
1300
    avio_wb32(pb, 0x1c);     // another size here!
1301
    ffio_wfourcc(pb, "MTDT");
1302
    avio_wb32(pb, 0x00010012);
1303
    avio_wb32(pb, 0x0a);
1304
    avio_wb32(pb, 0x55c40000);
1305
    avio_wb32(pb, 0x1);
1306
    avio_wb32(pb, 0x0);
1307
    return 0x34;
1308
}
1309

    
1310
static int mov_write_udta_sdp(AVIOContext *pb, AVCodecContext *ctx, int index)
1311
{
1312
    char buf[1000] = "";
1313
    int len;
1314

    
1315
    ff_sdp_write_media(buf, sizeof(buf), ctx, NULL, NULL, 0, 0);
1316
    av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", index);
1317
    len = strlen(buf);
1318

    
1319
    avio_wb32(pb, len + 24);
1320
    ffio_wfourcc(pb, "udta");
1321
    avio_wb32(pb, len + 16);
1322
    ffio_wfourcc(pb, "hnti");
1323
    avio_wb32(pb, len + 8);
1324
    ffio_wfourcc(pb, "sdp ");
1325
    avio_write(pb, buf, len);
1326
    return len + 24;
1327
}
1328

    
1329
static int mov_write_trak_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1330
{
1331
    int64_t pos = url_ftell(pb);
1332
    avio_wb32(pb, 0); /* size */
1333
    ffio_wfourcc(pb, "trak");
1334
    mov_write_tkhd_tag(pb, track, st);
1335
    if (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS)
1336
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1337
    if (track->tref_tag)
1338
        mov_write_tref_tag(pb, track);
1339
    mov_write_mdia_tag(pb, track);
1340
    if (track->mode == MODE_PSP)
1341
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1342
    if (track->tag == MKTAG('r','t','p',' '))
1343
        mov_write_udta_sdp(pb, track->rtp_ctx->streams[0]->codec, track->trackID);
1344
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO && track->mode == MODE_MOV) {
1345
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1346
        if (0.0 != sample_aspect_ratio && 1.0 != sample_aspect_ratio)
1347
            mov_write_tapt_tag(pb, track);
1348
    };
1349
    return updateSize(pb, pos);
1350
}
1351

    
1352
#if 0
1353
/* TODO: Not sorted out, but not necessary either */
1354
static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1355
{
1356
    avio_wb32(pb, 0x15); /* size */
1357
    ffio_wfourcc(pb, "iods");
1358
    avio_wb32(pb, 0);    /* version & flags */
1359
    avio_wb16(pb, 0x1007);
1360
    avio_w8(pb, 0);
1361
    avio_wb16(pb, 0x4fff);
1362
    avio_wb16(pb, 0xfffe);
1363
    avio_wb16(pb, 0x01ff);
1364
    return 0x15;
1365
}
1366
#endif
1367

    
1368
static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
1369
{
1370
    int maxTrackID = 1, i;
1371
    int64_t maxTrackLenTemp, maxTrackLen = 0;
1372
    int version;
1373

    
1374
    for (i=0; i<mov->nb_streams; i++) {
1375
        if(mov->tracks[i].entry > 0) {
1376
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration,
1377
                                             MOV_TIMESCALE,
1378
                                             mov->tracks[i].timescale,
1379
                                             AV_ROUND_UP);
1380
            if(maxTrackLen < maxTrackLenTemp)
1381
                maxTrackLen = maxTrackLenTemp;
1382
            if(maxTrackID < mov->tracks[i].trackID)
1383
                maxTrackID = mov->tracks[i].trackID;
1384
        }
1385
    }
1386

    
1387
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1388
    (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
1389
    ffio_wfourcc(pb, "mvhd");
1390
    avio_w8(pb, version);
1391
    avio_wb24(pb, 0); /* flags */
1392
    if (version == 1) {
1393
        avio_wb64(pb, mov->time);
1394
        avio_wb64(pb, mov->time);
1395
    } else {
1396
        avio_wb32(pb, mov->time); /* creation time */
1397
        avio_wb32(pb, mov->time); /* modification time */
1398
    }
1399
    avio_wb32(pb, MOV_TIMESCALE);
1400
    (version == 1) ? avio_wb64(pb, maxTrackLen) : avio_wb32(pb, maxTrackLen); /* duration of longest track */
1401

    
1402
    avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1403
    avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1404
    avio_wb16(pb, 0); /* reserved */
1405
    avio_wb32(pb, 0); /* reserved */
1406
    avio_wb32(pb, 0); /* reserved */
1407

    
1408
    /* Matrix structure */
1409
    avio_wb32(pb, 0x00010000); /* reserved */
1410
    avio_wb32(pb, 0x0); /* reserved */
1411
    avio_wb32(pb, 0x0); /* reserved */
1412
    avio_wb32(pb, 0x0); /* reserved */
1413
    avio_wb32(pb, 0x00010000); /* reserved */
1414
    avio_wb32(pb, 0x0); /* reserved */
1415
    avio_wb32(pb, 0x0); /* reserved */
1416
    avio_wb32(pb, 0x0); /* reserved */
1417
    avio_wb32(pb, 0x40000000); /* reserved */
1418

    
1419
    avio_wb32(pb, 0); /* reserved (preview time) */
1420
    avio_wb32(pb, 0); /* reserved (preview duration) */
1421
    avio_wb32(pb, 0); /* reserved (poster time) */
1422
    avio_wb32(pb, 0); /* reserved (selection time) */
1423
    avio_wb32(pb, 0); /* reserved (selection duration) */
1424
    avio_wb32(pb, 0); /* reserved (current time) */
1425
    avio_wb32(pb, maxTrackID+1); /* Next track id */
1426
    return 0x6c;
1427
}
1428

    
1429
static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
1430
                                     AVFormatContext *s)
1431
{
1432
    avio_wb32(pb, 33); /* size */
1433
    ffio_wfourcc(pb, "hdlr");
1434
    avio_wb32(pb, 0);
1435
    avio_wb32(pb, 0);
1436
    ffio_wfourcc(pb, "mdir");
1437
    ffio_wfourcc(pb, "appl");
1438
    avio_wb32(pb, 0);
1439
    avio_wb32(pb, 0);
1440
    avio_w8(pb, 0);
1441
    return 33;
1442
}
1443

    
1444
/* helper function to write a data tag with the specified string as data */
1445
static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
1446
{
1447
    if(long_style){
1448
        int size = 16 + strlen(data);
1449
        avio_wb32(pb, size); /* size */
1450
        ffio_wfourcc(pb, "data");
1451
        avio_wb32(pb, 1);
1452
        avio_wb32(pb, 0);
1453
        avio_write(pb, data, strlen(data));
1454
        return size;
1455
    }else{
1456
        if (!lang)
1457
            lang = ff_mov_iso639_to_lang("und", 1);
1458
        avio_wb16(pb, strlen(data)); /* string length */
1459
        avio_wb16(pb, lang);
1460
        avio_write(pb, data, strlen(data));
1461
        return strlen(data) + 4;
1462
    }
1463
}
1464

    
1465
static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style){
1466
    int size = 0;
1467
    if (value && value[0]) {
1468
        int64_t pos = url_ftell(pb);
1469
        avio_wb32(pb, 0); /* size */
1470
        ffio_wfourcc(pb, name);
1471
        mov_write_string_data_tag(pb, value, lang, long_style);
1472
        size= updateSize(pb, pos);
1473
    }
1474
    return size;
1475
}
1476

    
1477
static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
1478
                                     const char *name, const char *tag,
1479
                                     int long_style)
1480
{
1481
    int l, lang = 0, len, len2;
1482
    AVMetadataTag *t, *t2 = NULL;
1483
    char tag2[16];
1484

    
1485
    if (!(t = av_metadata_get(s->metadata, tag, NULL, 0)))
1486
        return 0;
1487

    
1488
    len = strlen(t->key);
1489
    snprintf(tag2, sizeof(tag2), "%s-", tag);
1490
    while ((t2 = av_metadata_get(s->metadata, tag2, t2, AV_METADATA_IGNORE_SUFFIX))) {
1491
        len2 = strlen(t2->key);
1492
        if (len2 == len+4 && !strcmp(t->value, t2->value)
1493
            && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 1)) >= 0) {
1494
            lang = l;
1495
            break;
1496
        }
1497
    }
1498
    return mov_write_string_tag(pb, name, t->value, lang, long_style);
1499
}
1500

    
1501
/* iTunes track number */
1502
static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
1503
                              AVFormatContext *s)
1504
{
1505
    AVMetadataTag *t = av_metadata_get(s->metadata, "track", NULL, 0);
1506
    int size = 0, track = t ? atoi(t->value) : 0;
1507
    if (track) {
1508
        avio_wb32(pb, 32); /* size */
1509
        ffio_wfourcc(pb, "trkn");
1510
            avio_wb32(pb, 24); /* size */
1511
            ffio_wfourcc(pb, "data");
1512
            avio_wb32(pb, 0);        // 8 bytes empty
1513
            avio_wb32(pb, 0);
1514
            avio_wb16(pb, 0);        // empty
1515
            avio_wb16(pb, track);    // track number
1516
            avio_wb16(pb, 0);        // total track number
1517
            avio_wb16(pb, 0);        // empty
1518
        size = 32;
1519
    }
1520
    return size;
1521
}
1522

    
1523
/* iTunes meta data list */
1524
static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
1525
                              AVFormatContext *s)
1526
{
1527
    int64_t pos = url_ftell(pb);
1528
    avio_wb32(pb, 0); /* size */
1529
    ffio_wfourcc(pb, "ilst");
1530
    mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1531
    mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
1532
    mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
1533
    mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1534
    mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1535
    mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
1536
    mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1537
    mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1538
    mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1539
    mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1540
    mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
1541
    mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
1542
    mov_write_string_metadata(s, pb, "desc",    "description",1);
1543
    mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
1544
    mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
1545
    mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
1546
    mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
1547
    mov_write_trkn_tag(pb, mov, s);
1548
    return updateSize(pb, pos);
1549
}
1550

    
1551
/* iTunes meta data tag */
1552
static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
1553
                              AVFormatContext *s)
1554
{
1555
    int size = 0;
1556
    int64_t pos = url_ftell(pb);
1557
    avio_wb32(pb, 0); /* size */
1558
    ffio_wfourcc(pb, "meta");
1559
    avio_wb32(pb, 0);
1560
    mov_write_itunes_hdlr_tag(pb, mov, s);
1561
    mov_write_ilst_tag(pb, mov, s);
1562
    size = updateSize(pb, pos);
1563
    return size;
1564
}
1565

    
1566
static int utf8len(const uint8_t *b)
1567
{
1568
    int len=0;
1569
    int val;
1570
    while(*b){
1571
        GET_UTF8(val, *b++, return -1;)
1572
        len++;
1573
    }
1574
    return len;
1575
}
1576

    
1577
static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
1578
{
1579
    int val;
1580
    while(*b){
1581
        GET_UTF8(val, *b++, return -1;)
1582
        avio_wb16(pb, val);
1583
    }
1584
    avio_wb16(pb, 0x00);
1585
    return 0;
1586
}
1587

    
1588
static uint16_t language_code(const char *str)
1589
{
1590
    return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1591
}
1592

    
1593
static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
1594
                                  const char *tag, const char *str)
1595
{
1596
    int64_t pos = url_ftell(pb);
1597
    AVMetadataTag *t = av_metadata_get(s->metadata, str, NULL, 0);
1598
    if (!t || !utf8len(t->value))
1599
        return 0;
1600
    avio_wb32(pb, 0);   /* size */
1601
    ffio_wfourcc(pb, tag); /* type */
1602
    avio_wb32(pb, 0);   /* version + flags */
1603
    if (!strcmp(tag, "yrrc"))
1604
        avio_wb16(pb, atoi(t->value));
1605
    else {
1606
        avio_wb16(pb, language_code("eng")); /* language */
1607
        avio_write(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
1608
        if (!strcmp(tag, "albm") &&
1609
            (t = av_metadata_get(s->metadata, "track", NULL, 0)))
1610
            avio_w8(pb, atoi(t->value));
1611
    }
1612
    return updateSize(pb, pos);
1613
}
1614

    
1615
static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
1616
{
1617
    int64_t pos = url_ftell(pb);
1618
    int i, nb_chapters = FFMIN(s->nb_chapters, 255);
1619

    
1620
    avio_wb32(pb, 0);            // size
1621
    ffio_wfourcc(pb, "chpl");
1622
    avio_wb32(pb, 0x01000000);   // version + flags
1623
    avio_wb32(pb, 0);            // unknown
1624
    avio_w8(pb, nb_chapters);
1625

    
1626
    for (i = 0; i < nb_chapters; i++) {
1627
        AVChapter *c = s->chapters[i];
1628
        AVMetadataTag *t;
1629
        avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
1630

    
1631
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
1632
            int len = FFMIN(strlen(t->value), 255);
1633
            avio_w8(pb, len);
1634
            avio_write(pb, t->value, len);
1635
        } else
1636
            avio_w8(pb, 0);
1637
    }
1638
    return updateSize(pb, pos);
1639
}
1640

    
1641
static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
1642
                              AVFormatContext *s)
1643
{
1644
    AVIOContext *pb_buf;
1645
    int i, ret, size;
1646
    uint8_t *buf;
1647

    
1648
    for (i = 0; i < s->nb_streams; i++)
1649
        if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1650
            return 0;
1651
        }
1652

    
1653
    ret = url_open_dyn_buf(&pb_buf);
1654
    if(ret < 0)
1655
        return ret;
1656

    
1657
        if (mov->mode & MODE_3GP) {
1658
            mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
1659
            mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1660
            mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1661
            mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1662
            mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1663
            mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1664
            mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1665
            mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
1666
        } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1667
            mov_write_string_metadata(s, pb_buf, "\251ART", "artist"     , 0);
1668
            mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
1669
            mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
1670
            mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
1671
            mov_write_string_metadata(s, pb_buf, "\251day", "date"       , 0);
1672
            mov_write_string_metadata(s, pb_buf, "\251swr", "encoder"    , 0);
1673
            mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
1674
            mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
1675
            mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
1676
        } else {
1677
            /* iTunes meta data */
1678
            mov_write_meta_tag(pb_buf, mov, s);
1679
        }
1680

    
1681
        if (s->nb_chapters)
1682
            mov_write_chpl_tag(pb_buf, s);
1683

    
1684
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1685
        avio_wb32(pb, size+8);
1686
        ffio_wfourcc(pb, "udta");
1687
        avio_write(pb, buf, size);
1688
    }
1689
    av_free(buf);
1690

    
1691
    return 0;
1692
}
1693

    
1694
static void mov_write_psp_udta_tag(AVIOContext *pb,
1695
                                  const char *str, const char *lang, int type)
1696
{
1697
    int len = utf8len(str)+1;
1698
    if(len<=0)
1699
        return;
1700
    avio_wb16(pb, len*2+10);            /* size */
1701
    avio_wb32(pb, type);                /* type */
1702
    avio_wb16(pb, language_code(lang)); /* language */
1703
    avio_wb16(pb, 0x01);                /* ? */
1704
    ascii_to_wc(pb, str);
1705
}
1706

    
1707
static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
1708
{
1709
    AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
1710
    int64_t pos, pos2;
1711

    
1712
    if (title) {
1713
        pos = url_ftell(pb);
1714
        avio_wb32(pb, 0); /* size placeholder*/
1715
        ffio_wfourcc(pb, "uuid");
1716
        ffio_wfourcc(pb, "USMT");
1717
        avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
1718
        avio_wb32(pb, 0xbb88695c);
1719
        avio_wb32(pb, 0xfac9c740);
1720

    
1721
        pos2 = url_ftell(pb);
1722
        avio_wb32(pb, 0); /* size placeholder*/
1723
        ffio_wfourcc(pb, "MTDT");
1724
        avio_wb16(pb, 4);
1725

    
1726
        // ?
1727
        avio_wb16(pb, 0x0C);                 /* size */
1728
        avio_wb32(pb, 0x0B);                 /* type */
1729
        avio_wb16(pb, language_code("und")); /* language */
1730
        avio_wb16(pb, 0x0);                  /* ? */
1731
        avio_wb16(pb, 0x021C);               /* data */
1732

    
1733
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1734
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1735
//        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);
1736
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1737

    
1738
        updateSize(pb, pos2);
1739
        return updateSize(pb, pos);
1740
    }
1741

    
1742
    return 0;
1743
}
1744

    
1745
static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
1746
                              AVFormatContext *s)
1747
{
1748
    int i;
1749
    int64_t pos = url_ftell(pb);
1750
    avio_wb32(pb, 0); /* size placeholder*/
1751
    ffio_wfourcc(pb, "moov");
1752

    
1753
    for (i=0; i<mov->nb_streams; i++) {
1754
        if(mov->tracks[i].entry <= 0) continue;
1755

    
1756
        mov->tracks[i].time = mov->time;
1757
        mov->tracks[i].trackID = i+1;
1758
    }
1759

    
1760
    if (mov->chapter_track)
1761
        for (i=0; i<s->nb_streams; i++) {
1762
            mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
1763
            mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].trackID;
1764
        }
1765
    for (i = 0; i < mov->nb_streams; i++) {
1766
        if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
1767
            mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
1768
            mov->tracks[i].tref_id =
1769
                mov->tracks[mov->tracks[i].src_track].trackID;
1770
        }
1771
    }
1772

    
1773
    mov_write_mvhd_tag(pb, mov);
1774
    //mov_write_iods_tag(pb, mov);
1775
    for (i=0; i<mov->nb_streams; i++) {
1776
        if(mov->tracks[i].entry > 0) {
1777
            mov_write_trak_tag(pb, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
1778
        }
1779
    }
1780

    
1781
    if (mov->mode == MODE_PSP)
1782
        mov_write_uuidusmt_tag(pb, s);
1783
    else
1784
        mov_write_udta_tag(pb, mov, s);
1785

    
1786
    return updateSize(pb, pos);
1787
}
1788

    
1789
static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
1790
{
1791
    avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
1792
    ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
1793

    
1794
    mov->mdat_pos = url_ftell(pb);
1795
    avio_wb32(pb, 0); /* size placeholder*/
1796
    ffio_wfourcc(pb, "mdat");
1797
    return 0;
1798
}
1799

    
1800
/* TODO: This needs to be more general */
1801
static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
1802
{
1803
    MOVMuxContext *mov = s->priv_data;
1804
    int64_t pos = url_ftell(pb);
1805
    int has_h264 = 0, has_video = 0;
1806
    int minor = 0x200;
1807
    int i;
1808

    
1809
    for (i = 0; i < s->nb_streams; i++) {
1810
        AVStream *st = s->streams[i];
1811
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1812
            has_video = 1;
1813
        if (st->codec->codec_id == CODEC_ID_H264)
1814
            has_h264 = 1;
1815
    }
1816

    
1817
    avio_wb32(pb, 0); /* size */
1818
    ffio_wfourcc(pb, "ftyp");
1819

    
1820
    if (mov->mode == MODE_3GP) {
1821
        ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
1822
        minor =     has_h264 ?   0x100 :   0x200;
1823
    } else if (mov->mode & MODE_3G2) {
1824
        ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
1825
        minor =     has_h264 ? 0x20000 : 0x10000;
1826
    }else if (mov->mode == MODE_PSP)
1827
        ffio_wfourcc(pb, "MSNV");
1828
    else if (mov->mode == MODE_MP4)
1829
        ffio_wfourcc(pb, "isom");
1830
    else if (mov->mode == MODE_IPOD)
1831
        ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
1832
    else
1833
        ffio_wfourcc(pb, "qt  ");
1834

    
1835
    avio_wb32(pb, minor);
1836

    
1837
    if(mov->mode == MODE_MOV)
1838
        ffio_wfourcc(pb, "qt  ");
1839
    else{
1840
        ffio_wfourcc(pb, "isom");
1841
        ffio_wfourcc(pb, "iso2");
1842
        if(has_h264)
1843
            ffio_wfourcc(pb, "avc1");
1844
    }
1845

    
1846
    if (mov->mode == MODE_3GP)
1847
        ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
1848
    else if (mov->mode & MODE_3G2)
1849
        ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
1850
    else if (mov->mode == MODE_PSP)
1851
        ffio_wfourcc(pb, "MSNV");
1852
    else if (mov->mode == MODE_MP4)
1853
        ffio_wfourcc(pb, "mp41");
1854
    return updateSize(pb, pos);
1855
}
1856

    
1857
static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
1858
{
1859
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1860
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1861
    int AudioRate = AudioCodec->sample_rate;
1862
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1863
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1864
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1865

    
1866
    avio_wb32(pb, 0x94); /* size */
1867
    ffio_wfourcc(pb, "uuid");
1868
    ffio_wfourcc(pb, "PROF");
1869

    
1870
    avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
1871
    avio_wb32(pb, 0xbb88695c);
1872
    avio_wb32(pb, 0xfac9c740);
1873

    
1874
    avio_wb32(pb, 0x0);  /* ? */
1875
    avio_wb32(pb, 0x3);  /* 3 sections ? */
1876

    
1877
    avio_wb32(pb, 0x14); /* size */
1878
    ffio_wfourcc(pb, "FPRF");
1879
    avio_wb32(pb, 0x0);  /* ? */
1880
    avio_wb32(pb, 0x0);  /* ? */
1881
    avio_wb32(pb, 0x0);  /* ? */
1882

    
1883
    avio_wb32(pb, 0x2c);  /* size */
1884
    ffio_wfourcc(pb, "APRF");/* audio */
1885
    avio_wb32(pb, 0x0);
1886
    avio_wb32(pb, 0x2);   /* TrackID */
1887
    ffio_wfourcc(pb, "mp4a");
1888
    avio_wb32(pb, 0x20f);
1889
    avio_wb32(pb, 0x0);
1890
    avio_wb32(pb, audio_kbitrate);
1891
    avio_wb32(pb, audio_kbitrate);
1892
    avio_wb32(pb, AudioRate);
1893
    avio_wb32(pb, AudioCodec->channels);
1894

    
1895
    avio_wb32(pb, 0x34);  /* size */
1896
    ffio_wfourcc(pb, "VPRF");   /* video */
1897
    avio_wb32(pb, 0x0);
1898
    avio_wb32(pb, 0x1);    /* TrackID */
1899
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1900
        ffio_wfourcc(pb, "avc1");
1901
        avio_wb16(pb, 0x014D);
1902
        avio_wb16(pb, 0x0015);
1903
    } else {
1904
        ffio_wfourcc(pb, "mp4v");
1905
        avio_wb16(pb, 0x0000);
1906
        avio_wb16(pb, 0x0103);
1907
    }
1908
    avio_wb32(pb, 0x0);
1909
    avio_wb32(pb, video_kbitrate);
1910
    avio_wb32(pb, video_kbitrate);
1911
    avio_wb32(pb, FrameRate);
1912
    avio_wb32(pb, FrameRate);
1913
    avio_wb16(pb, VideoCodec->width);
1914
    avio_wb16(pb, VideoCodec->height);
1915
    avio_wb32(pb, 0x010001); /* ? */
1916
}
1917

    
1918
static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
1919
{
1920
    uint32_t c = -1;
1921
    int i, closed_gop = 0;
1922

    
1923
    for (i = 0; i < pkt->size - 4; i++) {
1924
        c = (c<<8) + pkt->data[i];
1925
        if (c == 0x1b8) { // gop
1926
            closed_gop = pkt->data[i+4]>>6 & 0x01;
1927
        } else if (c == 0x100) { // pic
1928
            int temp_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
1929
            if (!temp_ref || closed_gop) // I picture is not reordered
1930
                *flags = MOV_SYNC_SAMPLE;
1931
            else
1932
                *flags = MOV_PARTIAL_SYNC_SAMPLE;
1933
            break;
1934
        }
1935
    }
1936
    return 0;
1937
}
1938

    
1939
int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1940
{
1941
    MOVMuxContext *mov = s->priv_data;
1942
    AVIOContext *pb = s->pb;
1943
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1944
    AVCodecContext *enc = trk->enc;
1945
    unsigned int samplesInChunk = 0;
1946
    int size= pkt->size;
1947

    
1948
    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1949
    if (!size) return 0; /* Discard 0 sized packets */
1950

    
1951
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1952
        /* We must find out how many AMR blocks there are in one packet */
1953
        static uint16_t packed_size[16] =
1954
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1955
        int len = 0;
1956

    
1957
        while (len < size && samplesInChunk < 100) {
1958
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1959
            samplesInChunk++;
1960
        }
1961
        if(samplesInChunk > 1){
1962
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
1963
            return -1;
1964
        }
1965
    } else if (enc->codec_id == CODEC_ID_ADPCM_MS ||
1966
               enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
1967
        samplesInChunk = enc->frame_size;
1968
    } else if (trk->sampleSize)
1969
        samplesInChunk = size/trk->sampleSize;
1970
    else
1971
        samplesInChunk = 1;
1972

    
1973
    /* copy extradata if it exists */
1974
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1975
        trk->vosLen = enc->extradata_size;
1976
        trk->vosData = av_malloc(trk->vosLen);
1977
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1978
    }
1979

    
1980
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1981
        /* from x264 or from bytestream h264 */
1982
        /* nal reformating needed */
1983
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1984
    } else {
1985
        avio_write(pb, pkt->data, size);
1986
    }
1987

    
1988
    if ((enc->codec_id == CODEC_ID_DNXHD ||
1989
         enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
1990
        /* copy frame to create needed atoms */
1991
        trk->vosLen = size;
1992
        trk->vosData = av_malloc(size);
1993
        if (!trk->vosData)
1994
            return AVERROR(ENOMEM);
1995
        memcpy(trk->vosData, pkt->data, size);
1996
    }
1997

    
1998
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1999
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
2000
        if (!trk->cluster)
2001
            return -1;
2002
    }
2003

    
2004
    trk->cluster[trk->entry].pos = url_ftell(pb) - size;
2005
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
2006
    trk->cluster[trk->entry].size = size;
2007
    trk->cluster[trk->entry].entries = samplesInChunk;
2008
    trk->cluster[trk->entry].dts = pkt->dts;
2009
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
2010

    
2011
    if (pkt->pts == AV_NOPTS_VALUE) {
2012
        av_log(s, AV_LOG_WARNING, "pts has no value\n");
2013
        pkt->pts = pkt->dts;
2014
    }
2015
    if (pkt->dts != pkt->pts)
2016
        trk->flags |= MOV_TRACK_CTTS;
2017
    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
2018
    trk->cluster[trk->entry].flags = 0;
2019
    if (pkt->flags & AV_PKT_FLAG_KEY) {
2020
        if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO &&
2021
            trk->entry > 0) { // force sync sample for the first key frame
2022
            mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
2023
            if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
2024
                trk->flags |= MOV_TRACK_STPS;
2025
        } else {
2026
            trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
2027
        }
2028
        if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
2029
            trk->hasKeyframes++;
2030
    }
2031
    trk->entry++;
2032
    trk->sampleCount += samplesInChunk;
2033
    mov->mdat_size += size;
2034

    
2035
    put_flush_packet(pb);
2036

    
2037
    if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
2038
        ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry);
2039
    return 0;
2040
}
2041

    
2042
// QuickTime chapters involve an additional text track with the chapter names
2043
// as samples, and a tref pointing from the other tracks to the chapter one.
2044
static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
2045
{
2046
    MOVMuxContext *mov = s->priv_data;
2047
    MOVTrack *track = &mov->tracks[tracknum];
2048
    AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
2049
    int i, len;
2050

    
2051
    track->mode = mov->mode;
2052
    track->tag = MKTAG('t','e','x','t');
2053
    track->timescale = MOV_TIMESCALE;
2054
    track->enc = avcodec_alloc_context();
2055
    track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
2056

    
2057
    for (i = 0; i < s->nb_chapters; i++) {
2058
        AVChapter *c = s->chapters[i];
2059
        AVMetadataTag *t;
2060

    
2061
        int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
2062
        pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
2063
        pkt.duration = end - pkt.dts;
2064

    
2065
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
2066
            len = strlen(t->value);
2067
            pkt.size = len+2;
2068
            pkt.data = av_malloc(pkt.size);
2069
            AV_WB16(pkt.data, len);
2070
            memcpy(pkt.data+2, t->value, len);
2071
            ff_mov_write_packet(s, &pkt);
2072
            av_freep(&pkt.data);
2073
        }
2074
    }
2075
}
2076

    
2077
static int mov_write_header(AVFormatContext *s)
2078
{
2079
    AVIOContext *pb = s->pb;
2080
    MOVMuxContext *mov = s->priv_data;
2081
    int i, hint_track = 0;
2082

    
2083
    if (url_is_streamed(s->pb)) {
2084
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
2085
        return -1;
2086
    }
2087

    
2088
    /* Default mode == MP4 */
2089
    mov->mode = MODE_MP4;
2090

    
2091
    if (s->oformat != NULL) {
2092
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
2093
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
2094
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
2095
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
2096
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
2097

    
2098
        mov_write_ftyp_tag(pb,s);
2099
        if (mov->mode == MODE_PSP) {
2100
            if (s->nb_streams != 2) {
2101
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
2102
                return -1;
2103
            }
2104
            mov_write_uuidprof_tag(pb,s);
2105
        }
2106
    }
2107

    
2108
    mov->nb_streams = s->nb_streams;
2109
    if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
2110
        mov->chapter_track = mov->nb_streams++;
2111

    
2112
    if (s->flags & AVFMT_FLAG_RTP_HINT) {
2113
        /* Add hint tracks for each audio and video stream */
2114
        hint_track = mov->nb_streams;
2115
        for (i = 0; i < s->nb_streams; i++) {
2116
            AVStream *st = s->streams[i];
2117
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2118
                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2119
                mov->nb_streams++;
2120
            }
2121
        }
2122
    }
2123

    
2124
    mov->tracks = av_mallocz(mov->nb_streams*sizeof(*mov->tracks));
2125
    if (!mov->tracks)
2126
        return AVERROR(ENOMEM);
2127

    
2128
    for(i=0; i<s->nb_streams; i++){
2129
        AVStream *st= s->streams[i];
2130
        MOVTrack *track= &mov->tracks[i];
2131
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
2132

    
2133
        track->enc = st->codec;
2134
        track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
2135
        if (track->language < 0)
2136
            track->language = 0;
2137
        track->mode = mov->mode;
2138
        track->tag = mov_find_codec_tag(s, track);
2139
        if (!track->tag) {
2140
            av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
2141
                   "codec not currently supported in container\n", i);
2142
            goto error;
2143
        }
2144
        /* If hinting of this track is enabled by a later hint track,
2145
         * this is updated. */
2146
        track->hint_track = -1;
2147
        if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2148
            if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
2149
                track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
2150
                track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
2151
                if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
2152
                    av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
2153
                    goto error;
2154
                }
2155
                track->height = track->tag>>24 == 'n' ? 486 : 576;
2156
            }
2157
            track->timescale = st->codec->time_base.den;
2158
            if (track->mode == MODE_MOV && track->timescale > 100000)
2159
                av_log(s, AV_LOG_WARNING,
2160
                       "WARNING codec timebase is very high. If duration is too long,\n"
2161
                       "file may not be playable by quicktime. Specify a shorter timebase\n"
2162
                       "or choose different container.\n");
2163
        }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO){
2164
            track->timescale = st->codec->sample_rate;
2165
            if(!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
2166
                av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
2167
                goto error;
2168
            }else if(st->codec->codec_id == CODEC_ID_ADPCM_MS ||
2169
                     st->codec->codec_id == CODEC_ID_ADPCM_IMA_WAV){
2170
                if (!st->codec->block_align) {
2171
                    av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
2172
                    goto error;
2173
                }
2174
                track->sampleSize = st->codec->block_align;
2175
            }else if(st->codec->frame_size > 1){ /* assume compressed audio */
2176
                track->audio_vbr = 1;
2177
            }else{
2178
                st->codec->frame_size = 1;
2179
                track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
2180
            }
2181
            if (track->mode != MODE_MOV) {
2182
                if (track->timescale > UINT16_MAX) {
2183
                    av_log(s, AV_LOG_ERROR, "track %d: output format does not support "
2184
                           "sample rate %dhz\n", i, track->timescale);
2185
                    goto error;
2186
                }
2187
                if (track->enc->codec_id == CODEC_ID_MP3 && track->timescale < 16000) {
2188
                    av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
2189
                           i, track->enc->sample_rate);
2190
                    goto error;
2191
                }
2192
            }
2193
        }else if(st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE){
2194
            track->timescale = st->codec->time_base.den;
2195
        }
2196
        if (!track->height)
2197
            track->height = st->codec->height;
2198

    
2199
        av_set_pts_info(st, 64, 1, track->timescale);
2200
    }
2201

    
2202
    mov_write_mdat_tag(pb, mov);
2203
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
2204

    
2205
    if (mov->chapter_track)
2206
        mov_create_chapter_track(s, mov->chapter_track);
2207

    
2208
    if (s->flags & AVFMT_FLAG_RTP_HINT) {
2209
        /* Initialize the hint tracks for each audio and video stream */
2210
        for (i = 0; i < s->nb_streams; i++) {
2211
            AVStream *st = s->streams[i];
2212
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2213
                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2214
                ff_mov_init_hinting(s, hint_track, i);
2215
                hint_track++;
2216
            }
2217
        }
2218
    }
2219

    
2220
    put_flush_packet(pb);
2221

    
2222
    return 0;
2223
 error:
2224
    av_freep(&mov->tracks);
2225
    return -1;
2226
}
2227

    
2228
static int mov_write_trailer(AVFormatContext *s)
2229
{
2230
    MOVMuxContext *mov = s->priv_data;
2231
    AVIOContext *pb = s->pb;
2232
    int res = 0;
2233
    int i;
2234

    
2235
    int64_t moov_pos = url_ftell(pb);
2236

    
2237
    /* Write size of mdat tag */
2238
    if (mov->mdat_size+8 <= UINT32_MAX) {
2239
        avio_seek(pb, mov->mdat_pos, SEEK_SET);
2240
        avio_wb32(pb, mov->mdat_size+8);
2241
    } else {
2242
        /* overwrite 'wide' placeholder atom */
2243
        avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
2244
        avio_wb32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
2245
        ffio_wfourcc(pb, "mdat");
2246
        avio_wb64(pb, mov->mdat_size+16);
2247
    }
2248
    avio_seek(pb, moov_pos, SEEK_SET);
2249

    
2250
    mov_write_moov_tag(pb, mov, s);
2251

    
2252
    if (mov->chapter_track)
2253
        av_freep(&mov->tracks[mov->chapter_track].enc);
2254

    
2255
    for (i=0; i<mov->nb_streams; i++) {
2256
        if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
2257
            ff_mov_close_hinting(&mov->tracks[i]);
2258
        av_freep(&mov->tracks[i].cluster);
2259

    
2260
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2261

    
2262
    }
2263

    
2264
    put_flush_packet(pb);
2265

    
2266
    av_freep(&mov->tracks);
2267

    
2268
    return res;
2269
}
2270

    
2271
#if CONFIG_MOV_MUXER
2272
AVOutputFormat ff_mov_muxer = {
2273
    "mov",
2274
    NULL_IF_CONFIG_SMALL("MOV format"),
2275
    NULL,
2276
    "mov",
2277
    sizeof(MOVMuxContext),
2278
    CODEC_ID_AAC,
2279
    CODEC_ID_MPEG4,
2280
    mov_write_header,
2281
    ff_mov_write_packet,
2282
    mov_write_trailer,
2283
    .flags = AVFMT_GLOBALHEADER,
2284
    .codec_tag = (const AVCodecTag* const []){codec_movvideo_tags, codec_movaudio_tags, 0},
2285
};
2286
#endif
2287
#if CONFIG_TGP_MUXER
2288
AVOutputFormat ff_tgp_muxer = {
2289
    "3gp",
2290
    NULL_IF_CONFIG_SMALL("3GP format"),
2291
    NULL,
2292
    "3gp",
2293
    sizeof(MOVMuxContext),
2294
    CODEC_ID_AMR_NB,
2295
    CODEC_ID_H263,
2296
    mov_write_header,
2297
    ff_mov_write_packet,
2298
    mov_write_trailer,
2299
    .flags = AVFMT_GLOBALHEADER,
2300
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2301
};
2302
#endif
2303
#if CONFIG_MP4_MUXER
2304
AVOutputFormat ff_mp4_muxer = {
2305
    "mp4",
2306
    NULL_IF_CONFIG_SMALL("MP4 format"),
2307
    "application/mp4",
2308
    "mp4",
2309
    sizeof(MOVMuxContext),
2310
    CODEC_ID_AAC,
2311
    CODEC_ID_MPEG4,
2312
    mov_write_header,
2313
    ff_mov_write_packet,
2314
    mov_write_trailer,
2315
    .flags = AVFMT_GLOBALHEADER,
2316
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2317
};
2318
#endif
2319
#if CONFIG_PSP_MUXER
2320
AVOutputFormat ff_psp_muxer = {
2321
    "psp",
2322
    NULL_IF_CONFIG_SMALL("PSP MP4 format"),
2323
    NULL,
2324
    "mp4,psp",
2325
    sizeof(MOVMuxContext),
2326
    CODEC_ID_AAC,
2327
    CODEC_ID_MPEG4,
2328
    mov_write_header,
2329
    ff_mov_write_packet,
2330
    mov_write_trailer,
2331
    .flags = AVFMT_GLOBALHEADER,
2332
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2333
};
2334
#endif
2335
#if CONFIG_TG2_MUXER
2336
AVOutputFormat ff_tg2_muxer = {
2337
    "3g2",
2338
    NULL_IF_CONFIG_SMALL("3GP2 format"),
2339
    NULL,
2340
    "3g2",
2341
    sizeof(MOVMuxContext),
2342
    CODEC_ID_AMR_NB,
2343
    CODEC_ID_H263,
2344
    mov_write_header,
2345
    ff_mov_write_packet,
2346
    mov_write_trailer,
2347
    .flags = AVFMT_GLOBALHEADER,
2348
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2349
};
2350
#endif
2351
#if CONFIG_IPOD_MUXER
2352
AVOutputFormat ff_ipod_muxer = {
2353
    "ipod",
2354
    NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
2355
    "application/mp4",
2356
    "m4v,m4a",
2357
    sizeof(MOVMuxContext),
2358
    CODEC_ID_AAC,
2359
    CODEC_ID_H264,
2360
    mov_write_header,
2361
    ff_mov_write_packet,
2362
    mov_write_trailer,
2363
    .flags = AVFMT_GLOBALHEADER,
2364
    .codec_tag = (const AVCodecTag* const []){codec_ipod_tags, 0},
2365
};
2366
#endif