ffmenc.c 11.3 KB
Newer Older
Baptiste Coudurier's avatar
Baptiste Coudurier committed
1 2
/*
 * FFM (ffserver live feed) muxer
3
 * Copyright (c) 2001 Fabrice Bellard
Baptiste Coudurier's avatar
Baptiste Coudurier committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * 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
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

22
#include "libavutil/intreadwrite.h"
23
#include "libavutil/intfloat.h"
24
#include "libavutil/avassert.h"
25
#include "libavutil/parseutils.h"
26
#include "libavutil/opt.h"
Baptiste Coudurier's avatar
Baptiste Coudurier committed
27
#include "avformat.h"
28
#include "avio_internal.h"
29
#include "internal.h"
Baptiste Coudurier's avatar
Baptiste Coudurier committed
30 31 32 33 34 35
#include "ffm.h"

static void flush_packet(AVFormatContext *s)
{
    FFMContext *ffm = s->priv_data;
    int fill_size, h;
36
    AVIOContext *pb = s->pb;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
37 38 39 40

    fill_size = ffm->packet_end - ffm->packet_ptr;
    memset(ffm->packet_ptr, 0, fill_size);

41
    av_assert1(avio_tell(pb) % ffm->packet_size == 0);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
42 43

    /* put header */
44 45 46
    avio_wb16(pb, PACKET_ID);
    avio_wb16(pb, fill_size);
    avio_wb64(pb, ffm->dts);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
47 48 49
    h = ffm->frame_offset;
    if (ffm->first_packet)
        h |= 0x8000;
50 51
    avio_wb16(pb, h);
    avio_write(pb, ffm->packet, ffm->packet_end - ffm->packet);
52
    avio_flush(pb);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
53 54 55 56 57 58 59 60 61 62

    /* prepare next packet */
    ffm->frame_offset = 0; /* no key frame */
    ffm->packet_ptr = ffm->packet;
    ffm->first_packet = 0;
}

/* 'first' is true if first data of a frame */
static void ffm_write_data(AVFormatContext *s,
                           const uint8_t *buf, int size,
Baptiste Coudurier's avatar
Baptiste Coudurier committed
63
                           int64_t dts, int header)
Baptiste Coudurier's avatar
Baptiste Coudurier committed
64 65 66 67
{
    FFMContext *ffm = s->priv_data;
    int len;

68
    if (header && ffm->frame_offset == 0) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
69
        ffm->frame_offset = ffm->packet_ptr - ffm->packet + FFM_HEADER_SIZE;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
70
        ffm->dts = dts;
71
    }
Baptiste Coudurier's avatar
Baptiste Coudurier committed
72 73 74 75 76 77 78 79 80 81 82

    /* write as many packets as needed */
    while (size > 0) {
        len = ffm->packet_end - ffm->packet_ptr;
        if (len > size)
            len = size;
        memcpy(ffm->packet_ptr, buf, len);

        ffm->packet_ptr += len;
        buf += len;
        size -= len;
83
        if (ffm->packet_ptr >= ffm->packet_end)
Baptiste Coudurier's avatar
Baptiste Coudurier committed
84 85 86 87
            flush_packet(s);
    }
}

88 89 90 91 92 93 94 95 96 97
static void write_header_chunk(AVIOContext *pb, AVIOContext *dpb, unsigned id)
{
    uint8_t *dyn_buf;
    int dyn_size= avio_close_dyn_buf(dpb, &dyn_buf);
    avio_wb32(pb, id);
    avio_wb32(pb, dyn_size);
    avio_write(pb, dyn_buf, dyn_size);
    av_free(dyn_buf);
}

98
static int ffm_write_header_codec_ctx(AVIOContext *pb, AVCodecParameters *ctxpar, unsigned tag, int type)
99 100 101 102
{
    AVIOContext *tmp;
    char *buf = NULL;
    int ret, need_coma = 0;
103
    AVCodecContext *ctx = NULL;
104 105 106 107 108 109 110

#define SKIP_DEFAULTS   AV_OPT_SERIALIZE_SKIP_DEFAULTS
#define OPT_FLAGS_EXACT AV_OPT_SERIALIZE_OPT_FLAGS_EXACT
#define ENC             AV_OPT_FLAG_ENCODING_PARAM

    if (avio_open_dyn_buf(&tmp) < 0)
        return AVERROR(ENOMEM);
111 112 113 114 115 116 117 118 119 120

    // AVCodecParameters does not suport AVOptions, we thus must copy it over to a context that does
    // otherwise it could be used directly and this would be much simpler
    ctx = avcodec_alloc_context3(NULL);
    if (!ctx) {
        ret = AVERROR(ENOMEM);
        goto fail;
    }
    avcodec_parameters_to_context(ctx, ctxpar);

121 122 123 124
    if ((ret = av_opt_serialize(ctx, ENC | type, SKIP_DEFAULTS, &buf, '=', ',')) < 0)
        goto fail;
    if (buf && strlen(buf)) {
        avio_write(tmp, buf, strlen(buf));
125
        av_freep(&buf);
126 127 128 129 130 131 132 133 134
        need_coma = 1;
    }
    if ((ret = av_opt_serialize(ctx, 0, SKIP_DEFAULTS | OPT_FLAGS_EXACT, &buf, '=', ',')) < 0)
        goto fail;
    if (buf && strlen(buf)) {
        if (need_coma)
            avio_w8(tmp, ',');
        avio_write(tmp, buf, strlen(buf));
    }
135
    av_freep(&buf);
136 137
    avio_w8(tmp, 0);
    write_header_chunk(pb, tmp, tag);
138
    avcodec_free_context(&ctx);
139 140 141
    return 0;
  fail:
    av_free(buf);
142
    ffio_free_dyn_buf(&tmp);
143
    avcodec_free_context(&ctx);
144 145 146 147 148 149 150
    return ret;

#undef SKIP_DEFAULTS
#undef OPT_FLAGS_EXACT
#undef ENC
}

151
static int ffm_write_recommended_config(AVIOContext *pb, AVCodecParameters *codecpar, unsigned tag,
152 153 154
                                        const char *configuration)
{
    int ret;
155
    const AVCodec *enc = avcodec_find_encoder(codecpar->codec_id);
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    AVIOContext *tmp;
    AVDictionaryEntry *t = NULL;
    AVDictionary *all = NULL, *comm = NULL, *prv = NULL;
    char *buf = NULL;

    if (!enc || !enc->priv_class || !enc->priv_data_size) {
        /* codec is not known/has no private options, so save everything as common options */
        if (avio_open_dyn_buf(&tmp) < 0)
            return AVERROR(ENOMEM);
        avio_put_str(tmp, configuration);
        write_header_chunk(pb, tmp, tag);
        return 0;
    }

    if ((ret = av_dict_parse_string(&all, configuration, "=", ",", 0)) < 0)
        return ret;

    while ((t = av_dict_get(all, "", t, AV_DICT_IGNORE_SUFFIX))) {
        if (av_opt_find((void *)&enc->priv_class, t->key, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)) {
            if ((ret = av_dict_set(&prv, t->key, t->value, 0)) < 0)
                goto fail;
        } else if ((ret = av_dict_set(&comm, t->key, t->value, 0)) < 0)
            goto fail;
    }

    if (comm) {
        if ((ret = av_dict_get_string(comm, &buf, '=', ',')) < 0 ||
            (ret = avio_open_dyn_buf(&tmp)) < 0)
            goto fail;
        avio_put_str(tmp, buf);
        av_freep(&buf);
        write_header_chunk(pb, tmp, tag);
    }
    if (prv) {
        if ((ret = av_dict_get_string(prv, &buf, '=', ',')) < 0 ||
            (ret = avio_open_dyn_buf(&tmp)) < 0)
            goto fail;
        avio_put_str(tmp, buf);
        write_header_chunk(pb, tmp, MKBETAG('C', 'P', 'R', 'V'));
    }

  fail:
    av_free(buf);
    av_dict_free(&all);
    av_dict_free(&comm);
    av_dict_free(&prv);
    return ret;
}

Baptiste Coudurier's avatar
Baptiste Coudurier committed
205 206 207 208
static int ffm_write_header(AVFormatContext *s)
{
    FFMContext *ffm = s->priv_data;
    AVStream *st;
209
    AVIOContext *pb = s->pb;
210
    AVCodecParameters *codecpar;
211
    int bit_rate, i, ret;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
212

213 214
    if ((ret = ff_parse_creation_time_metadata(s, &ffm->start_time, 0)) < 0)
        return ret;
215

Baptiste Coudurier's avatar
Baptiste Coudurier committed
216 217 218
    ffm->packet_size = FFM_PACKET_SIZE;

    /* header */
219
    avio_wl32(pb, MKTAG('F', 'F', 'M', '2'));
220 221
    avio_wb32(pb, ffm->packet_size);
    avio_wb64(pb, 0); /* current write position */
Baptiste Coudurier's avatar
Baptiste Coudurier committed
222

223 224 225
    if(avio_open_dyn_buf(&pb) < 0)
        return AVERROR(ENOMEM);

226
    avio_wb32(pb, s->nb_streams);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
227 228 229
    bit_rate = 0;
    for(i=0;i<s->nb_streams;i++) {
        st = s->streams[i];
230
        bit_rate += st->codecpar->bit_rate;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
231
    }
232
    avio_wb32(pb, bit_rate);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
233

234 235
    write_header_chunk(s->pb, pb, MKBETAG('M', 'A', 'I', 'N'));

Baptiste Coudurier's avatar
Baptiste Coudurier committed
236 237
    /* list of streams */
    for(i=0;i<s->nb_streams;i++) {
238
        int flags = 0;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
239
        st = s->streams[i];
240
        avpriv_set_pts_info(st, 64, 1, 1000000);
241 242
        if(avio_open_dyn_buf(&pb) < 0)
            return AVERROR(ENOMEM);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
243

244
        codecpar = st->codecpar;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
245
        /* generic info */
246 247 248
        avio_wb32(pb, codecpar->codec_id);
        avio_w8(pb, codecpar->codec_type);
        avio_wb32(pb, codecpar->bit_rate);
249 250 251 252 253 254 255 256 257 258
        if (codecpar->extradata_size)
            flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

        // If the user is not providing us with a configuration we have to fill it in as we cannot access the encoder
        if (!st->recommended_encoder_configuration) {
            if (s->flags & AVFMT_FLAG_BITEXACT)
                flags |= AV_CODEC_FLAG_BITEXACT;
        }

        avio_wb32(pb, flags);
259 260 261 262 263
        avio_wb32(pb, 0); // flags2
        avio_wb32(pb, 0); // debug
        if (codecpar->extradata_size) {
            avio_wb32(pb, codecpar->extradata_size);
            avio_write(pb, codecpar->extradata, codecpar->extradata_size);
264 265
        }
        write_header_chunk(s->pb, pb, MKBETAG('C', 'O', 'M', 'M'));
Baptiste Coudurier's avatar
Baptiste Coudurier committed
266
        /* specific info */
267
        switch(codecpar->codec_type) {
268
        case AVMEDIA_TYPE_VIDEO:
269 270 271
            if (st->recommended_encoder_configuration) {
                av_log(NULL, AV_LOG_DEBUG, "writing recommended configuration: %s\n",
                       st->recommended_encoder_configuration);
272
                if ((ret = ffm_write_recommended_config(s->pb, codecpar, MKBETAG('S', '2', 'V', 'I'),
273 274
                                                        st->recommended_encoder_configuration)) < 0)
                return ret;
275
            } else if ((ret = ffm_write_header_codec_ctx(s->pb, codecpar, MKBETAG('S', '2', 'V', 'I'), AV_OPT_FLAG_VIDEO_PARAM)) < 0)
276
                return ret;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
277
            break;
278
        case AVMEDIA_TYPE_AUDIO:
279 280 281
            if (st->recommended_encoder_configuration) {
                av_log(NULL, AV_LOG_DEBUG, "writing recommended configuration: %s\n",
                       st->recommended_encoder_configuration);
282
                if ((ret = ffm_write_recommended_config(s->pb, codecpar, MKBETAG('S', '2', 'A', 'U'),
283 284
                                                        st->recommended_encoder_configuration)) < 0)
                return ret;
285
            } else if ((ret = ffm_write_header_codec_ctx(s->pb, codecpar, MKBETAG('S', '2', 'A', 'U'), AV_OPT_FLAG_AUDIO_PARAM)) < 0)
286
                return ret;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
287 288 289 290 291
            break;
        default:
            return -1;
        }
    }
292 293 294
    pb = s->pb;

    avio_wb64(pb, 0); // end of header
Baptiste Coudurier's avatar
Baptiste Coudurier committed
295 296

    /* flush until end of block reached */
297
    while ((avio_tell(pb) % ffm->packet_size) != 0)
298
        avio_w8(pb, 0);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
299

300
    avio_flush(pb);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
301 302 303 304

    /* init packet mux */
    ffm->packet_ptr = ffm->packet;
    ffm->packet_end = ffm->packet + ffm->packet_size - FFM_HEADER_SIZE;
305
    av_assert0(ffm->packet_end >= ffm->packet);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
306
    ffm->frame_offset = 0;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
307
    ffm->dts = 0;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
308 309 310 311 312 313 314
    ffm->first_packet = 1;

    return 0;
}

static int ffm_write_packet(AVFormatContext *s, AVPacket *pkt)
{
315
    FFMContext *ffm = s->priv_data;
316
    int64_t dts;
Stefan Gehrer's avatar
Stefan Gehrer committed
317
    uint8_t header[FRAME_HEADER_SIZE+4];
318
    int header_size = FRAME_HEADER_SIZE;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
319

320
    dts = ffm->start_time + pkt->dts;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
321 322 323
    /* packet size & key_frame */
    header[0] = pkt->stream_index;
    header[1] = 0;
324
    if (pkt->flags & AV_PKT_FLAG_KEY)
Baptiste Coudurier's avatar
Baptiste Coudurier committed
325 326 327
        header[1] |= FLAG_KEY_FRAME;
    AV_WB24(header+2, pkt->size);
    AV_WB24(header+5, pkt->duration);
328
    AV_WB64(header+8, ffm->start_time + pkt->pts);
329 330 331 332 333
    if (pkt->pts != pkt->dts) {
        header[1] |= FLAG_DTS;
        AV_WB32(header+16, pkt->pts - pkt->dts);
        header_size += 4;
    }
334 335
    ffm_write_data(s, header, header_size, dts, 1);
    ffm_write_data(s, pkt->data, pkt->size, dts, 0);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

    return 0;
}

static int ffm_write_trailer(AVFormatContext *s)
{
    FFMContext *ffm = s->priv_data;

    /* flush packets */
    if (ffm->packet_ptr > ffm->packet)
        flush_packet(s);

    return 0;
}

351
AVOutputFormat ff_ffm_muxer = {
352
    .name              = "ffm",
353
    .long_name         = NULL_IF_CONFIG_SMALL("FFM (FFserver live feed)"),
354 355
    .extensions        = "ffm",
    .priv_data_size    = sizeof(FFMContext),
356 357
    .audio_codec       = AV_CODEC_ID_MP2,
    .video_codec       = AV_CODEC_ID_MPEG1VIDEO,
358 359 360
    .write_header      = ffm_write_header,
    .write_packet      = ffm_write_packet,
    .write_trailer     = ffm_write_trailer,
361
    .flags             = AVFMT_TS_NEGATIVE,
Baptiste Coudurier's avatar
Baptiste Coudurier committed
362
};