lavf.c 8.92 KB
Newer Older
1
/*****************************************************************************
Fiona Glaser's avatar
Fiona Glaser committed
2
 * lavf.c: libavformat input
3
 *****************************************************************************
Anton Mitrofanov's avatar
Anton Mitrofanov committed
4
 * Copyright (C) 2009-2020 x264 project
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * Authors: Mike Gurlitz <mike.gurlitz@gmail.com>
 *          Steven Walters <kemuri9@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
Fiona Glaser's avatar
Fiona Glaser committed
22 23 24
 *
 * This program is also available under a commercial proprietary license.
 * For more information, contact us at licensing@x264.com.
25 26
 *****************************************************************************/

27
#include "input.h"
28

29 30
#undef DECLARE_ALIGNED
#include <libavformat/avformat.h>
31 32
#include <libavutil/dict.h>
#include <libavutil/error.h>
33
#include <libavutil/mem.h>
34
#include <libavutil/pixdesc.h>
35

36 37
#define FAIL_IF_ERROR( cond, ... ) FAIL_IF_ERR( cond, "lavf", __VA_ARGS__ )

38 39 40
typedef struct
{
    AVFormatContext *lavf;
41
    AVCodecContext *lavc;
42
    AVFrame *frame;
43 44 45
    int stream_id;
    int next_frame;
    int vfr_input;
46
    cli_pic_t *first_pic;
47 48
} lavf_hnd_t;

49 50 51 52 53
/* handle the deprecated jpeg pixel formats */
static int handle_jpeg( int csp, int *fullrange )
{
    switch( csp )
    {
54 55 56
        case AV_PIX_FMT_YUVJ420P: *fullrange = 1; return AV_PIX_FMT_YUV420P;
        case AV_PIX_FMT_YUVJ422P: *fullrange = 1; return AV_PIX_FMT_YUV422P;
        case AV_PIX_FMT_YUVJ444P: *fullrange = 1; return AV_PIX_FMT_YUV444P;
57 58 59 60
        default:                               return csp;
    }
}

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
static AVCodecContext *codec_from_stream( AVStream *stream )
{
    AVCodec *codec = avcodec_find_decoder( stream->codecpar->codec_id );
    if( !codec )
        return NULL;

    AVCodecContext *c = avcodec_alloc_context3( codec );
    if( !c )
        return NULL;

    if( avcodec_parameters_to_context( c, stream->codecpar ) < 0 )
    {
        avcodec_free_context( &c );
        return NULL;
    }

    return c;
}

80
static int read_frame_internal( cli_pic_t *p_pic, lavf_hnd_t *h, int i_frame, video_info_t *info )
81 82 83 84 85 86 87
{
    if( h->first_pic && !info )
    {
        /* see if the frame we are requesting is the frame we have already read and stored.
         * if so, retrieve the pts and image data before freeing it. */
        if( !i_frame )
        {
88 89
            XCHG( cli_image_t, p_pic->img, h->first_pic->img );
            p_pic->pts = h->first_pic->pts;
90
        }
91
        lavf_input.picture_clean( h->first_pic, h );
92 93 94 95 96 97
        free( h->first_pic );
        h->first_pic = NULL;
        if( !i_frame )
            return 0;
    }

98 99 100 101
    AVPacket pkt;
    av_init_packet( &pkt );
    pkt.data = NULL;
    pkt.size = 0;
102 103 104

    while( i_frame >= h->next_frame )
    {
105
        int ret;
106

107 108 109
        while( (ret = avcodec_receive_frame( h->lavc, h->frame )) )
        {
            if( ret == AVERROR(EAGAIN) )
110
            {
111 112 113 114 115 116 117 118 119 120
                while( !(ret = av_read_frame( h->lavf, &pkt )) && pkt.stream_index != h->stream_id )
                    av_packet_unref( &pkt );

                if( ret )
                    ret = avcodec_send_packet( h->lavc, NULL );
                else
                {
                    ret = avcodec_send_packet( h->lavc, &pkt );
                    av_packet_unref( &pkt );
                }
121
            }
122 123
            else if( ret == AVERROR_EOF )
                return -1;
124

125
            if( ret )
126
            {
127 128
                x264_cli_log( "lavf", X264_LOG_WARNING, "video decoding failed on frame %d\n", h->next_frame );
                return -1;
129
            }
130
        }
131

132 133 134
        h->next_frame++;
    }

135 136
    memcpy( p_pic->img.stride, h->frame->linesize, sizeof(p_pic->img.stride) );
    memcpy( p_pic->img.plane, h->frame->data, sizeof(p_pic->img.plane) );
137
    int is_fullrange   = 0;
138 139 140
    p_pic->img.width   = h->lavc->width;
    p_pic->img.height  = h->lavc->height;
    p_pic->img.csp     = handle_jpeg( h->lavc->pix_fmt, &is_fullrange ) | X264_CSP_OTHER;
141 142

    if( info )
143
    {
144
        info->fullrange  = is_fullrange;
145 146
        info->interlaced = h->frame->interlaced_frame;
        info->tff        = h->frame->top_field_first;
147
    }
148 149 150

    if( h->vfr_input )
    {
151
        p_pic->pts = p_pic->duration = 0;
152 153
        if( h->frame->pts != AV_NOPTS_VALUE )
            p_pic->pts = h->frame->pts;
154 155
        else if( h->frame->pkt_dts != AV_NOPTS_VALUE )
            p_pic->pts = h->frame->pkt_dts; // for AVI files
156 157 158
        else if( info )
        {
            h->vfr_input = info->vfr = 0;
159
            return 0;
160 161 162 163 164 165 166 167
        }
    }

    return 0;
}

static int open_file( char *psz_filename, hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt )
{
168
    lavf_hnd_t *h = calloc( 1, sizeof(lavf_hnd_t) );
169 170 171 172 173
    if( !h )
        return -1;
    if( !strcmp( psz_filename, "-" ) )
        psz_filename = "pipe:";

174
    h->frame = av_frame_alloc();
175 176 177
    if( !h->frame )
        return -1;

178 179
    /* if resolution was passed in, place it and colorspace into options. this allows raw video support */
    AVDictionary *options = NULL;
180 181
    if( opt->resolution )
    {
182
        av_dict_set( &options, "video_size", opt->resolution, 0 );
183
        const char *csp = opt->colorspace ? opt->colorspace : av_get_pix_fmt_name( AV_PIX_FMT_YUV420P );
184
        av_dict_set( &options, "pixel_format", csp, 0 );
185 186
    }

187 188 189 190 191
    /* specify the input format. this is helpful when lavf fails to guess */
    AVInputFormat *format = NULL;
    if( opt->format )
        FAIL_IF_ERROR( !(format = av_find_input_format( opt->format )), "unknown file format: %s\n", opt->format );

192
    FAIL_IF_ERROR( avformat_open_input( &h->lavf, psz_filename, format, &options ), "could not open input file\n" );
193 194
    if( options )
        av_dict_free( &options );
195
    FAIL_IF_ERROR( avformat_find_stream_info( h->lavf, NULL ) < 0, "could not find input stream info\n" );
196 197

    int i = 0;
198
    while( i < h->lavf->nb_streams && h->lavf->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_VIDEO )
199
        i++;
200
    FAIL_IF_ERROR( i == h->lavf->nb_streams, "could not find video stream\n" );
201 202
    h->stream_id       = i;
    h->next_frame      = 0;
203 204 205 206
    h->lavc            = codec_from_stream( h->lavf->streams[i] );
    if( !h->lavc )
        return -1;

207 208
    info->fps_num      = h->lavf->streams[i]->avg_frame_rate.num;
    info->fps_den      = h->lavf->streams[i]->avg_frame_rate.den;
209 210
    info->timebase_num = h->lavf->streams[i]->time_base.num;
    info->timebase_den = h->lavf->streams[i]->time_base.den;
211 212
    /* lavf is thread unsafe as calling av_read_frame invalidates previously read AVPackets */
    info->thread_safe  = 0;
213
    h->vfr_input       = info->vfr;
214
    FAIL_IF_ERROR( avcodec_open2( h->lavc, avcodec_find_decoder( h->lavc->codec_id ), NULL ),
215
                   "could not find decoder for video stream\n" );
216 217

    /* prefetch the first frame and set/confirm flags */
218
    h->first_pic = malloc( sizeof(cli_pic_t) );
219
    FAIL_IF_ERROR( !h->first_pic || lavf_input.picture_alloc( h->first_pic, h, X264_CSP_OTHER, info->width, info->height ),
220 221
                   "malloc failed\n" );
    if( read_frame_internal( h->first_pic, h, 0, info ) )
222 223
        return -1;

224 225
    info->width      = h->lavc->width;
    info->height     = h->lavc->height;
226
    info->csp        = h->first_pic->img.csp;
227
    info->num_frames = h->lavf->streams[i]->nb_frames;
228 229 230
    info->sar_height = h->lavc->sample_aspect_ratio.den;
    info->sar_width  = h->lavc->sample_aspect_ratio.num;
    info->fullrange |= h->lavc->color_range == AVCOL_RANGE_JPEG;
231 232 233

    /* avisynth stores rgb data vertically flipped. */
    if( !strcasecmp( get_filename_extension( psz_filename ), "avs" ) &&
234
        (h->lavc->pix_fmt == AV_PIX_FMT_BGRA || h->lavc->pix_fmt == AV_PIX_FMT_BGR24) )
235 236
        info->csp |= X264_CSP_VFLIP;

237 238 239 240 241
    *p_handle = h;

    return 0;
}

242
static int picture_alloc( cli_pic_t *pic, hnd_t handle, int csp, int width, int height )
243
{
244
    if( x264_cli_pic_alloc( pic, X264_CSP_NONE, width, height ) )
245
        return -1;
246
    pic->img.csp = csp;
247
    pic->img.planes = 4;
248 249 250
    return 0;
}

251
static int read_frame( cli_pic_t *pic, hnd_t handle, int i_frame )
252
{
253
    return read_frame_internal( pic, handle, i_frame, NULL );
254 255
}

256
static void picture_clean( cli_pic_t *pic, hnd_t handle )
257
{
258
    memset( pic, 0, sizeof(cli_pic_t) );
259 260 261 262 263
}

static int close_file( hnd_t handle )
{
    lavf_hnd_t *h = handle;
264
    avcodec_free_context( &h->lavc );
265
    avformat_close_input( &h->lavf );
266
    av_frame_free( &h->frame );
267 268 269 270
    free( h );
    return 0;
}

271
const cli_input_t lavf_input = { open_file, picture_alloc, read_frame, NULL, picture_clean, close_file };