buffersrc.c 15.4 KB
Newer Older
1 2 3
/*
 * Copyright (c) 2008 Vitor Sessak
 *
4
 * This file is part of Libav.
5
 *
6
 * Libav is free software; you can redistribute it and/or
7 8 9 10
 * 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.
 *
11
 * Libav is distributed in the hope that it will be useful,
12 13 14 15 16
 * 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
17
 * License along with Libav; if not, write to the Free Software
18 19 20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

Stefano Sabatini's avatar
Stefano Sabatini committed
21 22 23 24 25
/**
 * @file
 * memory buffer source filter
 */

26 27
#include <float.h>

28 29 30
#include "libavutil/channel_layout.h"
#include "libavutil/common.h"
#include "libavutil/fifo.h"
31
#include "libavutil/frame.h"
32
#include "libavutil/imgutils.h"
33
#include "libavutil/internal.h"
34 35
#include "libavutil/opt.h"
#include "libavutil/samplefmt.h"
36
#include "audio.h"
37
#include "avfilter.h"
38
#include "buffersrc.h"
39
#include "formats.h"
40
#include "internal.h"
41
#include "video.h"
42

43
typedef struct BufferSourceContext {
44
    const AVClass    *class;
45
    AVFifoBuffer     *fifo;
46 47 48
    AVRational        time_base;     ///< time_base to set in the output link

    /* video only */
49
    int               h, w;
50
    enum AVPixelFormat  pix_fmt;
51
    char               *pix_fmt_str;
52
    AVRational        pixel_aspect;
53 54 55 56 57 58 59 60

    /* audio only */
    int sample_rate;
    enum AVSampleFormat sample_fmt;
    char               *sample_fmt_str;
    uint64_t channel_layout;
    char    *channel_layout_str;

61
    int eof;
62 63
} BufferSourceContext;

64
#define CHECK_VIDEO_PARAM_CHANGE(s, c, width, height, format)\
65 66 67 68 69
    if (c->w != width || c->h != height || c->pix_fmt != format) {\
        av_log(s, AV_LOG_ERROR, "Changing frame properties on the fly is not supported.\n");\
        return AVERROR(EINVAL);\
    }

70 71 72 73 74 75 76
#define CHECK_AUDIO_PARAM_CHANGE(s, c, srate, ch_layout, format)\
    if (c->sample_fmt != format || c->sample_rate != srate ||\
        c->channel_layout != ch_layout) {\
        av_log(s, AV_LOG_ERROR, "Changing frame properties on the fly is not supported.\n");\
        return AVERROR(EINVAL);\
    }

77
int attribute_align_arg av_buffersrc_write_frame(AVFilterContext *ctx, const AVFrame *frame)
78
{
79 80 81 82 83 84 85 86 87 88 89 90 91
    AVFrame *copy;
    int ret = 0;

    if (!(copy = av_frame_alloc()))
        return AVERROR(ENOMEM);
    ret = av_frame_ref(copy, frame);
    if (ret >= 0)
        ret = av_buffersrc_add_frame(ctx, copy);

    av_frame_free(&copy);
    return ret;
}

92 93
int attribute_align_arg av_buffersrc_add_frame(AVFilterContext *ctx,
                                               AVFrame *frame)
94 95 96
{
    BufferSourceContext *s = ctx->priv;
    AVFrame *copy;
97
    int refcounted, ret;
98

99
    if (!frame) {
100
        s->eof = 1;
101
        return 0;
102
    } else if (s->eof)
103 104
        return AVERROR(EINVAL);

105 106
    refcounted = !!frame->buf[0];

107
    switch (ctx->outputs[0]->type) {
108
    case AVMEDIA_TYPE_VIDEO:
109
        CHECK_VIDEO_PARAM_CHANGE(ctx, s, frame->width, frame->height,
110 111 112
                                 frame->format);
        break;
    case AVMEDIA_TYPE_AUDIO:
113
        CHECK_AUDIO_PARAM_CHANGE(ctx, s, frame->sample_rate, frame->channel_layout,
114 115 116 117 118
                                 frame->format);
        break;
    default:
        return AVERROR(EINVAL);
    }
119

120 121 122 123 124 125 126
    if (!av_fifo_space(s->fifo) &&
        (ret = av_fifo_realloc2(s->fifo, av_fifo_size(s->fifo) +
                                         sizeof(copy))) < 0)
        return ret;

    if (!(copy = av_frame_alloc()))
        return AVERROR(ENOMEM);
127 128 129 130 131 132 133 134 135 136

    if (refcounted) {
        av_frame_move_ref(copy, frame);
    } else {
        ret = av_frame_ref(copy, frame);
        if (ret < 0) {
            av_frame_free(&copy);
            return ret;
        }
    }
137

138
    if ((ret = av_fifo_generic_write(s->fifo, &copy, sizeof(copy), NULL)) < 0) {
139 140
        if (refcounted)
            av_frame_move_ref(frame, copy);
141
        av_frame_free(&copy);
142 143
        return ret;
    }
144 145 146 147

    return 0;
}

148
#if FF_API_AVFILTERBUFFER
149
FF_DISABLE_DEPRECATION_WARNINGS
150
static void compat_free_buffer(void *opaque, uint8_t *data)
151
{
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    AVFilterBufferRef *buf = opaque;
    avfilter_unref_buffer(buf);
}

static void compat_unref_buffer(void *opaque, uint8_t *data)
{
    AVBufferRef *buf = opaque;
    av_buffer_unref(&buf);
}

int av_buffersrc_buffer(AVFilterContext *ctx, AVFilterBufferRef *buf)
{
    BufferSourceContext *s = ctx->priv;
    AVFrame *frame = NULL;
    AVBufferRef *dummy_buf = NULL;
    int ret = 0, planes, i;
168

169
    if (!buf) {
170
        s->eof = 1;
171
        return 0;
172
    } else if (s->eof)
173 174
        return AVERROR(EINVAL);

175 176 177
    frame = av_frame_alloc();
    if (!frame)
        return AVERROR(ENOMEM);
178

179 180 181 182
    dummy_buf = av_buffer_create(NULL, 0, compat_free_buffer, buf, 0);
    if (!dummy_buf) {
        ret = AVERROR(ENOMEM);
        goto fail;
183
    }
184

185 186
    if ((ret = avfilter_copy_buf_props(frame, buf)) < 0)
        goto fail;
187

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
#define WRAP_PLANE(ref_out, data, data_size)                            \
do {                                                                    \
    AVBufferRef *dummy_ref = av_buffer_ref(dummy_buf);                  \
    if (!dummy_ref) {                                                   \
        ret = AVERROR(ENOMEM);                                          \
        goto fail;                                                      \
    }                                                                   \
    ref_out = av_buffer_create(data, data_size, compat_unref_buffer,    \
                               dummy_ref, 0);                           \
    if (!ref_out) {                                                     \
        av_frame_unref(frame);                                          \
        ret = AVERROR(ENOMEM);                                          \
        goto fail;                                                      \
    }                                                                   \
} while (0)

    if (ctx->outputs[0]->type  == AVMEDIA_TYPE_VIDEO) {
        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);

207 208
        planes = av_pix_fmt_count_planes(frame->format);
        if (!desc || planes <= 0) {
209 210 211 212 213
            ret = AVERROR(EINVAL);
            goto fail;
        }

        for (i = 0; i < planes; i++) {
Anton Khirnov's avatar
Anton Khirnov committed
214
            int v_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
215
            int plane_size = (frame->height >> v_shift) * frame->linesize[i];
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

            WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);
        }
    } else {
        int planar = av_sample_fmt_is_planar(frame->format);
        int channels = av_get_channel_layout_nb_channels(frame->channel_layout);

        planes = planar ? channels : 1;

        if (planes > FF_ARRAY_ELEMS(frame->buf)) {
            frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);
            frame->extended_buf = av_mallocz(sizeof(*frame->extended_buf) *
                                             frame->nb_extended_buf);
            if (!frame->extended_buf) {
                ret = AVERROR(ENOMEM);
                goto fail;
            }
        }

        for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)
            WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);

        for (i = 0; i < planes - FF_ARRAY_ELEMS(frame->buf); i++)
            WRAP_PLANE(frame->extended_buf[i],
                       frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],
                       frame->linesize[0]);
    }

    ret = av_buffersrc_add_frame(ctx, frame);

fail:
    av_buffer_unref(&dummy_buf);
    av_frame_free(&frame);

    return ret;
251
}
252
FF_ENABLE_DEPRECATION_WARNINGS
253
#endif
254

255
static av_cold int init_video(AVFilterContext *ctx)
256 257
{
    BufferSourceContext *c = ctx->priv;
258 259 260

    if (!c->pix_fmt_str || !c->w || !c->h || av_q2d(c->time_base) <= 0) {
        av_log(ctx, AV_LOG_ERROR, "Invalid parameters provided.\n");
261 262
        return AVERROR(EINVAL);
    }
263 264

    if ((c->pix_fmt = av_get_pix_fmt(c->pix_fmt_str)) == AV_PIX_FMT_NONE) {
265
        char *tail;
266
        c->pix_fmt = strtol(c->pix_fmt_str, &tail, 10);
267
        if (*tail || c->pix_fmt < 0 || !av_pix_fmt_desc_get(c->pix_fmt)) {
268
            av_log(ctx, AV_LOG_ERROR, "Invalid pixel format string '%s'\n", c->pix_fmt_str);
269 270 271
            return AVERROR(EINVAL);
        }
    }
272

273
    if (!(c->fifo = av_fifo_alloc(sizeof(AVFrame*))))
274 275
        return AVERROR(ENOMEM);

276
    av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d pixfmt:%s\n", c->w, c->h, av_get_pix_fmt_name(c->pix_fmt));
277
    return 0;
278 279
}

280 281
#define OFFSET(x) offsetof(BufferSourceContext, x)
#define A AV_OPT_FLAG_AUDIO_PARAM
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
#define V AV_OPT_FLAG_VIDEO_PARAM

static const AVOption video_options[] = {
    { "width",         NULL,                     OFFSET(w),                AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
    { "height",        NULL,                     OFFSET(h),                AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
    { "pix_fmt",       NULL,                     OFFSET(pix_fmt_str),      AV_OPT_TYPE_STRING,                    .flags = V },
#if FF_API_OLD_FILTER_OPTS
    /* those 4 are for compatibility with the old option passing system where each filter
     * did its own parsing */
    { "time_base_num", "deprecated, do not use", OFFSET(time_base.num),    AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
    { "time_base_den", "deprecated, do not use", OFFSET(time_base.den),    AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
    { "sar_num",       "deprecated, do not use", OFFSET(pixel_aspect.num), AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
    { "sar_den",       "deprecated, do not use", OFFSET(pixel_aspect.den), AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
#endif
    { "sar",           "sample aspect ratio",    OFFSET(pixel_aspect),     AV_OPT_TYPE_RATIONAL, { .dbl = 1 }, 0, DBL_MAX, V },
    { "time_base",     NULL,                     OFFSET(time_base),        AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, DBL_MAX, V },
    { NULL },
};

static const AVClass buffer_class = {
    .class_name = "buffer source",
    .item_name  = av_default_item_name,
    .option     = video_options,
    .version    = LIBAVUTIL_VERSION_INT,
};

308
static const AVOption audio_options[] = {
309
    { "time_base",      NULL, OFFSET(time_base),           AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, INT_MAX, A },
310
    { "sample_rate",    NULL, OFFSET(sample_rate),         AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, A },
311 312 313 314 315 316 317 318 319 320 321 322
    { "sample_fmt",     NULL, OFFSET(sample_fmt_str),      AV_OPT_TYPE_STRING,             .flags = A },
    { "channel_layout", NULL, OFFSET(channel_layout_str),  AV_OPT_TYPE_STRING,             .flags = A },
    { NULL },
};

static const AVClass abuffer_class = {
    .class_name = "abuffer source",
    .item_name  = av_default_item_name,
    .option     = audio_options,
    .version    = LIBAVUTIL_VERSION_INT,
};

323
static av_cold int init_audio(AVFilterContext *ctx)
324 325 326 327 328 329 330 331
{
    BufferSourceContext *s = ctx->priv;
    int ret = 0;

    s->sample_fmt = av_get_sample_fmt(s->sample_fmt_str);
    if (s->sample_fmt == AV_SAMPLE_FMT_NONE) {
        av_log(ctx, AV_LOG_ERROR, "Invalid sample format %s.\n",
               s->sample_fmt_str);
332
        return AVERROR(EINVAL);
333 334 335 336 337 338
    }

    s->channel_layout = av_get_channel_layout(s->channel_layout_str);
    if (!s->channel_layout) {
        av_log(ctx, AV_LOG_ERROR, "Invalid channel layout %s.\n",
               s->channel_layout_str);
339
        return AVERROR(EINVAL);
340 341
    }

342 343
    if (!(s->fifo = av_fifo_alloc(sizeof(AVFrame*))))
        return AVERROR(ENOMEM);
344 345 346 347 348 349 350 351 352 353 354

    if (!s->time_base.num)
        s->time_base = (AVRational){1, s->sample_rate};

    av_log(ctx, AV_LOG_VERBOSE, "tb:%d/%d samplefmt:%s samplerate: %d "
           "ch layout:%s\n", s->time_base.num, s->time_base.den, s->sample_fmt_str,
           s->sample_rate, s->channel_layout_str);

    return ret;
}

355 356 357
static av_cold void uninit(AVFilterContext *ctx)
{
    BufferSourceContext *s = ctx->priv;
358
    while (s->fifo && av_fifo_size(s->fifo)) {
359 360 361
        AVFrame *frame;
        av_fifo_generic_read(s->fifo, &frame, sizeof(frame), NULL);
        av_frame_free(&frame);
362 363 364
    }
    av_fifo_free(s->fifo);
    s->fifo = NULL;
365 366
}

367 368 369
static int query_formats(AVFilterContext *ctx)
{
    BufferSourceContext *c = ctx->priv;
370 371 372 373 374 375
    AVFilterChannelLayouts *channel_layouts = NULL;
    AVFilterFormats *formats = NULL;
    AVFilterFormats *samplerates = NULL;

    switch (ctx->outputs[0]->type) {
    case AVMEDIA_TYPE_VIDEO:
376 377
        ff_add_format(&formats, c->pix_fmt);
        ff_set_common_formats(ctx, formats);
378 379
        break;
    case AVMEDIA_TYPE_AUDIO:
380 381
        ff_add_format(&formats,           c->sample_fmt);
        ff_set_common_formats(ctx, formats);
382

383
        ff_add_format(&samplerates,       c->sample_rate);
384 385 386 387 388 389 390 391
        ff_set_common_samplerates(ctx, samplerates);

        ff_add_channel_layout(&channel_layouts, c->channel_layout);
        ff_set_common_channel_layouts(ctx, channel_layouts);
        break;
    default:
        return AVERROR(EINVAL);
    }
392 393 394 395 396 397 398 399

    return 0;
}

static int config_props(AVFilterLink *link)
{
    BufferSourceContext *c = link->src->priv;

400 401 402 403 404 405 406 407 408 409 410 411 412
    switch (link->type) {
    case AVMEDIA_TYPE_VIDEO:
        link->w = c->w;
        link->h = c->h;
        link->sample_aspect_ratio = c->pixel_aspect;
        break;
    case AVMEDIA_TYPE_AUDIO:
        link->channel_layout = c->channel_layout;
        link->sample_rate    = c->sample_rate;
        break;
    default:
        return AVERROR(EINVAL);
    }
413

414
    link->time_base = c->time_base;
415 416 417 418 419 420
    return 0;
}

static int request_frame(AVFilterLink *link)
{
    BufferSourceContext *c = link->src->priv;
421
    AVFrame *frame;
422
    int ret = 0;
423

424
    if (!av_fifo_size(c->fifo)) {
425 426
        if (c->eof)
            return AVERROR_EOF;
427
        return AVERROR(EAGAIN);
428
    }
429
    av_fifo_generic_read(c->fifo, &frame, sizeof(frame), NULL);
430

431
    ff_filter_frame(link, frame);
432

433
    return ret;
434 435 436 437 438
}

static int poll_frame(AVFilterLink *link)
{
    BufferSourceContext *c = link->src->priv;
439 440 441
    int size = av_fifo_size(c->fifo);
    if (!size && c->eof)
        return AVERROR_EOF;
442
    return size/sizeof(AVFrame*);
443 444
}

445 446 447 448 449 450 451 452 453 454 455
static const AVFilterPad avfilter_vsrc_buffer_outputs[] = {
    {
        .name          = "default",
        .type          = AVMEDIA_TYPE_VIDEO,
        .request_frame = request_frame,
        .poll_frame    = poll_frame,
        .config_props  = config_props,
    },
    { NULL }
};

456
AVFilter ff_vsrc_buffer = {
457
    .name      = "buffer",
458
    .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them accessible to the filterchain."),
459
    .priv_size = sizeof(BufferSourceContext),
460
    .priv_class = &buffer_class,
461 462
    .query_formats = query_formats,

463
    .init      = init_video,
464
    .uninit    = uninit,
465

466
    .inputs    = NULL,
467 468 469 470 471 472 473 474 475 476 477 478
    .outputs   = avfilter_vsrc_buffer_outputs,
};

static const AVFilterPad avfilter_asrc_abuffer_outputs[] = {
    {
        .name          = "default",
        .type          = AVMEDIA_TYPE_AUDIO,
        .request_frame = request_frame,
        .poll_frame    = poll_frame,
        .config_props  = config_props,
    },
    { NULL }
479
};
480

481
AVFilter ff_asrc_abuffer = {
482 483 484
    .name          = "abuffer",
    .description   = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them accessible to the filterchain."),
    .priv_size     = sizeof(BufferSourceContext),
485
    .priv_class    = &abuffer_class,
486 487 488 489 490
    .query_formats = query_formats,

    .init      = init_audio,
    .uninit    = uninit,

491
    .inputs    = NULL,
492
    .outputs   = avfilter_asrc_abuffer_outputs,
493
};