Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 32442930

History | View | Annotate | Download (76.9 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
    url_fseek(pb, pos, SEEK_SET);
44
    avio_wb32(pb, curpos - pos); /* rewrite size */
45
    url_fseek(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
        avio_wb32(pb, sSize); // sample size
95
        avio_wb32(pb, entries); // sample count
96
    }
97
    else {
98
        avio_wb32(pb, 0); // sample size
99
        avio_wb32(pb, entries); // sample count
100
        for (i=0; i<track->entry; i++) {
101
            for (j=0; j<track->cluster[i].entries; j++) {
102
                avio_wb32(pb, track->cluster[i].size /
103
                         track->cluster[i].entries);
104
            }
105
        }
106
    }
107
    return updateSize(pb, pos);
108
}
109

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

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

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

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

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

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

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

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

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

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

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

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

    
219
    return 11;
220
}
221

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
591
    return tag;
592
}
593

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

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

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

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

    
619
    return tag;
620
}
621

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

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

    
633
    return tag;
634
}
635

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

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

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

    
670
    return tag;
671
}
672

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

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

    
708
    return tag;
709
}
710

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

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

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

    
735
    return tag;
736
}
737

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

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

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

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

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

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

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

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

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

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

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

    
843
    if (track->mode == MODE_MOV &&
844
        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
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1220
        if(!sample_aspect_ratio || track->height != track->enc->height)
1221
            sample_aspect_ratio = 1;
1222
        avio_wb32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1223
        avio_wb32(pb, track->height*0x10000);
1224
    }
1225
    else {
1226
        avio_wb32(pb, 0);
1227
        avio_wb32(pb, 0);
1228
    }
1229
    return 0x5c;
1230
}
1231

    
1232
// This box seems important for the psp playback ... without it the movie seems to hang
1233
static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1234
{
1235
    avio_wb32(pb, 0x24); /* size  */
1236
    ffio_wfourcc(pb, "edts");
1237
    avio_wb32(pb, 0x1c); /* size  */
1238
    ffio_wfourcc(pb, "elst");
1239
    avio_wb32(pb, 0x0);
1240
    avio_wb32(pb, 0x1);
1241

    
1242
    /* duration   ... doesn't seem to effect psp */
1243
    avio_wb32(pb, av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1244
                                track->timescale, AV_ROUND_UP));
1245

    
1246
    avio_wb32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
1247
    avio_wb32(pb, 0x00010000);
1248
    return 0x24;
1249
}
1250

    
1251
static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1252
{
1253
    avio_wb32(pb, 20);   // size
1254
    ffio_wfourcc(pb, "tref");
1255
    avio_wb32(pb, 12);   // size (subatom)
1256
    avio_wl32(pb, track->tref_tag);
1257
    avio_wb32(pb, track->tref_id);
1258
    return 20;
1259
}
1260

    
1261
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1262
static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1263
{
1264
    avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1265
    ffio_wfourcc(pb, "uuid");
1266
    ffio_wfourcc(pb, "USMT");
1267
    avio_wb32(pb, 0x21d24fce);
1268
    avio_wb32(pb, 0xbb88695c);
1269
    avio_wb32(pb, 0xfac9c740);
1270
    avio_wb32(pb, 0x1c);     // another size here!
1271
    ffio_wfourcc(pb, "MTDT");
1272
    avio_wb32(pb, 0x00010012);
1273
    avio_wb32(pb, 0x0a);
1274
    avio_wb32(pb, 0x55c40000);
1275
    avio_wb32(pb, 0x1);
1276
    avio_wb32(pb, 0x0);
1277
    return 0x34;
1278
}
1279

    
1280
static int mov_write_udta_sdp(AVIOContext *pb, AVCodecContext *ctx, int index)
1281
{
1282
    char buf[1000] = "";
1283
    int len;
1284

    
1285
    ff_sdp_write_media(buf, sizeof(buf), ctx, NULL, NULL, 0, 0);
1286
    av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", index);
1287
    len = strlen(buf);
1288

    
1289
    avio_wb32(pb, len + 24);
1290
    ffio_wfourcc(pb, "udta");
1291
    avio_wb32(pb, len + 16);
1292
    ffio_wfourcc(pb, "hnti");
1293
    avio_wb32(pb, len + 8);
1294
    ffio_wfourcc(pb, "sdp ");
1295
    avio_write(pb, buf, len);
1296
    return len + 24;
1297
}
1298

    
1299
static int mov_write_trak_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1300
{
1301
    int64_t pos = url_ftell(pb);
1302
    avio_wb32(pb, 0); /* size */
1303
    ffio_wfourcc(pb, "trak");
1304
    mov_write_tkhd_tag(pb, track, st);
1305
    if (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS)
1306
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1307
    if (track->tref_tag)
1308
        mov_write_tref_tag(pb, track);
1309
    mov_write_mdia_tag(pb, track);
1310
    if (track->mode == MODE_PSP)
1311
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1312
    if (track->tag == MKTAG('r','t','p',' '))
1313
        mov_write_udta_sdp(pb, track->rtp_ctx->streams[0]->codec, track->trackID);
1314
    return updateSize(pb, pos);
1315
}
1316

    
1317
#if 0
1318
/* TODO: Not sorted out, but not necessary either */
1319
static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1320
{
1321
    avio_wb32(pb, 0x15); /* size */
1322
    ffio_wfourcc(pb, "iods");
1323
    avio_wb32(pb, 0);    /* version & flags */
1324
    avio_wb16(pb, 0x1007);
1325
    avio_w8(pb, 0);
1326
    avio_wb16(pb, 0x4fff);
1327
    avio_wb16(pb, 0xfffe);
1328
    avio_wb16(pb, 0x01ff);
1329
    return 0x15;
1330
}
1331
#endif
1332

    
1333
static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
1334
{
1335
    int maxTrackID = 1, i;
1336
    int64_t maxTrackLenTemp, maxTrackLen = 0;
1337
    int version;
1338

    
1339
    for (i=0; i<mov->nb_streams; i++) {
1340
        if(mov->tracks[i].entry > 0) {
1341
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration,
1342
                                             MOV_TIMESCALE,
1343
                                             mov->tracks[i].timescale,
1344
                                             AV_ROUND_UP);
1345
            if(maxTrackLen < maxTrackLenTemp)
1346
                maxTrackLen = maxTrackLenTemp;
1347
            if(maxTrackID < mov->tracks[i].trackID)
1348
                maxTrackID = mov->tracks[i].trackID;
1349
        }
1350
    }
1351

    
1352
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1353
    (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
1354
    ffio_wfourcc(pb, "mvhd");
1355
    avio_w8(pb, version);
1356
    avio_wb24(pb, 0); /* flags */
1357
    if (version == 1) {
1358
        avio_wb64(pb, mov->time);
1359
        avio_wb64(pb, mov->time);
1360
    } else {
1361
        avio_wb32(pb, mov->time); /* creation time */
1362
        avio_wb32(pb, mov->time); /* modification time */
1363
    }
1364
    avio_wb32(pb, MOV_TIMESCALE);
1365
    (version == 1) ? avio_wb64(pb, maxTrackLen) : avio_wb32(pb, maxTrackLen); /* duration of longest track */
1366

    
1367
    avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1368
    avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1369
    avio_wb16(pb, 0); /* reserved */
1370
    avio_wb32(pb, 0); /* reserved */
1371
    avio_wb32(pb, 0); /* reserved */
1372

    
1373
    /* Matrix structure */
1374
    avio_wb32(pb, 0x00010000); /* reserved */
1375
    avio_wb32(pb, 0x0); /* reserved */
1376
    avio_wb32(pb, 0x0); /* reserved */
1377
    avio_wb32(pb, 0x0); /* reserved */
1378
    avio_wb32(pb, 0x00010000); /* reserved */
1379
    avio_wb32(pb, 0x0); /* reserved */
1380
    avio_wb32(pb, 0x0); /* reserved */
1381
    avio_wb32(pb, 0x0); /* reserved */
1382
    avio_wb32(pb, 0x40000000); /* reserved */
1383

    
1384
    avio_wb32(pb, 0); /* reserved (preview time) */
1385
    avio_wb32(pb, 0); /* reserved (preview duration) */
1386
    avio_wb32(pb, 0); /* reserved (poster time) */
1387
    avio_wb32(pb, 0); /* reserved (selection time) */
1388
    avio_wb32(pb, 0); /* reserved (selection duration) */
1389
    avio_wb32(pb, 0); /* reserved (current time) */
1390
    avio_wb32(pb, maxTrackID+1); /* Next track id */
1391
    return 0x6c;
1392
}
1393

    
1394
static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
1395
                                     AVFormatContext *s)
1396
{
1397
    avio_wb32(pb, 33); /* size */
1398
    ffio_wfourcc(pb, "hdlr");
1399
    avio_wb32(pb, 0);
1400
    avio_wb32(pb, 0);
1401
    ffio_wfourcc(pb, "mdir");
1402
    ffio_wfourcc(pb, "appl");
1403
    avio_wb32(pb, 0);
1404
    avio_wb32(pb, 0);
1405
    avio_w8(pb, 0);
1406
    return 33;
1407
}
1408

    
1409
/* helper function to write a data tag with the specified string as data */
1410
static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
1411
{
1412
    if(long_style){
1413
        int size = 16 + strlen(data);
1414
        avio_wb32(pb, size); /* size */
1415
        ffio_wfourcc(pb, "data");
1416
        avio_wb32(pb, 1);
1417
        avio_wb32(pb, 0);
1418
        avio_write(pb, data, strlen(data));
1419
        return size;
1420
    }else{
1421
        if (!lang)
1422
            lang = ff_mov_iso639_to_lang("und", 1);
1423
        avio_wb16(pb, strlen(data)); /* string length */
1424
        avio_wb16(pb, lang);
1425
        avio_write(pb, data, strlen(data));
1426
        return strlen(data) + 4;
1427
    }
1428
}
1429

    
1430
static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style){
1431
    int size = 0;
1432
    if (value && value[0]) {
1433
        int64_t pos = url_ftell(pb);
1434
        avio_wb32(pb, 0); /* size */
1435
        ffio_wfourcc(pb, name);
1436
        mov_write_string_data_tag(pb, value, lang, long_style);
1437
        size= updateSize(pb, pos);
1438
    }
1439
    return size;
1440
}
1441

    
1442
static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
1443
                                     const char *name, const char *tag,
1444
                                     int long_style)
1445
{
1446
    int l, lang = 0, len, len2;
1447
    AVMetadataTag *t, *t2 = NULL;
1448
    char tag2[16];
1449

    
1450
    if (!(t = av_metadata_get(s->metadata, tag, NULL, 0)))
1451
        return 0;
1452

    
1453
    len = strlen(t->key);
1454
    snprintf(tag2, sizeof(tag2), "%s-", tag);
1455
    while ((t2 = av_metadata_get(s->metadata, tag2, t2, AV_METADATA_IGNORE_SUFFIX))) {
1456
        len2 = strlen(t2->key);
1457
        if (len2 == len+4 && !strcmp(t->value, t2->value)
1458
            && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 1)) >= 0) {
1459
            lang = l;
1460
            break;
1461
        }
1462
    }
1463
    return mov_write_string_tag(pb, name, t->value, lang, long_style);
1464
}
1465

    
1466
/* iTunes track number */
1467
static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
1468
                              AVFormatContext *s)
1469
{
1470
    AVMetadataTag *t = av_metadata_get(s->metadata, "track", NULL, 0);
1471
    int size = 0, track = t ? atoi(t->value) : 0;
1472
    if (track) {
1473
        avio_wb32(pb, 32); /* size */
1474
        ffio_wfourcc(pb, "trkn");
1475
            avio_wb32(pb, 24); /* size */
1476
            ffio_wfourcc(pb, "data");
1477
            avio_wb32(pb, 0);        // 8 bytes empty
1478
            avio_wb32(pb, 0);
1479
            avio_wb16(pb, 0);        // empty
1480
            avio_wb16(pb, track);    // track number
1481
            avio_wb16(pb, 0);        // total track number
1482
            avio_wb16(pb, 0);        // empty
1483
        size = 32;
1484
    }
1485
    return size;
1486
}
1487

    
1488
/* iTunes meta data list */
1489
static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
1490
                              AVFormatContext *s)
1491
{
1492
    int64_t pos = url_ftell(pb);
1493
    avio_wb32(pb, 0); /* size */
1494
    ffio_wfourcc(pb, "ilst");
1495
    mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1496
    mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
1497
    mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
1498
    mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1499
    mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1500
    mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
1501
    mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1502
    mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1503
    mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1504
    mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1505
    mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
1506
    mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
1507
    mov_write_string_metadata(s, pb, "desc",    "description",1);
1508
    mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
1509
    mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
1510
    mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
1511
    mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
1512
    mov_write_trkn_tag(pb, mov, s);
1513
    return updateSize(pb, pos);
1514
}
1515

    
1516
/* iTunes meta data tag */
1517
static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
1518
                              AVFormatContext *s)
1519
{
1520
    int size = 0;
1521
    int64_t pos = url_ftell(pb);
1522
    avio_wb32(pb, 0); /* size */
1523
    ffio_wfourcc(pb, "meta");
1524
    avio_wb32(pb, 0);
1525
    mov_write_itunes_hdlr_tag(pb, mov, s);
1526
    mov_write_ilst_tag(pb, mov, s);
1527
    size = updateSize(pb, pos);
1528
    return size;
1529
}
1530

    
1531
static int utf8len(const uint8_t *b)
1532
{
1533
    int len=0;
1534
    int val;
1535
    while(*b){
1536
        GET_UTF8(val, *b++, return -1;)
1537
        len++;
1538
    }
1539
    return len;
1540
}
1541

    
1542
static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
1543
{
1544
    int val;
1545
    while(*b){
1546
        GET_UTF8(val, *b++, return -1;)
1547
        avio_wb16(pb, val);
1548
    }
1549
    avio_wb16(pb, 0x00);
1550
    return 0;
1551
}
1552

    
1553
static uint16_t language_code(const char *str)
1554
{
1555
    return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1556
}
1557

    
1558
static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
1559
                                  const char *tag, const char *str)
1560
{
1561
    int64_t pos = url_ftell(pb);
1562
    AVMetadataTag *t = av_metadata_get(s->metadata, str, NULL, 0);
1563
    if (!t || !utf8len(t->value))
1564
        return 0;
1565
    avio_wb32(pb, 0);   /* size */
1566
    ffio_wfourcc(pb, tag); /* type */
1567
    avio_wb32(pb, 0);   /* version + flags */
1568
    if (!strcmp(tag, "yrrc"))
1569
        avio_wb16(pb, atoi(t->value));
1570
    else {
1571
        avio_wb16(pb, language_code("eng")); /* language */
1572
        avio_write(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
1573
        if (!strcmp(tag, "albm") &&
1574
            (t = av_metadata_get(s->metadata, "track", NULL, 0)))
1575
            avio_w8(pb, atoi(t->value));
1576
    }
1577
    return updateSize(pb, pos);
1578
}
1579

    
1580
static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
1581
{
1582
    int64_t pos = url_ftell(pb);
1583
    int i, nb_chapters = FFMIN(s->nb_chapters, 255);
1584

    
1585
    avio_wb32(pb, 0);            // size
1586
    ffio_wfourcc(pb, "chpl");
1587
    avio_wb32(pb, 0x01000000);   // version + flags
1588
    avio_wb32(pb, 0);            // unknown
1589
    avio_w8(pb, nb_chapters);
1590

    
1591
    for (i = 0; i < nb_chapters; i++) {
1592
        AVChapter *c = s->chapters[i];
1593
        AVMetadataTag *t;
1594
        avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
1595

    
1596
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
1597
            int len = FFMIN(strlen(t->value), 255);
1598
            avio_w8(pb, len);
1599
            avio_write(pb, t->value, len);
1600
        } else
1601
            avio_w8(pb, 0);
1602
    }
1603
    return updateSize(pb, pos);
1604
}
1605

    
1606
static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
1607
                              AVFormatContext *s)
1608
{
1609
    AVIOContext *pb_buf;
1610
    int i, ret, size;
1611
    uint8_t *buf;
1612

    
1613
    for (i = 0; i < s->nb_streams; i++)
1614
        if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1615
            return 0;
1616
        }
1617

    
1618
    ret = url_open_dyn_buf(&pb_buf);
1619
    if(ret < 0)
1620
        return ret;
1621

    
1622
        if (mov->mode & MODE_3GP) {
1623
            mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
1624
            mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1625
            mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1626
            mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1627
            mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1628
            mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1629
            mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1630
            mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
1631
        } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1632
            mov_write_string_metadata(s, pb_buf, "\251ART", "artist"     , 0);
1633
            mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
1634
            mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
1635
            mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
1636
            mov_write_string_metadata(s, pb_buf, "\251day", "date"       , 0);
1637
            mov_write_string_metadata(s, pb_buf, "\251swr", "encoder"    , 0);
1638
            mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
1639
            mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
1640
            mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
1641
        } else {
1642
            /* iTunes meta data */
1643
            mov_write_meta_tag(pb_buf, mov, s);
1644
        }
1645

    
1646
        if (s->nb_chapters)
1647
            mov_write_chpl_tag(pb_buf, s);
1648

    
1649
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1650
        avio_wb32(pb, size+8);
1651
        ffio_wfourcc(pb, "udta");
1652
        avio_write(pb, buf, size);
1653
    }
1654
    av_free(buf);
1655

    
1656
    return 0;
1657
}
1658

    
1659
static void mov_write_psp_udta_tag(AVIOContext *pb,
1660
                                  const char *str, const char *lang, int type)
1661
{
1662
    int len = utf8len(str)+1;
1663
    if(len<=0)
1664
        return;
1665
    avio_wb16(pb, len*2+10);            /* size */
1666
    avio_wb32(pb, type);                /* type */
1667
    avio_wb16(pb, language_code(lang)); /* language */
1668
    avio_wb16(pb, 0x01);                /* ? */
1669
    ascii_to_wc(pb, str);
1670
}
1671

    
1672
static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
1673
{
1674
    AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
1675
    int64_t pos, pos2;
1676

    
1677
    if (title) {
1678
        pos = url_ftell(pb);
1679
        avio_wb32(pb, 0); /* size placeholder*/
1680
        ffio_wfourcc(pb, "uuid");
1681
        ffio_wfourcc(pb, "USMT");
1682
        avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
1683
        avio_wb32(pb, 0xbb88695c);
1684
        avio_wb32(pb, 0xfac9c740);
1685

    
1686
        pos2 = url_ftell(pb);
1687
        avio_wb32(pb, 0); /* size placeholder*/
1688
        ffio_wfourcc(pb, "MTDT");
1689
        avio_wb16(pb, 4);
1690

    
1691
        // ?
1692
        avio_wb16(pb, 0x0C);                 /* size */
1693
        avio_wb32(pb, 0x0B);                 /* type */
1694
        avio_wb16(pb, language_code("und")); /* language */
1695
        avio_wb16(pb, 0x0);                  /* ? */
1696
        avio_wb16(pb, 0x021C);               /* data */
1697

    
1698
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1699
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1700
//        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);
1701
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1702

    
1703
        updateSize(pb, pos2);
1704
        return updateSize(pb, pos);
1705
    }
1706

    
1707
    return 0;
1708
}
1709

    
1710
static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
1711
                              AVFormatContext *s)
1712
{
1713
    int i;
1714
    int64_t pos = url_ftell(pb);
1715
    avio_wb32(pb, 0); /* size placeholder*/
1716
    ffio_wfourcc(pb, "moov");
1717

    
1718
    for (i=0; i<mov->nb_streams; i++) {
1719
        if(mov->tracks[i].entry <= 0) continue;
1720

    
1721
        mov->tracks[i].time = mov->time;
1722
        mov->tracks[i].trackID = i+1;
1723
    }
1724

    
1725
    if (mov->chapter_track)
1726
        for (i=0; i<s->nb_streams; i++) {
1727
            mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
1728
            mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].trackID;
1729
        }
1730
    for (i = 0; i < mov->nb_streams; i++) {
1731
        if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
1732
            mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
1733
            mov->tracks[i].tref_id =
1734
                mov->tracks[mov->tracks[i].src_track].trackID;
1735
        }
1736
    }
1737

    
1738
    mov_write_mvhd_tag(pb, mov);
1739
    //mov_write_iods_tag(pb, mov);
1740
    for (i=0; i<mov->nb_streams; i++) {
1741
        if(mov->tracks[i].entry > 0) {
1742
            mov_write_trak_tag(pb, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
1743
        }
1744
    }
1745

    
1746
    if (mov->mode == MODE_PSP)
1747
        mov_write_uuidusmt_tag(pb, s);
1748
    else
1749
        mov_write_udta_tag(pb, mov, s);
1750

    
1751
    return updateSize(pb, pos);
1752
}
1753

    
1754
static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
1755
{
1756
    avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
1757
    ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
1758

    
1759
    mov->mdat_pos = url_ftell(pb);
1760
    avio_wb32(pb, 0); /* size placeholder*/
1761
    ffio_wfourcc(pb, "mdat");
1762
    return 0;
1763
}
1764

    
1765
/* TODO: This needs to be more general */
1766
static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
1767
{
1768
    MOVMuxContext *mov = s->priv_data;
1769
    int64_t pos = url_ftell(pb);
1770
    int has_h264 = 0, has_video = 0;
1771
    int minor = 0x200;
1772
    int i;
1773

    
1774
    for (i = 0; i < s->nb_streams; i++) {
1775
        AVStream *st = s->streams[i];
1776
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1777
            has_video = 1;
1778
        if (st->codec->codec_id == CODEC_ID_H264)
1779
            has_h264 = 1;
1780
    }
1781

    
1782
    avio_wb32(pb, 0); /* size */
1783
    ffio_wfourcc(pb, "ftyp");
1784

    
1785
    if (mov->mode == MODE_3GP) {
1786
        ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
1787
        minor =     has_h264 ?   0x100 :   0x200;
1788
    } else if (mov->mode & MODE_3G2) {
1789
        ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
1790
        minor =     has_h264 ? 0x20000 : 0x10000;
1791
    }else if (mov->mode == MODE_PSP)
1792
        ffio_wfourcc(pb, "MSNV");
1793
    else if (mov->mode == MODE_MP4)
1794
        ffio_wfourcc(pb, "isom");
1795
    else if (mov->mode == MODE_IPOD)
1796
        ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
1797
    else
1798
        ffio_wfourcc(pb, "qt  ");
1799

    
1800
    avio_wb32(pb, minor);
1801

    
1802
    if(mov->mode == MODE_MOV)
1803
        ffio_wfourcc(pb, "qt  ");
1804
    else{
1805
        ffio_wfourcc(pb, "isom");
1806
        ffio_wfourcc(pb, "iso2");
1807
        if(has_h264)
1808
            ffio_wfourcc(pb, "avc1");
1809
    }
1810

    
1811
    if (mov->mode == MODE_3GP)
1812
        ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
1813
    else if (mov->mode & MODE_3G2)
1814
        ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
1815
    else if (mov->mode == MODE_PSP)
1816
        ffio_wfourcc(pb, "MSNV");
1817
    else if (mov->mode == MODE_MP4)
1818
        ffio_wfourcc(pb, "mp41");
1819
    return updateSize(pb, pos);
1820
}
1821

    
1822
static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
1823
{
1824
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1825
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1826
    int AudioRate = AudioCodec->sample_rate;
1827
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1828
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1829
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1830

    
1831
    avio_wb32(pb, 0x94); /* size */
1832
    ffio_wfourcc(pb, "uuid");
1833
    ffio_wfourcc(pb, "PROF");
1834

    
1835
    avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
1836
    avio_wb32(pb, 0xbb88695c);
1837
    avio_wb32(pb, 0xfac9c740);
1838

    
1839
    avio_wb32(pb, 0x0);  /* ? */
1840
    avio_wb32(pb, 0x3);  /* 3 sections ? */
1841

    
1842
    avio_wb32(pb, 0x14); /* size */
1843
    ffio_wfourcc(pb, "FPRF");
1844
    avio_wb32(pb, 0x0);  /* ? */
1845
    avio_wb32(pb, 0x0);  /* ? */
1846
    avio_wb32(pb, 0x0);  /* ? */
1847

    
1848
    avio_wb32(pb, 0x2c);  /* size */
1849
    ffio_wfourcc(pb, "APRF");/* audio */
1850
    avio_wb32(pb, 0x0);
1851
    avio_wb32(pb, 0x2);   /* TrackID */
1852
    ffio_wfourcc(pb, "mp4a");
1853
    avio_wb32(pb, 0x20f);
1854
    avio_wb32(pb, 0x0);
1855
    avio_wb32(pb, audio_kbitrate);
1856
    avio_wb32(pb, audio_kbitrate);
1857
    avio_wb32(pb, AudioRate);
1858
    avio_wb32(pb, AudioCodec->channels);
1859

    
1860
    avio_wb32(pb, 0x34);  /* size */
1861
    ffio_wfourcc(pb, "VPRF");   /* video */
1862
    avio_wb32(pb, 0x0);
1863
    avio_wb32(pb, 0x1);    /* TrackID */
1864
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1865
        ffio_wfourcc(pb, "avc1");
1866
        avio_wb16(pb, 0x014D);
1867
        avio_wb16(pb, 0x0015);
1868
    } else {
1869
        ffio_wfourcc(pb, "mp4v");
1870
        avio_wb16(pb, 0x0000);
1871
        avio_wb16(pb, 0x0103);
1872
    }
1873
    avio_wb32(pb, 0x0);
1874
    avio_wb32(pb, video_kbitrate);
1875
    avio_wb32(pb, video_kbitrate);
1876
    avio_wb32(pb, FrameRate);
1877
    avio_wb32(pb, FrameRate);
1878
    avio_wb16(pb, VideoCodec->width);
1879
    avio_wb16(pb, VideoCodec->height);
1880
    avio_wb32(pb, 0x010001); /* ? */
1881
}
1882

    
1883
static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
1884
{
1885
    uint32_t c = -1;
1886
    int i, closed_gop = 0;
1887

    
1888
    for (i = 0; i < pkt->size - 4; i++) {
1889
        c = (c<<8) + pkt->data[i];
1890
        if (c == 0x1b8) { // gop
1891
            closed_gop = pkt->data[i+4]>>6 & 0x01;
1892
        } else if (c == 0x100) { // pic
1893
            int temp_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
1894
            if (!temp_ref || closed_gop) // I picture is not reordered
1895
                *flags = MOV_SYNC_SAMPLE;
1896
            else
1897
                *flags = MOV_PARTIAL_SYNC_SAMPLE;
1898
            break;
1899
        }
1900
    }
1901
    return 0;
1902
}
1903

    
1904
int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1905
{
1906
    MOVMuxContext *mov = s->priv_data;
1907
    AVIOContext *pb = s->pb;
1908
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1909
    AVCodecContext *enc = trk->enc;
1910
    unsigned int samplesInChunk = 0;
1911
    int size= pkt->size;
1912

    
1913
    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1914
    if (!size) return 0; /* Discard 0 sized packets */
1915

    
1916
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1917
        /* We must find out how many AMR blocks there are in one packet */
1918
        static uint16_t packed_size[16] =
1919
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1920
        int len = 0;
1921

    
1922
        while (len < size && samplesInChunk < 100) {
1923
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1924
            samplesInChunk++;
1925
        }
1926
        if(samplesInChunk > 1){
1927
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
1928
            return -1;
1929
        }
1930
    } else if (enc->codec_id == CODEC_ID_ADPCM_MS ||
1931
               enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
1932
        samplesInChunk = enc->frame_size;
1933
    } else if (trk->sampleSize)
1934
        samplesInChunk = size/trk->sampleSize;
1935
    else
1936
        samplesInChunk = 1;
1937

    
1938
    /* copy extradata if it exists */
1939
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1940
        trk->vosLen = enc->extradata_size;
1941
        trk->vosData = av_malloc(trk->vosLen);
1942
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1943
    }
1944

    
1945
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1946
        /* from x264 or from bytestream h264 */
1947
        /* nal reformating needed */
1948
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1949
    } else {
1950
        avio_write(pb, pkt->data, size);
1951
    }
1952

    
1953
    if ((enc->codec_id == CODEC_ID_DNXHD ||
1954
         enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
1955
        /* copy frame to create needed atoms */
1956
        trk->vosLen = size;
1957
        trk->vosData = av_malloc(size);
1958
        if (!trk->vosData)
1959
            return AVERROR(ENOMEM);
1960
        memcpy(trk->vosData, pkt->data, size);
1961
    }
1962

    
1963
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1964
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1965
        if (!trk->cluster)
1966
            return -1;
1967
    }
1968

    
1969
    trk->cluster[trk->entry].pos = url_ftell(pb) - size;
1970
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1971
    trk->cluster[trk->entry].size = size;
1972
    trk->cluster[trk->entry].entries = samplesInChunk;
1973
    trk->cluster[trk->entry].dts = pkt->dts;
1974
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1975

    
1976
    if (pkt->pts == AV_NOPTS_VALUE) {
1977
        av_log(s, AV_LOG_WARNING, "pts has no value\n");
1978
        pkt->pts = pkt->dts;
1979
    }
1980
    if (pkt->dts != pkt->pts)
1981
        trk->flags |= MOV_TRACK_CTTS;
1982
    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1983
    trk->cluster[trk->entry].flags = 0;
1984
    if (pkt->flags & AV_PKT_FLAG_KEY) {
1985
        if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO &&
1986
            trk->entry > 0) { // force sync sample for the first key frame
1987
            mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
1988
            if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
1989
                trk->flags |= MOV_TRACK_STPS;
1990
        } else {
1991
            trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
1992
        }
1993
        if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
1994
            trk->hasKeyframes++;
1995
    }
1996
    trk->entry++;
1997
    trk->sampleCount += samplesInChunk;
1998
    mov->mdat_size += size;
1999

    
2000
    put_flush_packet(pb);
2001

    
2002
    if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
2003
        ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry);
2004
    return 0;
2005
}
2006

    
2007
// QuickTime chapters involve an additional text track with the chapter names
2008
// as samples, and a tref pointing from the other tracks to the chapter one.
2009
static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
2010
{
2011
    MOVMuxContext *mov = s->priv_data;
2012
    MOVTrack *track = &mov->tracks[tracknum];
2013
    AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
2014
    int i, len;
2015

    
2016
    track->mode = mov->mode;
2017
    track->tag = MKTAG('t','e','x','t');
2018
    track->timescale = MOV_TIMESCALE;
2019
    track->enc = avcodec_alloc_context();
2020
    track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
2021

    
2022
    for (i = 0; i < s->nb_chapters; i++) {
2023
        AVChapter *c = s->chapters[i];
2024
        AVMetadataTag *t;
2025

    
2026
        int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
2027
        pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
2028
        pkt.duration = end - pkt.dts;
2029

    
2030
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
2031
            len = strlen(t->value);
2032
            pkt.size = len+2;
2033
            pkt.data = av_malloc(pkt.size);
2034
            AV_WB16(pkt.data, len);
2035
            memcpy(pkt.data+2, t->value, len);
2036
            ff_mov_write_packet(s, &pkt);
2037
            av_freep(&pkt.data);
2038
        }
2039
    }
2040
}
2041

    
2042
static int mov_write_header(AVFormatContext *s)
2043
{
2044
    AVIOContext *pb = s->pb;
2045
    MOVMuxContext *mov = s->priv_data;
2046
    int i, hint_track = 0;
2047

    
2048
    if (url_is_streamed(s->pb)) {
2049
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
2050
        return -1;
2051
    }
2052

    
2053
    /* Default mode == MP4 */
2054
    mov->mode = MODE_MP4;
2055

    
2056
    if (s->oformat != NULL) {
2057
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
2058
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
2059
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
2060
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
2061
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
2062

    
2063
        mov_write_ftyp_tag(pb,s);
2064
        if (mov->mode == MODE_PSP) {
2065
            if (s->nb_streams != 2) {
2066
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
2067
                return -1;
2068
            }
2069
            mov_write_uuidprof_tag(pb,s);
2070
        }
2071
    }
2072

    
2073
    mov->nb_streams = s->nb_streams;
2074
    if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
2075
        mov->chapter_track = mov->nb_streams++;
2076

    
2077
    if (s->flags & AVFMT_FLAG_RTP_HINT) {
2078
        /* Add hint tracks for each audio and video stream */
2079
        hint_track = mov->nb_streams;
2080
        for (i = 0; i < s->nb_streams; i++) {
2081
            AVStream *st = s->streams[i];
2082
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2083
                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2084
                mov->nb_streams++;
2085
            }
2086
        }
2087
    }
2088

    
2089
    mov->tracks = av_mallocz(mov->nb_streams*sizeof(*mov->tracks));
2090
    if (!mov->tracks)
2091
        return AVERROR(ENOMEM);
2092

    
2093
    for(i=0; i<s->nb_streams; i++){
2094
        AVStream *st= s->streams[i];
2095
        MOVTrack *track= &mov->tracks[i];
2096
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
2097

    
2098
        track->enc = st->codec;
2099
        track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
2100
        if (track->language < 0)
2101
            track->language = 0;
2102
        track->mode = mov->mode;
2103
        track->tag = mov_find_codec_tag(s, track);
2104
        if (!track->tag) {
2105
            av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
2106
                   "codec not currently supported in container\n", i);
2107
            goto error;
2108
        }
2109
        /* If hinting of this track is enabled by a later hint track,
2110
         * this is updated. */
2111
        track->hint_track = -1;
2112
        if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2113
            if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
2114
                track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
2115
                track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
2116
                if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
2117
                    av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
2118
                    goto error;
2119
                }
2120
                track->height = track->tag>>24 == 'n' ? 486 : 576;
2121
            }
2122
            track->timescale = st->codec->time_base.den;
2123
            if (track->mode == MODE_MOV && track->timescale > 100000)
2124
                av_log(s, AV_LOG_WARNING,
2125
                       "WARNING codec timebase is very high. If duration is too long,\n"
2126
                       "file may not be playable by quicktime. Specify a shorter timebase\n"
2127
                       "or choose different container.\n");
2128
        }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO){
2129
            track->timescale = st->codec->sample_rate;
2130
            if(!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
2131
                av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
2132
                goto error;
2133
            }else if(st->codec->codec_id == CODEC_ID_ADPCM_MS ||
2134
                     st->codec->codec_id == CODEC_ID_ADPCM_IMA_WAV){
2135
                if (!st->codec->block_align) {
2136
                    av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
2137
                    goto error;
2138
                }
2139
                track->sampleSize = st->codec->block_align;
2140
            }else if(st->codec->frame_size > 1){ /* assume compressed audio */
2141
                track->audio_vbr = 1;
2142
            }else{
2143
                st->codec->frame_size = 1;
2144
                track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
2145
            }
2146
            if (track->mode != MODE_MOV) {
2147
                if (track->timescale > UINT16_MAX) {
2148
                    av_log(s, AV_LOG_ERROR, "track %d: output format does not support "
2149
                           "sample rate %dhz\n", i, track->timescale);
2150
                    goto error;
2151
                }
2152
                if (track->enc->codec_id == CODEC_ID_MP3 && track->timescale < 16000) {
2153
                    av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
2154
                           i, track->enc->sample_rate);
2155
                    goto error;
2156
                }
2157
            }
2158
        }else if(st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE){
2159
            track->timescale = st->codec->time_base.den;
2160
        }
2161
        if (!track->height)
2162
            track->height = st->codec->height;
2163

    
2164
        av_set_pts_info(st, 64, 1, track->timescale);
2165
    }
2166

    
2167
    mov_write_mdat_tag(pb, mov);
2168
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
2169

    
2170
    if (mov->chapter_track)
2171
        mov_create_chapter_track(s, mov->chapter_track);
2172

    
2173
    if (s->flags & AVFMT_FLAG_RTP_HINT) {
2174
        /* Initialize the hint tracks for each audio and video stream */
2175
        for (i = 0; i < s->nb_streams; i++) {
2176
            AVStream *st = s->streams[i];
2177
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2178
                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2179
                ff_mov_init_hinting(s, hint_track, i);
2180
                hint_track++;
2181
            }
2182
        }
2183
    }
2184

    
2185
    put_flush_packet(pb);
2186

    
2187
    return 0;
2188
 error:
2189
    av_freep(&mov->tracks);
2190
    return -1;
2191
}
2192

    
2193
static int mov_write_trailer(AVFormatContext *s)
2194
{
2195
    MOVMuxContext *mov = s->priv_data;
2196
    AVIOContext *pb = s->pb;
2197
    int res = 0;
2198
    int i;
2199

    
2200
    int64_t moov_pos = url_ftell(pb);
2201

    
2202
    /* Write size of mdat tag */
2203
    if (mov->mdat_size+8 <= UINT32_MAX) {
2204
        url_fseek(pb, mov->mdat_pos, SEEK_SET);
2205
        avio_wb32(pb, mov->mdat_size+8);
2206
    } else {
2207
        /* overwrite 'wide' placeholder atom */
2208
        url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
2209
        avio_wb32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
2210
        ffio_wfourcc(pb, "mdat");
2211
        avio_wb64(pb, mov->mdat_size+16);
2212
    }
2213
    url_fseek(pb, moov_pos, SEEK_SET);
2214

    
2215
    mov_write_moov_tag(pb, mov, s);
2216

    
2217
    if (mov->chapter_track)
2218
        av_freep(&mov->tracks[mov->chapter_track].enc);
2219

    
2220
    for (i=0; i<mov->nb_streams; i++) {
2221
        if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
2222
            ff_mov_close_hinting(&mov->tracks[i]);
2223
        av_freep(&mov->tracks[i].cluster);
2224

    
2225
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2226

    
2227
    }
2228

    
2229
    put_flush_packet(pb);
2230

    
2231
    av_freep(&mov->tracks);
2232

    
2233
    return res;
2234
}
2235

    
2236
#if CONFIG_MOV_MUXER
2237
AVOutputFormat ff_mov_muxer = {
2238
    "mov",
2239
    NULL_IF_CONFIG_SMALL("MOV format"),
2240
    NULL,
2241
    "mov",
2242
    sizeof(MOVMuxContext),
2243
    CODEC_ID_AAC,
2244
    CODEC_ID_MPEG4,
2245
    mov_write_header,
2246
    ff_mov_write_packet,
2247
    mov_write_trailer,
2248
    .flags = AVFMT_GLOBALHEADER,
2249
    .codec_tag = (const AVCodecTag* const []){codec_movvideo_tags, codec_movaudio_tags, 0},
2250
};
2251
#endif
2252
#if CONFIG_TGP_MUXER
2253
AVOutputFormat ff_tgp_muxer = {
2254
    "3gp",
2255
    NULL_IF_CONFIG_SMALL("3GP format"),
2256
    NULL,
2257
    "3gp",
2258
    sizeof(MOVMuxContext),
2259
    CODEC_ID_AMR_NB,
2260
    CODEC_ID_H263,
2261
    mov_write_header,
2262
    ff_mov_write_packet,
2263
    mov_write_trailer,
2264
    .flags = AVFMT_GLOBALHEADER,
2265
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2266
};
2267
#endif
2268
#if CONFIG_MP4_MUXER
2269
AVOutputFormat ff_mp4_muxer = {
2270
    "mp4",
2271
    NULL_IF_CONFIG_SMALL("MP4 format"),
2272
    "application/mp4",
2273
    "mp4",
2274
    sizeof(MOVMuxContext),
2275
    CODEC_ID_AAC,
2276
    CODEC_ID_MPEG4,
2277
    mov_write_header,
2278
    ff_mov_write_packet,
2279
    mov_write_trailer,
2280
    .flags = AVFMT_GLOBALHEADER,
2281
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2282
};
2283
#endif
2284
#if CONFIG_PSP_MUXER
2285
AVOutputFormat ff_psp_muxer = {
2286
    "psp",
2287
    NULL_IF_CONFIG_SMALL("PSP MP4 format"),
2288
    NULL,
2289
    "mp4,psp",
2290
    sizeof(MOVMuxContext),
2291
    CODEC_ID_AAC,
2292
    CODEC_ID_MPEG4,
2293
    mov_write_header,
2294
    ff_mov_write_packet,
2295
    mov_write_trailer,
2296
    .flags = AVFMT_GLOBALHEADER,
2297
    .codec_tag = (const AVCodecTag* const []){ff_mp4_obj_type, 0},
2298
};
2299
#endif
2300
#if CONFIG_TG2_MUXER
2301
AVOutputFormat ff_tg2_muxer = {
2302
    "3g2",
2303
    NULL_IF_CONFIG_SMALL("3GP2 format"),
2304
    NULL,
2305
    "3g2",
2306
    sizeof(MOVMuxContext),
2307
    CODEC_ID_AMR_NB,
2308
    CODEC_ID_H263,
2309
    mov_write_header,
2310
    ff_mov_write_packet,
2311
    mov_write_trailer,
2312
    .flags = AVFMT_GLOBALHEADER,
2313
    .codec_tag = (const AVCodecTag* const []){codec_3gp_tags, 0},
2314
};
2315
#endif
2316
#if CONFIG_IPOD_MUXER
2317
AVOutputFormat ff_ipod_muxer = {
2318
    "ipod",
2319
    NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
2320
    "application/mp4",
2321
    "m4v,m4a",
2322
    sizeof(MOVMuxContext),
2323
    CODEC_ID_AAC,
2324
    CODEC_ID_H264,
2325
    mov_write_header,
2326
    ff_mov_write_packet,
2327
    mov_write_trailer,
2328
    .flags = AVFMT_GLOBALHEADER,
2329
    .codec_tag = (const AVCodecTag* const []){codec_ipod_tags, 0},
2330
};
2331
#endif