Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ efdad9fb

History | View | Annotate | Download (78.7 KB)

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

    
24
#include "movenc.h"
25
#include "avformat.h"
26
#include "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 = avio_tell(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 = avio_tell(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 = avio_tell(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 = avio_tell(pb);
118
    avio_wb32(pb, 0); /* size */
119
    ffio_wfourcc(pb, "stsc");
120
    avio_wb32(pb, 0); // version & flags
121
    entryPos = avio_tell(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 = avio_tell(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 = avio_tell(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 = avio_tell(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 = avio_tell(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 = avio_tell(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 = avio_tell(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 = avio_tell(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 = avio_tell(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 = avio_tell(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, 2); /* yuv range: full 1 / normal 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->width == 720) /* SD */
628
        if (track->enc->height == 480) /* NTSC */
629
            if  (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
630
            else                                         tag = MKTAG('d','v','c',' ');
631
        else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
632
        else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
633
        else                                             tag = MKTAG('d','v','p','p');
634
    else if (track->enc->height == 720) /* HD 720 line */
635
        if  (track->enc->time_base.den == 50)            tag = MKTAG('d','v','h','q');
636
        else                                             tag = MKTAG('d','v','h','p');
637
    else if (track->enc->height == 1080) /* HD 1080 line */
638
        if  (track->enc->time_base.den == 25)            tag = MKTAG('d','v','h','5');
639
        else                                             tag = MKTAG('d','v','h','6');
640
    else {
641
        av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
642
        return 0;
643
    }
644

    
645
    return tag;
646
}
647

    
648
static const struct {
649
    enum PixelFormat pix_fmt;
650
    uint32_t tag;
651
    unsigned bps;
652
} mov_pix_fmt_tags[] = {
653
    { PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
654
    { PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
655
    { PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
656
    { PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
657
    { PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
658
    { PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
659
    { PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
660
    { PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
661
    { PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
662
    { PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
663
    { PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
664
    { PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
665
    { PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
666
    { PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
667
};
668

    
669
static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
670
{
671
    int tag = track->enc->codec_tag;
672
    int i;
673

    
674
    for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
675
        if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
676
            tag = mov_pix_fmt_tags[i].tag;
677
            track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
678
            break;
679
        }
680
    }
681

    
682
    return tag;
683
}
684

    
685
static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
686
{
687
    int tag = track->enc->codec_tag;
688

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

    
720
    return tag;
721
}
722

    
723
static const AVCodecTag codec_3gp_tags[] = {
724
    { CODEC_ID_H263,   MKTAG('s','2','6','3') },
725
    { CODEC_ID_H264,   MKTAG('a','v','c','1') },
726
    { CODEC_ID_MPEG4,  MKTAG('m','p','4','v') },
727
    { CODEC_ID_AAC,    MKTAG('m','p','4','a') },
728
    { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
729
    { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
730
    { CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
731
    { CODEC_ID_NONE, 0 },
732
};
733

    
734
static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
735
{
736
    int tag = track->enc->codec_tag;
737

    
738
    if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
739
        tag = mp4_get_codec_tag(s, track);
740
    else if (track->mode == MODE_IPOD)
741
        tag = ipod_get_codec_tag(s, track);
742
    else if (track->mode & MODE_3GP)
743
        tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
744
    else
745
        tag = mov_get_codec_tag(s, track);
746

    
747
    return tag;
748
}
749

    
750
/** Write uuid atom.
751
 * Needed to make file play in iPods running newest firmware
752
 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
753
 */
754
static int mov_write_uuid_tag_ipod(AVIOContext *pb)
755
{
756
    avio_wb32(pb, 28);
757
    ffio_wfourcc(pb, "uuid");
758
    avio_wb32(pb, 0x6b6840f2);
759
    avio_wb32(pb, 0x5f244fc5);
760
    avio_wb32(pb, 0xba39a51b);
761
    avio_wb32(pb, 0xcf0323f3);
762
    avio_wb32(pb, 0x0);
763
    return 28;
764
}
765

    
766
static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
767
{
768
    int64_t pos = avio_tell(pb);
769
    avio_wb32(pb, 0);    /* size */
770
    avio_wl32(pb, track->tag); // store it byteswapped
771
    avio_wb32(pb, 0);    /* Reserved */
772
    avio_wb16(pb, 0);    /* Reserved */
773
    avio_wb16(pb, 1);    /* Data-reference index */
774

    
775
    if (track->enc->extradata_size)
776
        avio_write(pb, track->enc->extradata, track->enc->extradata_size);
777

    
778
    return updateSize(pb, pos);
779
}
780

    
781
static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
782
{
783
    AVRational sar;
784
    av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
785
              track->enc->sample_aspect_ratio.den, INT_MAX);
786

    
787
    avio_wb32(pb, 16);
788
    ffio_wfourcc(pb, "pasp");
789
    avio_wb32(pb, sar.num);
790
    avio_wb32(pb, sar.den);
791
    return 16;
792
}
793

    
794
static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
795
{
796
    int64_t pos = avio_tell(pb);
797
    char compressor_name[32];
798

    
799
    avio_wb32(pb, 0); /* size */
800
    avio_wl32(pb, track->tag); // store it byteswapped
801
    avio_wb32(pb, 0); /* Reserved */
802
    avio_wb16(pb, 0); /* Reserved */
803
    avio_wb16(pb, 1); /* Data-reference index */
804

    
805
    avio_wb16(pb, 0); /* Codec stream version */
806
    avio_wb16(pb, 0); /* Codec stream revision (=0) */
807
    if (track->mode == MODE_MOV) {
808
        ffio_wfourcc(pb, "FFMP"); /* Vendor */
809
        if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
810
            avio_wb32(pb, 0); /* Temporal Quality */
811
            avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
812
        } else {
813
            avio_wb32(pb, 0x200); /* Temporal Quality = normal */
814
            avio_wb32(pb, 0x200); /* Spatial Quality = normal */
815
        }
816
    } else {
817
        avio_wb32(pb, 0); /* Reserved */
818
        avio_wb32(pb, 0); /* Reserved */
819
        avio_wb32(pb, 0); /* Reserved */
820
    }
821
    avio_wb16(pb, track->enc->width); /* Video width */
822
    avio_wb16(pb, track->height); /* Video height */
823
    avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
824
    avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
825
    avio_wb32(pb, 0); /* Data size (= 0) */
826
    avio_wb16(pb, 1); /* Frame count (= 1) */
827

    
828
    memset(compressor_name,0,32);
829
    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
830
    if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
831
        strncpy(compressor_name,track->enc->codec->name,31);
832
    avio_w8(pb, strlen(compressor_name));
833
    avio_write(pb, compressor_name, 31);
834

    
835
    if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
836
        avio_wb16(pb, track->enc->bits_per_coded_sample);
837
    else
838
        avio_wb16(pb, 0x18); /* Reserved */
839
    avio_wb16(pb, 0xffff); /* Reserved */
840
    if(track->tag == MKTAG('m','p','4','v'))
841
        mov_write_esds_tag(pb, track);
842
    else if(track->enc->codec_id == CODEC_ID_H263)
843
        mov_write_d263_tag(pb);
844
    else if(track->enc->codec_id == CODEC_ID_SVQ3)
845
        mov_write_svq3_tag(pb);
846
    else if(track->enc->codec_id == CODEC_ID_DNXHD)
847
        mov_write_avid_tag(pb, track);
848
    else if(track->enc->codec_id == CODEC_ID_H264) {
849
        mov_write_avcc_tag(pb, track);
850
        if(track->mode == MODE_IPOD)
851
            mov_write_uuid_tag_ipod(pb);
852
    } else if(track->vosLen > 0)
853
        mov_write_glbl_tag(pb, track);
854

    
855
    if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
856
        track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
857
        mov_write_pasp_tag(pb, track);
858
    }
859

    
860
    return updateSize(pb, pos);
861
}
862

    
863
static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
864
{
865
    int64_t pos = avio_tell(pb);
866
    avio_wb32(pb, 0); /* size */
867
    ffio_wfourcc(pb, "rtp ");
868
    avio_wb32(pb, 0); /* Reserved */
869
    avio_wb16(pb, 0); /* Reserved */
870
    avio_wb16(pb, 1); /* Data-reference index */
871

    
872
    avio_wb16(pb, 1); /* Hint track version */
873
    avio_wb16(pb, 1); /* Highest compatible version */
874
    avio_wb32(pb, track->max_packet_size); /* Max packet size */
875

    
876
    avio_wb32(pb, 12); /* size */
877
    ffio_wfourcc(pb, "tims");
878
    avio_wb32(pb, track->timescale);
879

    
880
    return updateSize(pb, pos);
881
}
882

    
883
static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
884
{
885
    int64_t pos = avio_tell(pb);
886
    avio_wb32(pb, 0); /* size */
887
    ffio_wfourcc(pb, "stsd");
888
    avio_wb32(pb, 0); /* version & flags */
889
    avio_wb32(pb, 1); /* entry count */
890
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
891
        mov_write_video_tag(pb, track);
892
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
893
        mov_write_audio_tag(pb, track);
894
    else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
895
        mov_write_subtitle_tag(pb, track);
896
    else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
897
        mov_write_rtp_tag(pb, track);
898
    return updateSize(pb, pos);
899
}
900

    
901
static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
902
{
903
    MOVStts *ctts_entries;
904
    uint32_t entries = 0;
905
    uint32_t atom_size;
906
    int i;
907

    
908
    ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
909
    ctts_entries[0].count = 1;
910
    ctts_entries[0].duration = track->cluster[0].cts;
911
    for (i=1; i<track->entry; i++) {
912
        if (track->cluster[i].cts == ctts_entries[entries].duration) {
913
            ctts_entries[entries].count++; /* compress */
914
        } else {
915
            entries++;
916
            ctts_entries[entries].duration = track->cluster[i].cts;
917
            ctts_entries[entries].count = 1;
918
        }
919
    }
920
    entries++; /* last one */
921
    atom_size = 16 + (entries * 8);
922
    avio_wb32(pb, atom_size); /* size */
923
    ffio_wfourcc(pb, "ctts");
924
    avio_wb32(pb, 0); /* version & flags */
925
    avio_wb32(pb, entries); /* entry count */
926
    for (i=0; i<entries; i++) {
927
        avio_wb32(pb, ctts_entries[i].count);
928
        avio_wb32(pb, ctts_entries[i].duration);
929
    }
930
    av_free(ctts_entries);
931
    return atom_size;
932
}
933

    
934
/* Time to sample atom */
935
static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
936
{
937
    MOVStts *stts_entries;
938
    uint32_t entries = -1;
939
    uint32_t atom_size;
940
    int i;
941

    
942
    if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
943
        stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
944
        stts_entries[0].count = track->sampleCount;
945
        stts_entries[0].duration = 1;
946
        entries = 1;
947
    } else {
948
        stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
949
        for (i=0; i<track->entry; i++) {
950
            int64_t duration = i + 1 == track->entry ?
951
                track->trackDuration - track->cluster[i].dts + track->cluster[0].dts : /* readjusting */
952
                track->cluster[i+1].dts - track->cluster[i].dts;
953
            if (i && duration == stts_entries[entries].duration) {
954
                stts_entries[entries].count++; /* compress */
955
            } else {
956
                entries++;
957
                stts_entries[entries].duration = duration;
958
                stts_entries[entries].count = 1;
959
            }
960
        }
961
        entries++; /* last one */
962
    }
963
    atom_size = 16 + (entries * 8);
964
    avio_wb32(pb, atom_size); /* size */
965
    ffio_wfourcc(pb, "stts");
966
    avio_wb32(pb, 0); /* version & flags */
967
    avio_wb32(pb, entries); /* entry count */
968
    for (i=0; i<entries; i++) {
969
        avio_wb32(pb, stts_entries[i].count);
970
        avio_wb32(pb, stts_entries[i].duration);
971
    }
972
    av_free(stts_entries);
973
    return atom_size;
974
}
975

    
976
static int mov_write_dref_tag(AVIOContext *pb)
977
{
978
    avio_wb32(pb, 28); /* size */
979
    ffio_wfourcc(pb, "dref");
980
    avio_wb32(pb, 0); /* version & flags */
981
    avio_wb32(pb, 1); /* entry count */
982

    
983
    avio_wb32(pb, 0xc); /* size */
984
    ffio_wfourcc(pb, "url ");
985
    avio_wb32(pb, 1); /* version & flags */
986

    
987
    return 28;
988
}
989

    
990
static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
991
{
992
    int64_t pos = avio_tell(pb);
993
    avio_wb32(pb, 0); /* size */
994
    ffio_wfourcc(pb, "stbl");
995
    mov_write_stsd_tag(pb, track);
996
    mov_write_stts_tag(pb, track);
997
    if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
998
         track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
999
        track->hasKeyframes && track->hasKeyframes < track->entry)
1000
        mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1001
    if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1002
        mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1003
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1004
        track->flags & MOV_TRACK_CTTS)
1005
        mov_write_ctts_tag(pb, track);
1006
    mov_write_stsc_tag(pb, track);
1007
    mov_write_stsz_tag(pb, track);
1008
    mov_write_stco_tag(pb, track);
1009
    return updateSize(pb, pos);
1010
}
1011

    
1012
static int mov_write_dinf_tag(AVIOContext *pb)
1013
{
1014
    int64_t pos = avio_tell(pb);
1015
    avio_wb32(pb, 0); /* size */
1016
    ffio_wfourcc(pb, "dinf");
1017
    mov_write_dref_tag(pb);
1018
    return updateSize(pb, pos);
1019
}
1020

    
1021
static int mov_write_nmhd_tag(AVIOContext *pb)
1022
{
1023
    avio_wb32(pb, 12);
1024
    ffio_wfourcc(pb, "nmhd");
1025
    avio_wb32(pb, 0);
1026
    return 12;
1027
}
1028

    
1029
static int mov_write_gmhd_tag(AVIOContext *pb)
1030
{
1031
    avio_wb32(pb, 0x20);   /* size */
1032
    ffio_wfourcc(pb, "gmhd");
1033
    avio_wb32(pb, 0x18);   /* gmin size */
1034
    ffio_wfourcc(pb, "gmin");/* generic media info */
1035
    avio_wb32(pb, 0);      /* version & flags */
1036
    avio_wb16(pb, 0x40);   /* graphics mode = */
1037
    avio_wb16(pb, 0x8000); /* opColor (r?) */
1038
    avio_wb16(pb, 0x8000); /* opColor (g?) */
1039
    avio_wb16(pb, 0x8000); /* opColor (b?) */
1040
    avio_wb16(pb, 0);      /* balance */
1041
    avio_wb16(pb, 0);      /* reserved */
1042
    return 0x20;
1043
}
1044

    
1045
static int mov_write_smhd_tag(AVIOContext *pb)
1046
{
1047
    avio_wb32(pb, 16); /* size */
1048
    ffio_wfourcc(pb, "smhd");
1049
    avio_wb32(pb, 0); /* version & flags */
1050
    avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1051
    avio_wb16(pb, 0); /* reserved */
1052
    return 16;
1053
}
1054

    
1055
static int mov_write_vmhd_tag(AVIOContext *pb)
1056
{
1057
    avio_wb32(pb, 0x14); /* size (always 0x14) */
1058
    ffio_wfourcc(pb, "vmhd");
1059
    avio_wb32(pb, 0x01); /* version & flags */
1060
    avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1061
    return 0x14;
1062
}
1063

    
1064
static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1065
{
1066
    const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1067
    int64_t pos = avio_tell(pb);
1068

    
1069
    if (!track) { /* no media --> data handler */
1070
        hdlr = "dhlr";
1071
        hdlr_type = "url ";
1072
        descr = "DataHandler";
1073
    } else {
1074
        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1075
        if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1076
            hdlr_type = "vide";
1077
            descr = "VideoHandler";
1078
        } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1079
            hdlr_type = "soun";
1080
            descr = "SoundHandler";
1081
        } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1082
            if (track->tag == MKTAG('t','x','3','g')) hdlr_type = "sbtl";
1083
            else                                      hdlr_type = "text";
1084
            descr = "SubtitleHandler";
1085
        } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1086
            hdlr_type = "hint";
1087
            descr = "HintHandler";
1088
        }
1089
    }
1090

    
1091
    avio_wb32(pb, 0); /* size */
1092
    ffio_wfourcc(pb, "hdlr");
1093
    avio_wb32(pb, 0); /* Version & flags */
1094
    avio_write(pb, hdlr, 4); /* handler */
1095
    ffio_wfourcc(pb, hdlr_type); /* handler type */
1096
    avio_wb32(pb ,0); /* reserved */
1097
    avio_wb32(pb ,0); /* reserved */
1098
    avio_wb32(pb ,0); /* reserved */
1099
    if (!track || track->mode == MODE_MOV)
1100
        avio_w8(pb, strlen(descr)); /* pascal string */
1101
    avio_write(pb, descr, strlen(descr)); /* handler description */
1102
    if (track && track->mode != MODE_MOV)
1103
        avio_w8(pb, 0); /* c string */
1104
    return updateSize(pb, pos);
1105
}
1106

    
1107
static int mov_write_hmhd_tag(AVIOContext *pb)
1108
{
1109
    /* This atom must be present, but leaving the values at zero
1110
     * seems harmless. */
1111
    avio_wb32(pb, 28); /* size */
1112
    ffio_wfourcc(pb, "hmhd");
1113
    avio_wb32(pb, 0); /* version, flags */
1114
    avio_wb16(pb, 0); /* maxPDUsize */
1115
    avio_wb16(pb, 0); /* avgPDUsize */
1116
    avio_wb32(pb, 0); /* maxbitrate */
1117
    avio_wb32(pb, 0); /* avgbitrate */
1118
    avio_wb32(pb, 0); /* reserved */
1119
    return 28;
1120
}
1121

    
1122
static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1123
{
1124
    int64_t pos = avio_tell(pb);
1125
    avio_wb32(pb, 0); /* size */
1126
    ffio_wfourcc(pb, "minf");
1127
    if(track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1128
        mov_write_vmhd_tag(pb);
1129
    else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1130
        mov_write_smhd_tag(pb);
1131
    else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1132
        if (track->tag == MKTAG('t','e','x','t')) mov_write_gmhd_tag(pb);
1133
        else                                      mov_write_nmhd_tag(pb);
1134
    } else if (track->tag == MKTAG('r','t','p',' ')) {
1135
        mov_write_hmhd_tag(pb);
1136
    }
1137
    if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1138
        mov_write_hdlr_tag(pb, NULL);
1139
    mov_write_dinf_tag(pb);
1140
    mov_write_stbl_tag(pb, track);
1141
    return updateSize(pb, pos);
1142
}
1143

    
1144
static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1145
{
1146
    int version = track->trackDuration < INT32_MAX ? 0 : 1;
1147

    
1148
    (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1149
    ffio_wfourcc(pb, "mdhd");
1150
    avio_w8(pb, version);
1151
    avio_wb24(pb, 0); /* flags */
1152
    if (version == 1) {
1153
        avio_wb64(pb, track->time);
1154
        avio_wb64(pb, track->time);
1155
    } else {
1156
        avio_wb32(pb, track->time); /* creation time */
1157
        avio_wb32(pb, track->time); /* modification time */
1158
    }
1159
    avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1160
    (version == 1) ? avio_wb64(pb, track->trackDuration) : avio_wb32(pb, track->trackDuration); /* duration */
1161
    avio_wb16(pb, track->language); /* language */
1162
    avio_wb16(pb, 0); /* reserved (quality) */
1163

    
1164
    if(version!=0 && track->mode == MODE_MOV){
1165
        av_log(NULL, AV_LOG_ERROR,
1166
            "FATAL error, file duration too long for timebase, this file will not be\n"
1167
            "playable with quicktime. Choose a different timebase or a different\n"
1168
            "container format\n");
1169
    }
1170

    
1171
    return 32;
1172
}
1173

    
1174
static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1175
{
1176
    int64_t pos = avio_tell(pb);
1177
    avio_wb32(pb, 0); /* size */
1178
    ffio_wfourcc(pb, "mdia");
1179
    mov_write_mdhd_tag(pb, track);
1180
    mov_write_hdlr_tag(pb, track);
1181
    mov_write_minf_tag(pb, track);
1182
    return updateSize(pb, pos);
1183
}
1184

    
1185
static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1186
{
1187
    int64_t duration = av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1188
                                      track->timescale, AV_ROUND_UP);
1189
    int version = duration < INT32_MAX ? 0 : 1;
1190

    
1191
    (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1192
    ffio_wfourcc(pb, "tkhd");
1193
    avio_w8(pb, version);
1194
    avio_wb24(pb, 0xf); /* flags (track enabled) */
1195
    if (version == 1) {
1196
        avio_wb64(pb, track->time);
1197
        avio_wb64(pb, track->time);
1198
    } else {
1199
        avio_wb32(pb, track->time); /* creation time */
1200
        avio_wb32(pb, track->time); /* modification time */
1201
    }
1202
    avio_wb32(pb, track->trackID); /* track-id */
1203
    avio_wb32(pb, 0); /* reserved */
1204
    (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1205

    
1206
    avio_wb32(pb, 0); /* reserved */
1207
    avio_wb32(pb, 0); /* reserved */
1208
    avio_wb32(pb, 0x0); /* reserved (Layer & Alternate group) */
1209
    /* Volume, only for audio */
1210
    if(track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1211
        avio_wb16(pb, 0x0100);
1212
    else
1213
        avio_wb16(pb, 0);
1214
    avio_wb16(pb, 0); /* reserved */
1215

    
1216
    /* Matrix structure */
1217
    avio_wb32(pb, 0x00010000); /* reserved */
1218
    avio_wb32(pb, 0x0); /* reserved */
1219
    avio_wb32(pb, 0x0); /* reserved */
1220
    avio_wb32(pb, 0x0); /* reserved */
1221
    avio_wb32(pb, 0x00010000); /* reserved */
1222
    avio_wb32(pb, 0x0); /* reserved */
1223
    avio_wb32(pb, 0x0); /* reserved */
1224
    avio_wb32(pb, 0x0); /* reserved */
1225
    avio_wb32(pb, 0x40000000); /* reserved */
1226

    
1227
    /* Track width and height, for visual only */
1228
    if(st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1229
              track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1230
        if(track->mode == MODE_MOV) {
1231
            avio_wb32(pb, track->enc->width << 16);
1232
            avio_wb32(pb, track->height << 16);
1233
        } else {
1234
            double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1235
            if(!sample_aspect_ratio || track->height != track->enc->height)
1236
                sample_aspect_ratio = 1;
1237
            avio_wb32(pb, sample_aspect_ratio * track->enc->width*0x10000);
1238
            avio_wb32(pb, track->height*0x10000);
1239
        }
1240
    }
1241
    else {
1242
        avio_wb32(pb, 0);
1243
        avio_wb32(pb, 0);
1244
    }
1245
    return 0x5c;
1246
}
1247

    
1248
static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1249
{
1250
    int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1251
                               track->enc->sample_aspect_ratio.den);
1252

    
1253
    int64_t pos = avio_tell(pb);
1254

    
1255
    avio_wb32(pb, 0); /* size */
1256
    ffio_wfourcc(pb, "tapt");
1257

    
1258
    avio_wb32(pb, 20);
1259
    ffio_wfourcc(pb, "clef");
1260
    avio_wb32(pb, 0);
1261
    avio_wb32(pb, width << 16);
1262
    avio_wb32(pb, track->enc->height << 16);
1263

    
1264
    avio_wb32(pb, 20);
1265
    ffio_wfourcc(pb, "enof");
1266
    avio_wb32(pb, 0);
1267
    avio_wb32(pb, track->enc->width << 16);
1268
    avio_wb32(pb, track->enc->height << 16);
1269

    
1270
    return updateSize(pb, pos);
1271
};
1272

    
1273
// This box seems important for the psp playback ... without it the movie seems to hang
1274
static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1275
{
1276
    avio_wb32(pb, 0x24); /* size  */
1277
    ffio_wfourcc(pb, "edts");
1278
    avio_wb32(pb, 0x1c); /* size  */
1279
    ffio_wfourcc(pb, "elst");
1280
    avio_wb32(pb, 0x0);
1281
    avio_wb32(pb, 0x1);
1282

    
1283
    /* duration   ... doesn't seem to effect psp */
1284
    avio_wb32(pb, av_rescale_rnd(track->trackDuration, MOV_TIMESCALE,
1285
                                track->timescale, AV_ROUND_UP));
1286

    
1287
    avio_wb32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
1288
    avio_wb32(pb, 0x00010000);
1289
    return 0x24;
1290
}
1291

    
1292
static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1293
{
1294
    avio_wb32(pb, 20);   // size
1295
    ffio_wfourcc(pb, "tref");
1296
    avio_wb32(pb, 12);   // size (subatom)
1297
    avio_wl32(pb, track->tref_tag);
1298
    avio_wb32(pb, track->tref_id);
1299
    return 20;
1300
}
1301

    
1302
// goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
1303
static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1304
{
1305
    avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1306
    ffio_wfourcc(pb, "uuid");
1307
    ffio_wfourcc(pb, "USMT");
1308
    avio_wb32(pb, 0x21d24fce);
1309
    avio_wb32(pb, 0xbb88695c);
1310
    avio_wb32(pb, 0xfac9c740);
1311
    avio_wb32(pb, 0x1c);     // another size here!
1312
    ffio_wfourcc(pb, "MTDT");
1313
    avio_wb32(pb, 0x00010012);
1314
    avio_wb32(pb, 0x0a);
1315
    avio_wb32(pb, 0x55c40000);
1316
    avio_wb32(pb, 0x1);
1317
    avio_wb32(pb, 0x0);
1318
    return 0x34;
1319
}
1320

    
1321
static int mov_write_udta_sdp(AVIOContext *pb, AVCodecContext *ctx, int index)
1322
{
1323
    char buf[1000] = "";
1324
    int len;
1325

    
1326
    ff_sdp_write_media(buf, sizeof(buf), ctx, NULL, NULL, 0, 0);
1327
    av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", index);
1328
    len = strlen(buf);
1329

    
1330
    avio_wb32(pb, len + 24);
1331
    ffio_wfourcc(pb, "udta");
1332
    avio_wb32(pb, len + 16);
1333
    ffio_wfourcc(pb, "hnti");
1334
    avio_wb32(pb, len + 8);
1335
    ffio_wfourcc(pb, "sdp ");
1336
    avio_write(pb, buf, len);
1337
    return len + 24;
1338
}
1339

    
1340
static int mov_write_trak_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1341
{
1342
    int64_t pos = avio_tell(pb);
1343
    avio_wb32(pb, 0); /* size */
1344
    ffio_wfourcc(pb, "trak");
1345
    mov_write_tkhd_tag(pb, track, st);
1346
    if (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS)
1347
        mov_write_edts_tag(pb, track);  // PSP Movies require edts box
1348
    if (track->tref_tag)
1349
        mov_write_tref_tag(pb, track);
1350
    mov_write_mdia_tag(pb, track);
1351
    if (track->mode == MODE_PSP)
1352
        mov_write_uuid_tag_psp(pb,track);  // PSP Movies require this uuid box
1353
    if (track->tag == MKTAG('r','t','p',' '))
1354
        mov_write_udta_sdp(pb, track->rtp_ctx->streams[0]->codec, track->trackID);
1355
    if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO && track->mode == MODE_MOV) {
1356
        double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1357
        if (0.0 != sample_aspect_ratio && 1.0 != sample_aspect_ratio)
1358
            mov_write_tapt_tag(pb, track);
1359
    };
1360
    return updateSize(pb, pos);
1361
}
1362

    
1363
#if 0
1364
/* TODO: Not sorted out, but not necessary either */
1365
static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1366
{
1367
    avio_wb32(pb, 0x15); /* size */
1368
    ffio_wfourcc(pb, "iods");
1369
    avio_wb32(pb, 0);    /* version & flags */
1370
    avio_wb16(pb, 0x1007);
1371
    avio_w8(pb, 0);
1372
    avio_wb16(pb, 0x4fff);
1373
    avio_wb16(pb, 0xfffe);
1374
    avio_wb16(pb, 0x01ff);
1375
    return 0x15;
1376
}
1377
#endif
1378

    
1379
static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
1380
{
1381
    int maxTrackID = 1, i;
1382
    int64_t maxTrackLenTemp, maxTrackLen = 0;
1383
    int version;
1384

    
1385
    for (i=0; i<mov->nb_streams; i++) {
1386
        if(mov->tracks[i].entry > 0) {
1387
            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration,
1388
                                             MOV_TIMESCALE,
1389
                                             mov->tracks[i].timescale,
1390
                                             AV_ROUND_UP);
1391
            if(maxTrackLen < maxTrackLenTemp)
1392
                maxTrackLen = maxTrackLenTemp;
1393
            if(maxTrackID < mov->tracks[i].trackID)
1394
                maxTrackID = mov->tracks[i].trackID;
1395
        }
1396
    }
1397

    
1398
    version = maxTrackLen < UINT32_MAX ? 0 : 1;
1399
    (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
1400
    ffio_wfourcc(pb, "mvhd");
1401
    avio_w8(pb, version);
1402
    avio_wb24(pb, 0); /* flags */
1403
    if (version == 1) {
1404
        avio_wb64(pb, mov->time);
1405
        avio_wb64(pb, mov->time);
1406
    } else {
1407
        avio_wb32(pb, mov->time); /* creation time */
1408
        avio_wb32(pb, mov->time); /* modification time */
1409
    }
1410
    avio_wb32(pb, MOV_TIMESCALE);
1411
    (version == 1) ? avio_wb64(pb, maxTrackLen) : avio_wb32(pb, maxTrackLen); /* duration of longest track */
1412

    
1413
    avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1414
    avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1415
    avio_wb16(pb, 0); /* reserved */
1416
    avio_wb32(pb, 0); /* reserved */
1417
    avio_wb32(pb, 0); /* reserved */
1418

    
1419
    /* Matrix structure */
1420
    avio_wb32(pb, 0x00010000); /* reserved */
1421
    avio_wb32(pb, 0x0); /* reserved */
1422
    avio_wb32(pb, 0x0); /* reserved */
1423
    avio_wb32(pb, 0x0); /* reserved */
1424
    avio_wb32(pb, 0x00010000); /* reserved */
1425
    avio_wb32(pb, 0x0); /* reserved */
1426
    avio_wb32(pb, 0x0); /* reserved */
1427
    avio_wb32(pb, 0x0); /* reserved */
1428
    avio_wb32(pb, 0x40000000); /* reserved */
1429

    
1430
    avio_wb32(pb, 0); /* reserved (preview time) */
1431
    avio_wb32(pb, 0); /* reserved (preview duration) */
1432
    avio_wb32(pb, 0); /* reserved (poster time) */
1433
    avio_wb32(pb, 0); /* reserved (selection time) */
1434
    avio_wb32(pb, 0); /* reserved (selection duration) */
1435
    avio_wb32(pb, 0); /* reserved (current time) */
1436
    avio_wb32(pb, maxTrackID+1); /* Next track id */
1437
    return 0x6c;
1438
}
1439

    
1440
static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
1441
                                     AVFormatContext *s)
1442
{
1443
    avio_wb32(pb, 33); /* size */
1444
    ffio_wfourcc(pb, "hdlr");
1445
    avio_wb32(pb, 0);
1446
    avio_wb32(pb, 0);
1447
    ffio_wfourcc(pb, "mdir");
1448
    ffio_wfourcc(pb, "appl");
1449
    avio_wb32(pb, 0);
1450
    avio_wb32(pb, 0);
1451
    avio_w8(pb, 0);
1452
    return 33;
1453
}
1454

    
1455
/* helper function to write a data tag with the specified string as data */
1456
static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
1457
{
1458
    if(long_style){
1459
        int size = 16 + strlen(data);
1460
        avio_wb32(pb, size); /* size */
1461
        ffio_wfourcc(pb, "data");
1462
        avio_wb32(pb, 1);
1463
        avio_wb32(pb, 0);
1464
        avio_write(pb, data, strlen(data));
1465
        return size;
1466
    }else{
1467
        if (!lang)
1468
            lang = ff_mov_iso639_to_lang("und", 1);
1469
        avio_wb16(pb, strlen(data)); /* string length */
1470
        avio_wb16(pb, lang);
1471
        avio_write(pb, data, strlen(data));
1472
        return strlen(data) + 4;
1473
    }
1474
}
1475

    
1476
static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style){
1477
    int size = 0;
1478
    if (value && value[0]) {
1479
        int64_t pos = avio_tell(pb);
1480
        avio_wb32(pb, 0); /* size */
1481
        ffio_wfourcc(pb, name);
1482
        mov_write_string_data_tag(pb, value, lang, long_style);
1483
        size= updateSize(pb, pos);
1484
    }
1485
    return size;
1486
}
1487

    
1488
static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
1489
                                     const char *name, const char *tag,
1490
                                     int long_style)
1491
{
1492
    int l, lang = 0, len, len2;
1493
    AVMetadataTag *t, *t2 = NULL;
1494
    char tag2[16];
1495

    
1496
    if (!(t = av_metadata_get(s->metadata, tag, NULL, 0)))
1497
        return 0;
1498

    
1499
    len = strlen(t->key);
1500
    snprintf(tag2, sizeof(tag2), "%s-", tag);
1501
    while ((t2 = av_metadata_get(s->metadata, tag2, t2, AV_METADATA_IGNORE_SUFFIX))) {
1502
        len2 = strlen(t2->key);
1503
        if (len2 == len+4 && !strcmp(t->value, t2->value)
1504
            && (l=ff_mov_iso639_to_lang(&t2->key[len2-3], 1)) >= 0) {
1505
            lang = l;
1506
            break;
1507
        }
1508
    }
1509
    return mov_write_string_tag(pb, name, t->value, lang, long_style);
1510
}
1511

    
1512
/* iTunes track number */
1513
static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
1514
                              AVFormatContext *s)
1515
{
1516
    AVMetadataTag *t = av_metadata_get(s->metadata, "track", NULL, 0);
1517
    int size = 0, track = t ? atoi(t->value) : 0;
1518
    if (track) {
1519
        avio_wb32(pb, 32); /* size */
1520
        ffio_wfourcc(pb, "trkn");
1521
            avio_wb32(pb, 24); /* size */
1522
            ffio_wfourcc(pb, "data");
1523
            avio_wb32(pb, 0);        // 8 bytes empty
1524
            avio_wb32(pb, 0);
1525
            avio_wb16(pb, 0);        // empty
1526
            avio_wb16(pb, track);    // track number
1527
            avio_wb16(pb, 0);        // total track number
1528
            avio_wb16(pb, 0);        // empty
1529
        size = 32;
1530
    }
1531
    return size;
1532
}
1533

    
1534
/* iTunes meta data list */
1535
static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
1536
                              AVFormatContext *s)
1537
{
1538
    int64_t pos = avio_tell(pb);
1539
    avio_wb32(pb, 0); /* size */
1540
    ffio_wfourcc(pb, "ilst");
1541
    mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
1542
    mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
1543
    mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
1544
    mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1545
    mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
1546
    mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
1547
    mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
1548
    mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
1549
    mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
1550
    mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
1551
    mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
1552
    mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
1553
    mov_write_string_metadata(s, pb, "desc",    "description",1);
1554
    mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
1555
    mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
1556
    mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
1557
    mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
1558
    mov_write_trkn_tag(pb, mov, s);
1559
    return updateSize(pb, pos);
1560
}
1561

    
1562
/* iTunes meta data tag */
1563
static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
1564
                              AVFormatContext *s)
1565
{
1566
    int size = 0;
1567
    int64_t pos = avio_tell(pb);
1568
    avio_wb32(pb, 0); /* size */
1569
    ffio_wfourcc(pb, "meta");
1570
    avio_wb32(pb, 0);
1571
    mov_write_itunes_hdlr_tag(pb, mov, s);
1572
    mov_write_ilst_tag(pb, mov, s);
1573
    size = updateSize(pb, pos);
1574
    return size;
1575
}
1576

    
1577
static int utf8len(const uint8_t *b)
1578
{
1579
    int len=0;
1580
    int val;
1581
    while(*b){
1582
        GET_UTF8(val, *b++, return -1;)
1583
        len++;
1584
    }
1585
    return len;
1586
}
1587

    
1588
static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
1589
{
1590
    int val;
1591
    while(*b){
1592
        GET_UTF8(val, *b++, return -1;)
1593
        avio_wb16(pb, val);
1594
    }
1595
    avio_wb16(pb, 0x00);
1596
    return 0;
1597
}
1598

    
1599
static uint16_t language_code(const char *str)
1600
{
1601
    return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1602
}
1603

    
1604
static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
1605
                                  const char *tag, const char *str)
1606
{
1607
    int64_t pos = avio_tell(pb);
1608
    AVMetadataTag *t = av_metadata_get(s->metadata, str, NULL, 0);
1609
    if (!t || !utf8len(t->value))
1610
        return 0;
1611
    avio_wb32(pb, 0);   /* size */
1612
    ffio_wfourcc(pb, tag); /* type */
1613
    avio_wb32(pb, 0);   /* version + flags */
1614
    if (!strcmp(tag, "yrrc"))
1615
        avio_wb16(pb, atoi(t->value));
1616
    else {
1617
        avio_wb16(pb, language_code("eng")); /* language */
1618
        avio_write(pb, t->value, strlen(t->value)+1); /* UTF8 string value */
1619
        if (!strcmp(tag, "albm") &&
1620
            (t = av_metadata_get(s->metadata, "track", NULL, 0)))
1621
            avio_w8(pb, atoi(t->value));
1622
    }
1623
    return updateSize(pb, pos);
1624
}
1625

    
1626
static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
1627
{
1628
    int64_t pos = avio_tell(pb);
1629
    int i, nb_chapters = FFMIN(s->nb_chapters, 255);
1630

    
1631
    avio_wb32(pb, 0);            // size
1632
    ffio_wfourcc(pb, "chpl");
1633
    avio_wb32(pb, 0x01000000);   // version + flags
1634
    avio_wb32(pb, 0);            // unknown
1635
    avio_w8(pb, nb_chapters);
1636

    
1637
    for (i = 0; i < nb_chapters; i++) {
1638
        AVChapter *c = s->chapters[i];
1639
        AVMetadataTag *t;
1640
        avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
1641

    
1642
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
1643
            int len = FFMIN(strlen(t->value), 255);
1644
            avio_w8(pb, len);
1645
            avio_write(pb, t->value, len);
1646
        } else
1647
            avio_w8(pb, 0);
1648
    }
1649
    return updateSize(pb, pos);
1650
}
1651

    
1652
static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
1653
                              AVFormatContext *s)
1654
{
1655
    AVIOContext *pb_buf;
1656
    int i, ret, size;
1657
    uint8_t *buf;
1658

    
1659
    for (i = 0; i < s->nb_streams; i++)
1660
        if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1661
            return 0;
1662
        }
1663

    
1664
    ret = url_open_dyn_buf(&pb_buf);
1665
    if(ret < 0)
1666
        return ret;
1667

    
1668
        if (mov->mode & MODE_3GP) {
1669
            mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
1670
            mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
1671
            mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
1672
            mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
1673
            mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
1674
            mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
1675
            mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
1676
            mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
1677
        } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1678
            mov_write_string_metadata(s, pb_buf, "\251ART", "artist"     , 0);
1679
            mov_write_string_metadata(s, pb_buf, "\251nam", "title"      , 0);
1680
            mov_write_string_metadata(s, pb_buf, "\251aut", "author"     , 0);
1681
            mov_write_string_metadata(s, pb_buf, "\251alb", "album"      , 0);
1682
            mov_write_string_metadata(s, pb_buf, "\251day", "date"       , 0);
1683
            mov_write_string_metadata(s, pb_buf, "\251swr", "encoder"    , 0);
1684
            mov_write_string_metadata(s, pb_buf, "\251des", "comment"    , 0);
1685
            mov_write_string_metadata(s, pb_buf, "\251gen", "genre"      , 0);
1686
            mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright"  , 0);
1687
        } else {
1688
            /* iTunes meta data */
1689
            mov_write_meta_tag(pb_buf, mov, s);
1690
        }
1691

    
1692
        if (s->nb_chapters)
1693
            mov_write_chpl_tag(pb_buf, s);
1694

    
1695
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1696
        avio_wb32(pb, size+8);
1697
        ffio_wfourcc(pb, "udta");
1698
        avio_write(pb, buf, size);
1699
    }
1700
    av_free(buf);
1701

    
1702
    return 0;
1703
}
1704

    
1705
static void mov_write_psp_udta_tag(AVIOContext *pb,
1706
                                  const char *str, const char *lang, int type)
1707
{
1708
    int len = utf8len(str)+1;
1709
    if(len<=0)
1710
        return;
1711
    avio_wb16(pb, len*2+10);            /* size */
1712
    avio_wb32(pb, type);                /* type */
1713
    avio_wb16(pb, language_code(lang)); /* language */
1714
    avio_wb16(pb, 0x01);                /* ? */
1715
    ascii_to_wc(pb, str);
1716
}
1717

    
1718
static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
1719
{
1720
    AVMetadataTag *title = av_metadata_get(s->metadata, "title", NULL, 0);
1721
    int64_t pos, pos2;
1722

    
1723
    if (title) {
1724
        pos = avio_tell(pb);
1725
        avio_wb32(pb, 0); /* size placeholder*/
1726
        ffio_wfourcc(pb, "uuid");
1727
        ffio_wfourcc(pb, "USMT");
1728
        avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
1729
        avio_wb32(pb, 0xbb88695c);
1730
        avio_wb32(pb, 0xfac9c740);
1731

    
1732
        pos2 = avio_tell(pb);
1733
        avio_wb32(pb, 0); /* size placeholder*/
1734
        ffio_wfourcc(pb, "MTDT");
1735
        avio_wb16(pb, 4);
1736

    
1737
        // ?
1738
        avio_wb16(pb, 0x0C);                 /* size */
1739
        avio_wb32(pb, 0x0B);                 /* type */
1740
        avio_wb16(pb, language_code("und")); /* language */
1741
        avio_wb16(pb, 0x0);                  /* ? */
1742
        avio_wb16(pb, 0x021C);               /* data */
1743

    
1744
        mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
1745
        mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
1746
//        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);
1747
        mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1748

    
1749
        updateSize(pb, pos2);
1750
        return updateSize(pb, pos);
1751
    }
1752

    
1753
    return 0;
1754
}
1755

    
1756
static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
1757
                              AVFormatContext *s)
1758
{
1759
    int i;
1760
    int64_t pos = avio_tell(pb);
1761
    avio_wb32(pb, 0); /* size placeholder*/
1762
    ffio_wfourcc(pb, "moov");
1763

    
1764
    for (i=0; i<mov->nb_streams; i++) {
1765
        if(mov->tracks[i].entry <= 0) continue;
1766

    
1767
        mov->tracks[i].time = mov->time;
1768
        mov->tracks[i].trackID = i+1;
1769
    }
1770

    
1771
    if (mov->chapter_track)
1772
        for (i=0; i<s->nb_streams; i++) {
1773
            mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
1774
            mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].trackID;
1775
        }
1776
    for (i = 0; i < mov->nb_streams; i++) {
1777
        if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
1778
            mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
1779
            mov->tracks[i].tref_id =
1780
                mov->tracks[mov->tracks[i].src_track].trackID;
1781
        }
1782
    }
1783

    
1784
    mov_write_mvhd_tag(pb, mov);
1785
    //mov_write_iods_tag(pb, mov);
1786
    for (i=0; i<mov->nb_streams; i++) {
1787
        if(mov->tracks[i].entry > 0) {
1788
            mov_write_trak_tag(pb, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
1789
        }
1790
    }
1791

    
1792
    if (mov->mode == MODE_PSP)
1793
        mov_write_uuidusmt_tag(pb, s);
1794
    else
1795
        mov_write_udta_tag(pb, mov, s);
1796

    
1797
    return updateSize(pb, pos);
1798
}
1799

    
1800
static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
1801
{
1802
    avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
1803
    ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
1804

    
1805
    mov->mdat_pos = avio_tell(pb);
1806
    avio_wb32(pb, 0); /* size placeholder*/
1807
    ffio_wfourcc(pb, "mdat");
1808
    return 0;
1809
}
1810

    
1811
/* TODO: This needs to be more general */
1812
static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
1813
{
1814
    MOVMuxContext *mov = s->priv_data;
1815
    int64_t pos = avio_tell(pb);
1816
    int has_h264 = 0, has_video = 0;
1817
    int minor = 0x200;
1818
    int i;
1819

    
1820
    for (i = 0; i < s->nb_streams; i++) {
1821
        AVStream *st = s->streams[i];
1822
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1823
            has_video = 1;
1824
        if (st->codec->codec_id == CODEC_ID_H264)
1825
            has_h264 = 1;
1826
    }
1827

    
1828
    avio_wb32(pb, 0); /* size */
1829
    ffio_wfourcc(pb, "ftyp");
1830

    
1831
    if (mov->mode == MODE_3GP) {
1832
        ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
1833
        minor =     has_h264 ?   0x100 :   0x200;
1834
    } else if (mov->mode & MODE_3G2) {
1835
        ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
1836
        minor =     has_h264 ? 0x20000 : 0x10000;
1837
    }else if (mov->mode == MODE_PSP)
1838
        ffio_wfourcc(pb, "MSNV");
1839
    else if (mov->mode == MODE_MP4)
1840
        ffio_wfourcc(pb, "isom");
1841
    else if (mov->mode == MODE_IPOD)
1842
        ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
1843
    else
1844
        ffio_wfourcc(pb, "qt  ");
1845

    
1846
    avio_wb32(pb, minor);
1847

    
1848
    if(mov->mode == MODE_MOV)
1849
        ffio_wfourcc(pb, "qt  ");
1850
    else{
1851
        ffio_wfourcc(pb, "isom");
1852
        ffio_wfourcc(pb, "iso2");
1853
        if(has_h264)
1854
            ffio_wfourcc(pb, "avc1");
1855
    }
1856

    
1857
    if (mov->mode == MODE_3GP)
1858
        ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
1859
    else if (mov->mode & MODE_3G2)
1860
        ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
1861
    else if (mov->mode == MODE_PSP)
1862
        ffio_wfourcc(pb, "MSNV");
1863
    else if (mov->mode == MODE_MP4)
1864
        ffio_wfourcc(pb, "mp41");
1865
    return updateSize(pb, pos);
1866
}
1867

    
1868
static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
1869
{
1870
    AVCodecContext *VideoCodec = s->streams[0]->codec;
1871
    AVCodecContext *AudioCodec = s->streams[1]->codec;
1872
    int AudioRate = AudioCodec->sample_rate;
1873
    int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1874
    int audio_kbitrate= AudioCodec->bit_rate / 1000;
1875
    int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1876

    
1877
    avio_wb32(pb, 0x94); /* size */
1878
    ffio_wfourcc(pb, "uuid");
1879
    ffio_wfourcc(pb, "PROF");
1880

    
1881
    avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
1882
    avio_wb32(pb, 0xbb88695c);
1883
    avio_wb32(pb, 0xfac9c740);
1884

    
1885
    avio_wb32(pb, 0x0);  /* ? */
1886
    avio_wb32(pb, 0x3);  /* 3 sections ? */
1887

    
1888
    avio_wb32(pb, 0x14); /* size */
1889
    ffio_wfourcc(pb, "FPRF");
1890
    avio_wb32(pb, 0x0);  /* ? */
1891
    avio_wb32(pb, 0x0);  /* ? */
1892
    avio_wb32(pb, 0x0);  /* ? */
1893

    
1894
    avio_wb32(pb, 0x2c);  /* size */
1895
    ffio_wfourcc(pb, "APRF");/* audio */
1896
    avio_wb32(pb, 0x0);
1897
    avio_wb32(pb, 0x2);   /* TrackID */
1898
    ffio_wfourcc(pb, "mp4a");
1899
    avio_wb32(pb, 0x20f);
1900
    avio_wb32(pb, 0x0);
1901
    avio_wb32(pb, audio_kbitrate);
1902
    avio_wb32(pb, audio_kbitrate);
1903
    avio_wb32(pb, AudioRate);
1904
    avio_wb32(pb, AudioCodec->channels);
1905

    
1906
    avio_wb32(pb, 0x34);  /* size */
1907
    ffio_wfourcc(pb, "VPRF");   /* video */
1908
    avio_wb32(pb, 0x0);
1909
    avio_wb32(pb, 0x1);    /* TrackID */
1910
    if (VideoCodec->codec_id == CODEC_ID_H264) {
1911
        ffio_wfourcc(pb, "avc1");
1912
        avio_wb16(pb, 0x014D);
1913
        avio_wb16(pb, 0x0015);
1914
    } else {
1915
        ffio_wfourcc(pb, "mp4v");
1916
        avio_wb16(pb, 0x0000);
1917
        avio_wb16(pb, 0x0103);
1918
    }
1919
    avio_wb32(pb, 0x0);
1920
    avio_wb32(pb, video_kbitrate);
1921
    avio_wb32(pb, video_kbitrate);
1922
    avio_wb32(pb, FrameRate);
1923
    avio_wb32(pb, FrameRate);
1924
    avio_wb16(pb, VideoCodec->width);
1925
    avio_wb16(pb, VideoCodec->height);
1926
    avio_wb32(pb, 0x010001); /* ? */
1927
}
1928

    
1929
static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
1930
{
1931
    uint32_t c = -1;
1932
    int i, closed_gop = 0;
1933

    
1934
    for (i = 0; i < pkt->size - 4; i++) {
1935
        c = (c<<8) + pkt->data[i];
1936
        if (c == 0x1b8) { // gop
1937
            closed_gop = pkt->data[i+4]>>6 & 0x01;
1938
        } else if (c == 0x100) { // pic
1939
            int temp_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
1940
            if (!temp_ref || closed_gop) // I picture is not reordered
1941
                *flags = MOV_SYNC_SAMPLE;
1942
            else
1943
                *flags = MOV_PARTIAL_SYNC_SAMPLE;
1944
            break;
1945
        }
1946
    }
1947
    return 0;
1948
}
1949

    
1950
int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1951
{
1952
    MOVMuxContext *mov = s->priv_data;
1953
    AVIOContext *pb = s->pb;
1954
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
1955
    AVCodecContext *enc = trk->enc;
1956
    unsigned int samplesInChunk = 0;
1957
    int size= pkt->size;
1958

    
1959
    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1960
    if (!size) return 0; /* Discard 0 sized packets */
1961

    
1962
    if (enc->codec_id == CODEC_ID_AMR_NB) {
1963
        /* We must find out how many AMR blocks there are in one packet */
1964
        static uint16_t packed_size[16] =
1965
            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1966
        int len = 0;
1967

    
1968
        while (len < size && samplesInChunk < 100) {
1969
            len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1970
            samplesInChunk++;
1971
        }
1972
        if(samplesInChunk > 1){
1973
            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
1974
            return -1;
1975
        }
1976
    } else if (enc->codec_id == CODEC_ID_ADPCM_MS ||
1977
               enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
1978
        samplesInChunk = enc->frame_size;
1979
    } else if (trk->sampleSize)
1980
        samplesInChunk = size/trk->sampleSize;
1981
    else
1982
        samplesInChunk = 1;
1983

    
1984
    /* copy extradata if it exists */
1985
    if (trk->vosLen == 0 && enc->extradata_size > 0) {
1986
        trk->vosLen = enc->extradata_size;
1987
        trk->vosData = av_malloc(trk->vosLen);
1988
        memcpy(trk->vosData, enc->extradata, trk->vosLen);
1989
    }
1990

    
1991
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1992
        /* from x264 or from bytestream h264 */
1993
        /* nal reformating needed */
1994
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1995
    } else {
1996
        avio_write(pb, pkt->data, size);
1997
    }
1998

    
1999
    if ((enc->codec_id == CODEC_ID_DNXHD ||
2000
         enc->codec_id == CODEC_ID_AC3) && !trk->vosLen) {
2001
        /* copy frame to create needed atoms */
2002
        trk->vosLen = size;
2003
        trk->vosData = av_malloc(size);
2004
        if (!trk->vosData)
2005
            return AVERROR(ENOMEM);
2006
        memcpy(trk->vosData, pkt->data, size);
2007
    }
2008

    
2009
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
2010
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
2011
        if (!trk->cluster)
2012
            return -1;
2013
    }
2014

    
2015
    trk->cluster[trk->entry].pos = avio_tell(pb) - size;
2016
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
2017
    trk->cluster[trk->entry].size = size;
2018
    trk->cluster[trk->entry].entries = samplesInChunk;
2019
    trk->cluster[trk->entry].dts = pkt->dts;
2020
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
2021

    
2022
    if (pkt->pts == AV_NOPTS_VALUE) {
2023
        av_log(s, AV_LOG_WARNING, "pts has no value\n");
2024
        pkt->pts = pkt->dts;
2025
    }
2026
    if (pkt->dts != pkt->pts)
2027
        trk->flags |= MOV_TRACK_CTTS;
2028
    trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
2029
    trk->cluster[trk->entry].flags = 0;
2030
    if (pkt->flags & AV_PKT_FLAG_KEY) {
2031
        if (mov->mode == MODE_MOV && enc->codec_id == CODEC_ID_MPEG2VIDEO &&
2032
            trk->entry > 0) { // force sync sample for the first key frame
2033
            mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
2034
            if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
2035
                trk->flags |= MOV_TRACK_STPS;
2036
        } else {
2037
            trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
2038
        }
2039
        if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
2040
            trk->hasKeyframes++;
2041
    }
2042
    trk->entry++;
2043
    trk->sampleCount += samplesInChunk;
2044
    mov->mdat_size += size;
2045

    
2046
    avio_flush(pb);
2047

    
2048
    if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
2049
        ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry);
2050
    return 0;
2051
}
2052

    
2053
// QuickTime chapters involve an additional text track with the chapter names
2054
// as samples, and a tref pointing from the other tracks to the chapter one.
2055
static void mov_create_chapter_track(AVFormatContext *s, int tracknum)
2056
{
2057
    MOVMuxContext *mov = s->priv_data;
2058
    MOVTrack *track = &mov->tracks[tracknum];
2059
    AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
2060
    int i, len;
2061

    
2062
    track->mode = mov->mode;
2063
    track->tag = MKTAG('t','e','x','t');
2064
    track->timescale = MOV_TIMESCALE;
2065
    track->enc = avcodec_alloc_context();
2066
    track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
2067

    
2068
    for (i = 0; i < s->nb_chapters; i++) {
2069
        AVChapter *c = s->chapters[i];
2070
        AVMetadataTag *t;
2071

    
2072
        int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
2073
        pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
2074
        pkt.duration = end - pkt.dts;
2075

    
2076
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
2077
            len = strlen(t->value);
2078
            pkt.size = len+2;
2079
            pkt.data = av_malloc(pkt.size);
2080
            AV_WB16(pkt.data, len);
2081
            memcpy(pkt.data+2, t->value, len);
2082
            ff_mov_write_packet(s, &pkt);
2083
            av_freep(&pkt.data);
2084
        }
2085
    }
2086
}
2087

    
2088
static int mov_write_header(AVFormatContext *s)
2089
{
2090
    AVIOContext *pb = s->pb;
2091
    MOVMuxContext *mov = s->priv_data;
2092
    int i, hint_track = 0;
2093

    
2094
    if (url_is_streamed(s->pb)) {
2095
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
2096
        return -1;
2097
    }
2098

    
2099
    /* Default mode == MP4 */
2100
    mov->mode = MODE_MP4;
2101

    
2102
    if (s->oformat != NULL) {
2103
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
2104
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
2105
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
2106
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
2107
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
2108

    
2109
        mov_write_ftyp_tag(pb,s);
2110
        if (mov->mode == MODE_PSP) {
2111
            if (s->nb_streams != 2) {
2112
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
2113
                return -1;
2114
            }
2115
            mov_write_uuidprof_tag(pb,s);
2116
        }
2117
    }
2118

    
2119
    mov->nb_streams = s->nb_streams;
2120
    if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
2121
        mov->chapter_track = mov->nb_streams++;
2122

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

    
2135
    mov->tracks = av_mallocz(mov->nb_streams*sizeof(*mov->tracks));
2136
    if (!mov->tracks)
2137
        return AVERROR(ENOMEM);
2138

    
2139
    for(i=0; i<s->nb_streams; i++){
2140
        AVStream *st= s->streams[i];
2141
        MOVTrack *track= &mov->tracks[i];
2142
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
2143

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

    
2210
        av_set_pts_info(st, 64, 1, track->timescale);
2211
    }
2212

    
2213
    mov_write_mdat_tag(pb, mov);
2214
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
2215

    
2216
    if (mov->chapter_track)
2217
        mov_create_chapter_track(s, mov->chapter_track);
2218

    
2219
    if (s->flags & AVFMT_FLAG_RTP_HINT) {
2220
        /* Initialize the hint tracks for each audio and video stream */
2221
        for (i = 0; i < s->nb_streams; i++) {
2222
            AVStream *st = s->streams[i];
2223
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2224
                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2225
                ff_mov_init_hinting(s, hint_track, i);
2226
                hint_track++;
2227
            }
2228
        }
2229
    }
2230

    
2231
    avio_flush(pb);
2232

    
2233
    return 0;
2234
 error:
2235
    av_freep(&mov->tracks);
2236
    return -1;
2237
}
2238

    
2239
static int mov_write_trailer(AVFormatContext *s)
2240
{
2241
    MOVMuxContext *mov = s->priv_data;
2242
    AVIOContext *pb = s->pb;
2243
    int res = 0;
2244
    int i;
2245

    
2246
    int64_t moov_pos = avio_tell(pb);
2247

    
2248
    /* Write size of mdat tag */
2249
    if (mov->mdat_size+8 <= UINT32_MAX) {
2250
        avio_seek(pb, mov->mdat_pos, SEEK_SET);
2251
        avio_wb32(pb, mov->mdat_size+8);
2252
    } else {
2253
        /* overwrite 'wide' placeholder atom */
2254
        avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
2255
        avio_wb32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
2256
        ffio_wfourcc(pb, "mdat");
2257
        avio_wb64(pb, mov->mdat_size+16);
2258
    }
2259
    avio_seek(pb, moov_pos, SEEK_SET);
2260

    
2261
    mov_write_moov_tag(pb, mov, s);
2262

    
2263
    if (mov->chapter_track)
2264
        av_freep(&mov->tracks[mov->chapter_track].enc);
2265

    
2266
    for (i=0; i<mov->nb_streams; i++) {
2267
        if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
2268
            ff_mov_close_hinting(&mov->tracks[i]);
2269
        av_freep(&mov->tracks[i].cluster);
2270

    
2271
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2272

    
2273
    }
2274

    
2275
    avio_flush(pb);
2276

    
2277
    av_freep(&mov->tracks);
2278

    
2279
    return res;
2280
}
2281

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