Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ c22f2527

History | View | Annotate | Download (78.9 KB)

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

    
24
#include "movenc.h"
25
#include "avformat.h"
26
#include "avio_internal.h"
27
#include "riff.h"
28
#include "avio.h"
29
#include "isom.h"
30
#include "avc.h"
31
#include "libavcodec/get_bits.h"
32
#include "libavcodec/put_bits.h"
33
#include "internal.h"
34
#include "libavutil/avstring.h"
35

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

    
39
//FIXME support 64 bit variant with wide placeholders
40
static int64_t updateSize(AVIOContext *pb, int64_t pos)
41
{
42
    int64_t curpos = 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 void putDescr(AVIOContext *pb, int tag, unsigned int size)
242
{
243
    int i = 3;
244
    avio_w8(pb, tag);
245
    for(; i>0; i--)
246
        avio_w8(pb, (size>>(7*i)) | 0x80);
247
    avio_w8(pb, size & 0x7F);
248
}
249

    
250
static unsigned compute_avg_bitrate(MOVTrack *track)
251
{
252
    uint64_t size = 0;
253
    int i;
254
    for (i = 0; i < track->entry; i++)
255
        size += track->cluster[i].size;
256
    return size * 8 * track->timescale / track->trackDuration;
257
}
258

    
259
static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
260
{
261
    int64_t pos = avio_tell(pb);
262
    int decoderSpecificInfoLen = track->vosLen ? 5+track->vosLen : 0;
263
    unsigned avg_bitrate;
264

    
265
    avio_wb32(pb, 0); // size
266
    ffio_wfourcc(pb, "esds");
267
    avio_wb32(pb, 0); // Version
268

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

    
274
    // DecoderConfig descriptor
275
    putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
276

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

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

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

    
295
    avg_bitrate = compute_avg_bitrate(track);
296
    // maxbitrate (FIXME should be max rate in any 1 sec window)
297
    avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
298
    avio_wb32(pb, avg_bitrate);
299

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
593
    return tag;
594
}
595

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

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

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

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

    
621
    return tag;
622
}
623

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

    
628
    if (track->enc->width == 720) /* SD */
629
        if (track->enc->height == 480) /* NTSC */
630
            if  (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
631
            else                                         tag = MKTAG('d','v','c',' ');
632
        else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
633
        else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
634
        else                                             tag = MKTAG('d','v','p','p');
635
    else if (track->enc->height == 720) /* HD 720 line */
636
        if  (track->enc->time_base.den == 50)            tag = MKTAG('d','v','h','q');
637
        else                                             tag = MKTAG('d','v','h','p');
638
    else if (track->enc->height == 1080) /* HD 1080 line */
639
        if  (track->enc->time_base.den == 25)            tag = MKTAG('d','v','h','5');
640
        else                                             tag = MKTAG('d','v','h','6');
641
    else {
642
        av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
643
        return 0;
644
    }
645

    
646
    return tag;
647
}
648

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

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

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

    
683
    return tag;
684
}
685

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

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

    
721
    return tag;
722
}
723

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

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

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

    
748
    return tag;
749
}
750

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
988
    return 28;
989
}
990

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1172
    return 32;
1173
}
1174

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

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

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

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

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

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

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

    
1254
    int64_t pos = avio_tell(pb);
1255

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1665
    ret = avio_open_dyn_buf(&pb_buf);
1666
    if(ret < 0)
1667
        return ret;
1668

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

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

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

    
1703
    return 0;
1704
}
1705

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

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

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

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

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

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

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

    
1754
    return 0;
1755
}
1756

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1847
    avio_wb32(pb, minor);
1848

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1992
    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1993
        /* from x264 or from bytestream h264 */
1994
        /* nal reformating needed */
1995
        size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
1996
    } else if (enc->codec_id == CODEC_ID_AAC && pkt->size > 2 &&
1997
               (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
1998
        av_log(s, AV_LOG_ERROR, "malformated aac bitstream, use -absf aac_adtstoasc\n");
1999
        return -1;
2000
    } else {
2001
        avio_write(pb, pkt->data, size);
2002
    }
2003

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

    
2014
    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
2015
        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
2016
        if (!trk->cluster)
2017
            return -1;
2018
    }
2019

    
2020
    trk->cluster[trk->entry].pos = avio_tell(pb) - size;
2021
    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
2022
    trk->cluster[trk->entry].size = size;
2023
    trk->cluster[trk->entry].entries = samplesInChunk;
2024
    trk->cluster[trk->entry].dts = pkt->dts;
2025
    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
2026

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

    
2051
    avio_flush(pb);
2052

    
2053
    if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
2054
        ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry);
2055
    return 0;
2056
}
2057

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

    
2067
    track->mode = mov->mode;
2068
    track->tag = MKTAG('t','e','x','t');
2069
    track->timescale = MOV_TIMESCALE;
2070
    track->enc = avcodec_alloc_context();
2071
    track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
2072

    
2073
    for (i = 0; i < s->nb_chapters; i++) {
2074
        AVChapter *c = s->chapters[i];
2075
        AVMetadataTag *t;
2076

    
2077
        int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
2078
        pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
2079
        pkt.duration = end - pkt.dts;
2080

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

    
2093
static int mov_write_header(AVFormatContext *s)
2094
{
2095
    AVIOContext *pb = s->pb;
2096
    MOVMuxContext *mov = s->priv_data;
2097
    int i, hint_track = 0;
2098

    
2099
    if (!s->pb->seekable) {
2100
        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
2101
        return -1;
2102
    }
2103

    
2104
    /* Default mode == MP4 */
2105
    mov->mode = MODE_MP4;
2106

    
2107
    if (s->oformat != NULL) {
2108
        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
2109
        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
2110
        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
2111
        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
2112
        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
2113

    
2114
        mov_write_ftyp_tag(pb,s);
2115
        if (mov->mode == MODE_PSP) {
2116
            if (s->nb_streams != 2) {
2117
                av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
2118
                return -1;
2119
            }
2120
            mov_write_uuidprof_tag(pb,s);
2121
        }
2122
    }
2123

    
2124
    mov->nb_streams = s->nb_streams;
2125
    if (mov->mode & (MODE_MOV|MODE_IPOD) && s->nb_chapters)
2126
        mov->chapter_track = mov->nb_streams++;
2127

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

    
2140
    mov->tracks = av_mallocz(mov->nb_streams*sizeof(*mov->tracks));
2141
    if (!mov->tracks)
2142
        return AVERROR(ENOMEM);
2143

    
2144
    for(i=0; i<s->nb_streams; i++){
2145
        AVStream *st= s->streams[i];
2146
        MOVTrack *track= &mov->tracks[i];
2147
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
2148

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

    
2215
        av_set_pts_info(st, 64, 1, track->timescale);
2216
    }
2217

    
2218
    mov_write_mdat_tag(pb, mov);
2219
    mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
2220

    
2221
    if (mov->chapter_track)
2222
        mov_create_chapter_track(s, mov->chapter_track);
2223

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

    
2236
    avio_flush(pb);
2237

    
2238
    return 0;
2239
 error:
2240
    av_freep(&mov->tracks);
2241
    return -1;
2242
}
2243

    
2244
static int mov_write_trailer(AVFormatContext *s)
2245
{
2246
    MOVMuxContext *mov = s->priv_data;
2247
    AVIOContext *pb = s->pb;
2248
    int res = 0;
2249
    int i;
2250

    
2251
    int64_t moov_pos = avio_tell(pb);
2252

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

    
2266
    mov_write_moov_tag(pb, mov, s);
2267

    
2268
    if (mov->chapter_track)
2269
        av_freep(&mov->tracks[mov->chapter_track].enc);
2270

    
2271
    for (i=0; i<mov->nb_streams; i++) {
2272
        if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
2273
            ff_mov_close_hinting(&mov->tracks[i]);
2274
        av_freep(&mov->tracks[i].cluster);
2275

    
2276
        if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
2277

    
2278
    }
2279

    
2280
    avio_flush(pb);
2281

    
2282
    av_freep(&mov->tracks);
2283

    
2284
    return res;
2285
}
2286

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