flvenc.c 15.9 KB
Newer Older
1
/*
2
 * FLV muxer
3
 * Copyright (c) 2003 The Libav Project
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * Libav is distributed in the hope that it will be useful,
13 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with Libav; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

22
#include "libavutil/intfloat.h"
23
#include "avformat.h"
24
#include "flv.h"
25
#include "internal.h"
B
Baptiste Coudurier 已提交
26
#include "avc.h"
T
Tomás Touceda 已提交
27
#include "metadata.h"
28
#include "libavutil/dict.h"
29

M
cleanup  
Michael Niedermayer 已提交
30 31 32
#undef NDEBUG
#include <assert.h>

33
static const AVCodecTag flv_video_codec_ids[] = {
34 35
    {CODEC_ID_FLV1,    FLV_CODECID_H263  },
    {CODEC_ID_FLASHSV, FLV_CODECID_SCREEN},
36
    {CODEC_ID_FLASHSV2, FLV_CODECID_SCREEN2},
37
    {CODEC_ID_VP6F,    FLV_CODECID_VP6   },
38
    {CODEC_ID_VP6,     FLV_CODECID_VP6   },
B
Baptiste Coudurier 已提交
39
    {CODEC_ID_H264,    FLV_CODECID_H264  },
40 41 42
    {CODEC_ID_NONE,    0}
};

43
static const AVCodecTag flv_audio_codec_ids[] = {
44
    {CODEC_ID_MP3,       FLV_CODECID_MP3    >> FLV_AUDIO_CODECID_OFFSET},
45
    {CODEC_ID_PCM_U8,    FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
46
    {CODEC_ID_PCM_S16BE, FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
47 48
    {CODEC_ID_PCM_S16LE, FLV_CODECID_PCM_LE >> FLV_AUDIO_CODECID_OFFSET},
    {CODEC_ID_ADPCM_SWF, FLV_CODECID_ADPCM  >> FLV_AUDIO_CODECID_OFFSET},
B
Baptiste Coudurier 已提交
49
    {CODEC_ID_AAC,       FLV_CODECID_AAC    >> FLV_AUDIO_CODECID_OFFSET},
B
Bartlomiej Wolowiec 已提交
50
    {CODEC_ID_NELLYMOSER, FLV_CODECID_NELLYMOSER >> FLV_AUDIO_CODECID_OFFSET},
51
    {CODEC_ID_SPEEX,     FLV_CODECID_SPEEX  >> FLV_AUDIO_CODECID_OFFSET},
52 53 54
    {CODEC_ID_NONE,      0}
};

55
typedef struct FLVContext {
M
Michael Niedermayer 已提交
56
    int reserved;
57 58
    int64_t duration_offset;
    int64_t filesize_offset;
59
    int64_t duration;
60
    int64_t delay;      ///< first dts delay (needed for AVC & Speex)
61 62
} FLVContext;

63 64 65 66
typedef struct FLVStreamContext {
    int64_t last_ts;    ///< last timestamp for each stream
} FLVStreamContext;

M
Michael Niedermayer 已提交
67
static int get_audio_flags(AVCodecContext *enc){
68
    int flags = (enc->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT : FLV_SAMPLESSIZE_8BIT;
M
Michael Niedermayer 已提交
69

B
Baptiste Coudurier 已提交
70 71
    if (enc->codec_id == CODEC_ID_AAC) // specs force these parameters
        return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ | FLV_SAMPLESSIZE_16BIT | FLV_STEREO;
72 73 74 75 76 77 78 79 80 81 82
    else if (enc->codec_id == CODEC_ID_SPEEX) {
        if (enc->sample_rate != 16000) {
            av_log(enc, AV_LOG_ERROR, "flv only supports wideband (16kHz) Speex audio\n");
            return -1;
        }
        if (enc->channels != 1) {
            av_log(enc, AV_LOG_ERROR, "flv only supports mono Speex audio\n");
            return -1;
        }
        return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT;
    } else {
M
Michael Niedermayer 已提交
83 84
    switch (enc->sample_rate) {
        case    44100:
85
            flags |= FLV_SAMPLERATE_44100HZ;
M
Michael Niedermayer 已提交
86 87
            break;
        case    22050:
88
            flags |= FLV_SAMPLERATE_22050HZ;
M
Michael Niedermayer 已提交
89 90
            break;
        case    11025:
91
            flags |= FLV_SAMPLERATE_11025HZ;
M
Michael Niedermayer 已提交
92 93 94
            break;
        case     8000: //nellymoser only
        case     5512: //not mp3
95
            if(enc->codec_id != CODEC_ID_MP3){
M
indent  
Michael Niedermayer 已提交
96 97
                flags |= FLV_SAMPLERATE_SPECIAL;
                break;
98
            }
M
Michael Niedermayer 已提交
99
        default:
D
Diego Biurrun 已提交
100
            av_log(enc, AV_LOG_ERROR, "flv does not support that sample rate, choose from (44100, 22050, 11025).\n");
M
Michael Niedermayer 已提交
101 102
            return -1;
    }
B
Baptiste Coudurier 已提交
103
    }
M
Michael Niedermayer 已提交
104 105

    if (enc->channels > 1) {
106
        flags |= FLV_STEREO;
M
Michael Niedermayer 已提交
107
    }
108

M
Michael Niedermayer 已提交
109 110
    switch(enc->codec_id){
    case CODEC_ID_MP3:
111
        flags |= FLV_CODECID_MP3    | FLV_SAMPLESSIZE_16BIT;
M
Michael Niedermayer 已提交
112
        break;
113
    case CODEC_ID_PCM_U8:
114
        flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_8BIT;
115
        break;
A
Alex Beregszaszi 已提交
116
    case CODEC_ID_PCM_S16BE:
117
        flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_16BIT;
118
        break;
A
Alex Beregszaszi 已提交
119
    case CODEC_ID_PCM_S16LE:
120
        flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;
121
        break;
A
Alex Beregszaszi 已提交
122
    case CODEC_ID_ADPCM_SWF:
123
        flags |= FLV_CODECID_ADPCM | FLV_SAMPLESSIZE_16BIT;
124
        break;
B
Bartlomiej Wolowiec 已提交
125
    case CODEC_ID_NELLYMOSER:
126 127 128 129 130
        if (enc->sample_rate == 8000) {
            flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
        } else {
            flags |= FLV_CODECID_NELLYMOSER | FLV_SAMPLESSIZE_16BIT;
        }
B
Bartlomiej Wolowiec 已提交
131
        break;
M
Michael Niedermayer 已提交
132 133 134 135
    case 0:
        flags |= enc->codec_tag<<4;
        break;
    default:
136
        av_log(enc, AV_LOG_ERROR, "codec not compatible with flv\n");
M
Michael Niedermayer 已提交
137 138
        return -1;
    }
139

M
Michael Niedermayer 已提交
140 141 142
    return flags;
}

143
static void put_amf_string(AVIOContext *pb, const char *str)
144 145
{
    size_t len = strlen(str);
146 147
    avio_wb16(pb, len);
    avio_write(pb, str, len);
148 149
}

150
static void put_avc_eos_tag(AVIOContext *pb, unsigned ts) {
151 152 153 154 155 156 157 158 159
    avio_w8(pb, FLV_TAG_TYPE_VIDEO);
    avio_wb24(pb, 5);  /* Tag Data Size */
    avio_wb24(pb, ts);  /* lower 24 bits of timestamp in ms*/
    avio_w8(pb, (ts >> 24) & 0x7F);  /* MSB of ts in ms*/
    avio_wb24(pb, 0);  /* StreamId = 0 */
    avio_w8(pb, 23);  /* ub[4] FrameType = 1, ub[4] CodecId = 7 */
    avio_w8(pb, 2);  /* AVC end of sequence */
    avio_wb24(pb, 0);  /* Always 0 for AVC EOS. */
    avio_wb32(pb, 16);  /* Size of FLV tag */
160 161
}

162
static void put_amf_double(AVIOContext *pb, double d)
163
{
164
    avio_w8(pb, AMF_DATA_TYPE_NUMBER);
165
    avio_wb64(pb, av_double2int(d));
166 167
}

168
static void put_amf_bool(AVIOContext *pb, int b) {
169 170
    avio_w8(pb, AMF_DATA_TYPE_BOOL);
    avio_w8(pb, !!b);
171 172
}

173 174
static int flv_write_header(AVFormatContext *s)
{
175
    AVIOContext *pb = s->pb;
176
    FLVContext *flv = s->priv_data;
177
    AVCodecContext *audio_enc = NULL, *video_enc = NULL;
178
    int i, metadata_count = 0;
179
    double framerate = 0.0;
180
    int64_t metadata_size_pos, data_size, metadata_count_pos;
181
    AVDictionaryEntry *tag = NULL;
182

M
Michael Niedermayer 已提交
183
    for(i=0; i<s->nb_streams; i++){
184
        AVCodecContext *enc = s->streams[i]->codec;
185
        FLVStreamContext *sc;
186
        if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
187 188 189 190 191
            if (s->streams[i]->r_frame_rate.den && s->streams[i]->r_frame_rate.num) {
                framerate = av_q2d(s->streams[i]->r_frame_rate);
            } else {
                framerate = 1/av_q2d(s->streams[i]->codec->time_base);
            }
192 193
            video_enc = enc;
            if(enc->codec_tag == 0) {
194 195 196
                av_log(enc, AV_LOG_ERROR, "video codec not compatible with flv\n");
                return -1;
            }
197
        } else {
198
            audio_enc = enc;
199 200
            if(get_audio_flags(enc)<0)
                return -1;
201
        }
202
        avpriv_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
203 204 205 206 207 208

        sc = av_mallocz(sizeof(FLVStreamContext));
        if (!sc)
            return AVERROR(ENOMEM);
        s->streams[i]->priv_data = sc;
        sc->last_ts = -1;
209
    }
210 211
    flv->delay = AV_NOPTS_VALUE;

212
    avio_write(pb, "FLV", 3);
213 214
    avio_w8(pb,1);
    avio_w8(pb,   FLV_HEADER_FLAG_HASAUDIO * !!audio_enc
215
                 + FLV_HEADER_FLAG_HASVIDEO * !!video_enc);
216 217
    avio_wb32(pb,9);
    avio_wb32(pb,0);
218 219 220

    for(i=0; i<s->nb_streams; i++){
        if(s->streams[i]->codec->codec_tag == 5){
221 222 223 224 225
            avio_w8(pb,8); // message type
            avio_wb24(pb,0); // include flags
            avio_wb24(pb,0); // time stamp
            avio_wb32(pb,0); // reserved
            avio_wb32(pb,11); // size
M
Michael Niedermayer 已提交
226 227 228
            flv->reserved=5;
        }
    }
229

230
    /* write meta_tag */
231
    avio_w8(pb, 18);         // tag type META
232
    metadata_size_pos= avio_tell(pb);
233 234 235
    avio_wb24(pb, 0);          // size of data part (sum of all parts below)
    avio_wb24(pb, 0);          // time stamp
    avio_wb32(pb, 0);          // reserved
236 237 238 239

    /* now data of data_size size */

    /* first event name as a string */
240
    avio_w8(pb, AMF_DATA_TYPE_STRING);
241 242 243
    put_amf_string(pb, "onMetaData"); // 12 bytes

    /* mixed array (hash) with size and string/type/data tuples */
244
    avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
245 246 247
    metadata_count_pos = avio_tell(pb);
    metadata_count = 5*!!video_enc + 5*!!audio_enc + 2; // +2 for duration and file size
    avio_wb32(pb, metadata_count);
248

249
    put_amf_string(pb, "duration");
250
    flv->duration_offset= avio_tell(pb);
251
    put_amf_double(pb, s->duration / AV_TIME_BASE); // fill in the guessed duration, it'll be corrected later if incorrect
252

253
    if(video_enc){
254
        put_amf_string(pb, "width");
255
        put_amf_double(pb, video_enc->width);
256 257

        put_amf_string(pb, "height");
258
        put_amf_double(pb, video_enc->height);
259 260

        put_amf_string(pb, "videodatarate");
261
        put_amf_double(pb, video_enc->bit_rate / 1024.0);
262 263 264

        put_amf_string(pb, "framerate");
        put_amf_double(pb, framerate);
265 266

        put_amf_string(pb, "videocodecid");
267
        put_amf_double(pb, video_enc->codec_tag);
268 269
    }

270
    if(audio_enc){
271 272 273
        put_amf_string(pb, "audiodatarate");
        put_amf_double(pb, audio_enc->bit_rate / 1024.0);

274
        put_amf_string(pb, "audiosamplerate");
275
        put_amf_double(pb, audio_enc->sample_rate);
276 277

        put_amf_string(pb, "audiosamplesize");
278
        put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_U8 ? 8 : 16);
279 280

        put_amf_string(pb, "stereo");
281
        put_amf_bool(pb, audio_enc->channels == 2);
282 283

        put_amf_string(pb, "audiocodecid");
284
        put_amf_double(pb, audio_enc->codec_tag);
285 286
    }

287
    while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
T
Tomás Touceda 已提交
288
        put_amf_string(pb, tag->key);
289
        avio_w8(pb, AMF_DATA_TYPE_STRING);
T
Tomás Touceda 已提交
290
        put_amf_string(pb, tag->value);
291
        metadata_count++;
T
Tomás Touceda 已提交
292 293
    }

294
    put_amf_string(pb, "filesize");
295
    flv->filesize_offset= avio_tell(pb);
296
    put_amf_double(pb, 0); // delayed write
297 298

    put_amf_string(pb, "");
299
    avio_w8(pb, AMF_END_OF_OBJECT);
300 301

    /* write total size of tag */
302
    data_size= avio_tell(pb) - metadata_size_pos - 10;
303 304 305 306

    avio_seek(pb, metadata_count_pos, SEEK_SET);
    avio_wb32(pb, metadata_count);

A
Anton Khirnov 已提交
307
    avio_seek(pb, metadata_size_pos, SEEK_SET);
308
    avio_wb24(pb, data_size);
309
    avio_skip(pb, data_size + 10 - 3);
310
    avio_wb32(pb, data_size + 11);
311

B
Baptiste Coudurier 已提交
312 313 314
    for (i = 0; i < s->nb_streams; i++) {
        AVCodecContext *enc = s->streams[i]->codec;
        if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264) {
315
            int64_t pos;
316
            avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
B
Baptiste Coudurier 已提交
317
                     FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
318 319 320 321
            avio_wb24(pb, 0); // size patched later
            avio_wb24(pb, 0); // ts
            avio_w8(pb, 0); // ts ext
            avio_wb24(pb, 0); // streamid
322
            pos = avio_tell(pb);
B
Baptiste Coudurier 已提交
323
            if (enc->codec_id == CODEC_ID_AAC) {
324 325 326
                avio_w8(pb, get_audio_flags(enc));
                avio_w8(pb, 0); // AAC sequence header
                avio_write(pb, enc->extradata, enc->extradata_size);
B
Baptiste Coudurier 已提交
327
            } else {
328 329 330
                avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
                avio_w8(pb, 0); // AVC sequence header
                avio_wb24(pb, 0); // composition time
B
Baptiste Coudurier 已提交
331 332
                ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
            }
333
            data_size = avio_tell(pb) - pos;
A
Anton Khirnov 已提交
334
            avio_seek(pb, -data_size - 10, SEEK_CUR);
335
            avio_wb24(pb, data_size);
336
            avio_skip(pb, data_size + 10 - 3);
337
            avio_wb32(pb, data_size + 11); // previous tag size
B
Baptiste Coudurier 已提交
338 339 340
        }
    }

341 342 343 344 345
    return 0;
}

static int flv_write_trailer(AVFormatContext *s)
{
346 347
    int64_t file_size;

348
    AVIOContext *pb = s->pb;
349
    FLVContext *flv = s->priv_data;
350 351 352 353 354
    int i;

    /* Add EOS tag */
    for (i = 0; i < s->nb_streams; i++) {
        AVCodecContext *enc = s->streams[i]->codec;
355
        FLVStreamContext *sc = s->streams[i]->priv_data;
356
        if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&
357
                enc->codec_id == CODEC_ID_H264) {
358
            put_avc_eos_tag(pb, sc->last_ts);
359 360
        }
    }
361

362
    file_size = avio_tell(pb);
363

D
Diego Biurrun 已提交
364
    /* update information */
A
Anton Khirnov 已提交
365
    avio_seek(pb, flv->duration_offset, SEEK_SET);
366
    put_amf_double(pb, flv->duration / (double)1000);
A
Anton Khirnov 已提交
367
    avio_seek(pb, flv->filesize_offset, SEEK_SET);
368 369
    put_amf_double(pb, file_size);

A
Anton Khirnov 已提交
370
    avio_seek(pb, file_size, SEEK_SET);
371 372 373
    return 0;
}

374
static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
375
{
376
    AVIOContext *pb = s->pb;
377
    AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
378
    FLVContext *flv = s->priv_data;
379
    FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data;
B
Baptiste Coudurier 已提交
380
    unsigned ts;
381
    int size= pkt->size;
382
    uint8_t *data= NULL;
383
    int flags, flags_size;
384

385
//    av_log(s, AV_LOG_DEBUG, "type:%d pts: %"PRId64" size:%d\n", enc->codec_type, timestamp, size);
386

B
Baptiste Coudurier 已提交
387 388
    if(enc->codec_id == CODEC_ID_VP6 || enc->codec_id == CODEC_ID_VP6F ||
       enc->codec_id == CODEC_ID_AAC)
389
        flags_size= 2;
B
Baptiste Coudurier 已提交
390 391
    else if(enc->codec_id == CODEC_ID_H264)
        flags_size= 5;
392 393 394
    else
        flags_size= 1;

395
    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
396
        avio_w8(pb, FLV_TAG_TYPE_VIDEO);
397

398
        flags = enc->codec_tag;
399 400 401 402 403
        if(flags == 0) {
            av_log(enc, AV_LOG_ERROR, "video codec %X not compatible with flv\n",enc->codec_id);
            return -1;
        }

404
        flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
M
Michael Niedermayer 已提交
405
    } else {
406
        assert(enc->codec_type == AVMEDIA_TYPE_AUDIO);
M
Michael Niedermayer 已提交
407
        flags = get_audio_flags(enc);
408

M
cleanup  
Michael Niedermayer 已提交
409 410
        assert(size);

411
        avio_w8(pb, FLV_TAG_TYPE_AUDIO);
M
Michael Niedermayer 已提交
412 413
    }

414
    if (enc->codec_id == CODEC_ID_H264) {
D
Diego Biurrun 已提交
415
        /* check if extradata looks like MP4 */
416 417 418 419
        if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1) {
            if (ff_avc_parse_nal_units_buf(pkt->data, &data, &size) < 0)
                return -1;
        }
B
Baptiste Coudurier 已提交
420
    }
421 422 423 424 425 426 427
    if (flv->delay == AV_NOPTS_VALUE)
        flv->delay = -pkt->dts;
    if (pkt->dts < -flv->delay) {
        av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with "
                                  "respect to DTS\n");
        return AVERROR(EINVAL);
    }
B
Baptiste Coudurier 已提交
428

429
    ts = pkt->dts + flv->delay; // add delay to force positive dts
430 431

    /* check Speex packet duration */
432
    if (enc->codec_id == CODEC_ID_SPEEX && ts - sc->last_ts > 160) {
433 434 435
        av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than "
                                  "8 frames per packet. Adobe Flash "
                                  "Player cannot handle this!\n");
436
    }
437

438 439
    if (sc->last_ts < ts)
        sc->last_ts = ts;
440

441 442 443 444 445
    avio_wb24(pb,size + flags_size);
    avio_wb24(pb,ts);
    avio_w8(pb,(ts >> 24) & 0x7F); // timestamps are 32bits _signed_
    avio_wb24(pb,flv->reserved);
    avio_w8(pb,flags);
446
    if (enc->codec_id == CODEC_ID_VP6)
447
        avio_w8(pb,0);
448
    if (enc->codec_id == CODEC_ID_VP6F)
449
        avio_w8(pb, enc->extradata_size ? enc->extradata[0] : 0);
B
Baptiste Coudurier 已提交
450
    else if (enc->codec_id == CODEC_ID_AAC)
451
        avio_w8(pb,1); // AAC raw
B
Baptiste Coudurier 已提交
452
    else if (enc->codec_id == CODEC_ID_H264) {
453 454
        avio_w8(pb,1); // AVC NALU
        avio_wb24(pb,pkt->pts - pkt->dts);
B
Baptiste Coudurier 已提交
455
    }
456

457
    avio_write(pb, data ? data : pkt->data, size);
458

459
    avio_wb32(pb,size+flags_size+11); // previous tag size
460
    flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);
461

462
    avio_flush(pb);
463 464 465

    av_free(data);

L
Luca Barbato 已提交
466
    return pb->error;
467 468
}

469
AVOutputFormat ff_flv_muxer = {
470 471 472 473 474
    .name           = "flv",
    .long_name      = NULL_IF_CONFIG_SMALL("FLV format"),
    .mime_type      = "video/x-flv",
    .extensions     = "flv",
    .priv_data_size = sizeof(FLVContext),
475
#if CONFIG_LIBMP3LAME
476
    .audio_codec    = CODEC_ID_MP3,
477
#else // CONFIG_LIBMP3LAME
478
    .audio_codec    = CODEC_ID_ADPCM_SWF,
479
#endif // CONFIG_LIBMP3LAME
480 481 482 483
    .video_codec    = CODEC_ID_FLV1,
    .write_header   = flv_write_header,
    .write_packet   = flv_write_packet,
    .write_trailer  = flv_write_trailer,
484
    .codec_tag= (const AVCodecTag* const []){flv_video_codec_ids, flv_audio_codec_ids, 0},
485
    .flags= AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
486
};