Statistics
| Branch: | Revision:

ffmpeg / libavformat / movenc.c @ 62bacc4e

History | View | Annotate | Download (76.1 KB)

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

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

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

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

    
46
    return curpos - pos;
47
}
48

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

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

    
78
    int64_t pos = url_ftell(pb);
79
    put_be32(pb, 0); /* size */
80
    put_tag(pb, "stsz");
81
    put_be32(pb, 0); /* version & flags */
82

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

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

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

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

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

    
163
static int mov_write_amr_tag(ByteIOContext *pb, MOVTrack *track)
164
{
165
    put_be32(pb, 0x11); /* size */
166
    if (track->mode == MODE_MOV) put_tag(pb, "samr");
167
    else                         put_tag(pb, "damr");
168
    put_tag(pb, "FFMP");
169
    put_byte(pb, 0); /* decoder version */
170

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

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

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

    
187
    put_be32(pb, 11);
188
    put_tag(pb, "dac3");
189

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

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

    
215
    flush_put_bits(&pbc);
216
    put_buffer(pb, buf, sizeof(buf));
217

    
218
    return 11;
219
}
220

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

    
231
static int mov_write_enda_tag(ByteIOContext *pb)
232
{
233
    put_be32(pb, 10);
234
    put_tag(pb, "enda");
235
    put_be16(pb, 1); /* little endian */
236
    return 10;
237
}
238

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

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

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

    
260
    put_be32(pb, 0); // size
261
    put_tag(pb, "esds");
262
    put_be32(pb, 0); // Version
263

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

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

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

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

    
288
    put_byte(pb,  track->enc->rc_buffer_size>>(3+16));    // Buffersize DB (24 bits)
289
    put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
290

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

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

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

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

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

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

    
331
    put_be32(pb, 0);     /* size */
332
    put_tag(pb, "wave");
333

    
334
    put_be32(pb, 12);    /* size */
335
    put_tag(pb, "frma");
336
    put_le32(pb, track->tag);
337

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

    
357
    put_be32(pb, 8);     /* size */
358
    put_be32(pb, 0);     /* null tag */
359

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

    
363
static int mov_write_glbl_tag(ByteIOContext *pb, MOVTrack *track)
364
{
365
    put_be32(pb, track->vosLen+8);
366
    put_tag(pb, "glbl");
367
    put_buffer(pb, track->vosData, track->vosLen);
368
    return 8+track->vosLen;
369
}
370

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

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

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

    
418
    put_be32(pb, 0); /* size */
419
    put_le32(pb, tag); // store it byteswapped
420
    put_be32(pb, 0); /* Reserved */
421
    put_be16(pb, 0); /* Reserved */
422
    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */
423

    
424
    /* SoundDescription */
425
    put_be16(pb, version); /* Version */
426
    put_be16(pb, 0); /* Revision level */
427
    put_be32(pb, 0); /* Reserved */
428

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

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

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

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

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

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

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

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

    
522
    put_be32(pb, 0);
523
    put_tag(pb, "avcC");
524
    ff_isom_write_avcc(pb, track->vosData, track->vosLen);
525
    return updateSize(pb, pos);
526
}
527

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

    
539
    put_be32(pb, 24); /* size */
540
    put_tag(pb, "APRG");
541
    put_tag(pb, "APRG");
542
    put_tag(pb, "0001");
543
    put_be32(pb, 1); /* unknown */
544
    put_be32(pb, 0); /* unknown */
545

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

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

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

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

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

    
590
    return tag;
591
}
592

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

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

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

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

    
618
    return tag;
619
}
620

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

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

    
632
    return tag;
633
}
634

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

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

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

    
669
    return tag;
670
}
671

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

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

    
707
    return tag;
708
}
709

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

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

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

    
734
    return tag;
735
}
736

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

    
753
static int mov_write_subtitle_tag(ByteIOContext *pb, MOVTrack *track)
754
{
755
    int64_t pos = url_ftell(pb);
756
    put_be32(pb, 0);    /* size */
757
    put_le32(pb, track->tag); // store it byteswapped
758
    put_be32(pb, 0);    /* Reserved */
759
    put_be16(pb, 0);    /* Reserved */
760
    put_be16(pb, 1);    /* Data-reference index */
761

    
762
    if (track->enc->extradata_size)
763
        put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
764

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

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

    
774
    put_be32(pb, 16);
775
    put_tag(pb, "pasp");
776
    put_be32(pb, sar.num);
777
    put_be32(pb, sar.den);
778
    return 16;
779
}
780

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

    
786
    put_be32(pb, 0); /* size */
787
    put_le32(pb, track->tag); // store it byteswapped
788
    put_be32(pb, 0); /* Reserved */
789
    put_be16(pb, 0); /* Reserved */
790
    put_be16(pb, 1); /* Data-reference index */
791

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

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

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

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

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

    
851
static int mov_write_rtp_tag(ByteIOContext *pb, MOVTrack *track)
852
{
853
    int64_t pos = url_ftell(pb);
854
    put_be32(pb, 0); /* size */
855
    put_tag(pb, "rtp ");
856
    put_be32(pb, 0); /* Reserved */
857
    put_be16(pb, 0); /* Reserved */
858
    put_be16(pb, 1); /* Data-reference index */
859

    
860
    put_be16(pb, 1); /* Hint track version */
861
    put_be16(pb, 1); /* Highest compatible version */
862
    put_be32(pb, track->max_packet_size); /* Max packet size */
863

    
864
    put_be32(pb, 12); /* size */
865
    put_tag(pb, "tims");
866
    put_be32(pb, track->timescale);
867

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

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

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

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

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

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

    
964
static int mov_write_dref_tag(ByteIOContext *pb)
965
{
966
    put_be32(pb, 28); /* size */
967
    put_tag(pb, "dref");
968
    put_be32(pb, 0); /* version & flags */
969
    put_be32(pb, 1); /* entry count */
970

    
971
    put_be32(pb, 0xc); /* size */
972
    put_tag(pb, "url ");
973
    put_be32(pb, 1); /* version & flags */
974

    
975
    return 28;
976
}
977

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

    
1000
static int mov_write_dinf_tag(ByteIOContext *pb)
1001
{
1002
    int64_t pos = url_ftell(pb);
1003
    put_be32(pb, 0); /* size */
1004
    put_tag(pb, "dinf");
1005
    mov_write_dref_tag(pb);
1006
    return updateSize(pb, pos);
1007
}
1008

    
1009
static int mov_write_nmhd_tag(ByteIOContext *pb)
1010
{
1011
    put_be32(pb, 12);
1012
    put_tag(pb, "nmhd");
1013
    put_be32(pb, 0);
1014
    return 12;
1015
}
1016

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

    
1033
static int mov_write_smhd_tag(ByteIOContext *pb)
1034
{
1035
    put_be32(pb, 16); /* size */
1036
    put_tag(pb, "smhd");
1037
    put_be32(pb, 0); /* version & flags */
1038
    put_be16(pb, 0); /* reserved (balance, normally = 0) */
1039
    put_be16(pb, 0); /* reserved */
1040
    return 16;
1041
}
1042

    
1043
static int mov_write_vmhd_tag(ByteIOContext *pb)
1044
{
1045
    put_be32(pb, 0x14); /* size (always 0x14) */
1046
    put_tag(pb, "vmhd");
1047
    put_be32(pb, 0x01); /* version & flags */
1048
    put_be64(pb, 0); /* reserved (graphics mode = copy) */
1049
    return 0x14;
1050
}
1051

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

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

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

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

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

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

    
1136
    (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
1137
    put_tag(pb, "mdhd");
1138
    put_byte(pb, version);
1139
    put_be24(pb, 0); /* flags */
1140
    if (version == 1) {
1141
        put_be64(pb, track->time);
1142
        put_be64(pb, track->time);
1143
    } else {
1144
        put_be32(pb, track->time); /* creation time */
1145
        put_be32(pb, track->time); /* modification time */
1146
    }
1147
    put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
1148
    (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
1149
    put_be16(pb, track->language); /* language */
1150
    put_be16(pb, 0); /* reserved (quality) */
1151

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

    
1159
    return 32;
1160
}
1161

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

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

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

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

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

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

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

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

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

    
1250
static int mov_write_tref_tag(ByteIOContext *pb, MOVTrack *track)
1251
{
1252
    put_be32(pb, 20);   // size
1253
    put_tag(pb, "tref");
1254
    put_be32(pb, 12);   // size (subatom)
1255
    put_le32(pb, track->tref_tag);
1256
    put_be32(pb, track->tref_id);
1257
    return 20;
1258
}
1259

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

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

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

    
1288
    put_be32(pb, len + 24);
1289
    put_tag (pb, "udta");
1290
    put_be32(pb, len + 16);
1291
    put_tag (pb, "hnti");
1292
    put_be32(pb, len + 8);
1293
    put_tag (pb, "sdp ");
1294
    put_buffer(pb, buf, len);
1295
    return len + 24;
1296
}
1297

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

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

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

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

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

    
1366
    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1367
    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1368
    put_be16(pb, 0); /* reserved */
1369
    put_be32(pb, 0); /* reserved */
1370
    put_be32(pb, 0); /* reserved */
1371

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

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

    
1393
static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVMuxContext *mov,
1394
                                     AVFormatContext *s)
1395
{
1396
    put_be32(pb, 33); /* size */
1397
    put_tag(pb, "hdlr");
1398
    put_be32(pb, 0);
1399
    put_be32(pb, 0);
1400
    put_tag(pb, "mdir");
1401
    put_tag(pb, "appl");
1402
    put_be32(pb, 0);
1403
    put_be32(pb, 0);
1404
    put_byte(pb, 0);
1405
    return 33;
1406
}
1407

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1584
    put_be32(pb, 0);            // size
1585
    put_tag (pb, "chpl");
1586
    put_be32(pb, 0x01000000);   // version + flags
1587
    put_be32(pb, 0);            // unknown
1588
    put_byte(pb, nb_chapters);
1589

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

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

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

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

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

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

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

    
1648
    if ((size = url_close_dyn_buf(pb_buf, &buf)) > 0) {
1649
        put_be32(pb, size+8);
1650
        put_tag(pb, "udta");
1651
        put_buffer(pb, buf, size);
1652
    }
1653
    av_free(buf);
1654

    
1655
    return 0;
1656
}
1657

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

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

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

    
1685
        pos2 = url_ftell(pb);
1686
        put_be32(pb, 0); /* size placeholder*/
1687
        put_tag(pb, "MTDT");
1688
        put_be16(pb, 4);
1689

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

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

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

    
1706
    return 0;
1707
}
1708

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

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

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

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

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

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

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

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

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

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

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

    
1781
    put_be32(pb, 0); /* size */
1782
    put_tag(pb, "ftyp");
1783

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

    
1799
    put_be32(pb, minor);
1800

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

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

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

    
1830
    put_be32(pb, 0x94); /* size */
1831
    put_tag(pb, "uuid");
1832
    put_tag(pb, "PROF");
1833

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

    
1838
    put_be32(pb, 0x0);  /* ? */
1839
    put_be32(pb, 0x3);  /* 3 sections ? */
1840

    
1841
    put_be32(pb, 0x14); /* size */
1842
    put_tag(pb, "FPRF");
1843
    put_be32(pb, 0x0);  /* ? */
1844
    put_be32(pb, 0x0);  /* ? */
1845
    put_be32(pb, 0x0);  /* ? */
1846

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1999
    put_flush_packet(pb);
2000

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2184
    put_flush_packet(pb);
2185

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

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

    
2199
    int64_t moov_pos = url_ftell(pb);
2200

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

    
2214
    mov_write_moov_tag(pb, mov, s);
2215

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

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

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

    
2226
    }
2227

    
2228
    put_flush_packet(pb);
2229

    
2230
    av_freep(&mov->tracks);
2231

    
2232
    return res;
2233
}
2234

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