FFmpeg怎么利用ffplay实现自定义输入流播放

2023-06-02,

本篇内容主要讲解“FFmpeg怎么利用ffplay实现自定义输入流播放”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“FFmpeg怎么利用ffplay实现自定义输入流播放”吧!

    一、如何使用AVIOContext

    avio是ffmpeg自定义输入流的对象,它是AVformatContext的一个字段,我只需要创建avio对象并实现其回调方法,然后给AVformatContext.pb赋值即可。

    1、定义回调方法

    以文件流为例(省略了打开文件和获取文件长度的操作)

    FILE* file;
    static int avio_read(ACPlay play, uint8_t* buf, int bufsize)
    {
        return fread(buf, 1, bufsize, file);
    }
    static int64_t avio_seek(ACPlay play, int64_t offset, int whence)
    {
        switch (whence)
        {
        case AVSEEK_SIZE:
            return fileSize;
            break;
        case SEEK_CUR:
            fseek(file, offset, whence);
            break;
        case SEEK_SET:
            fseek(file, offset, whence);
            break;
        case SEEK_END:
            fseek(file, offset, whence);
            break;
        default:
            break;
        }
        return  ftell(test3file);
    }

    2、关联AVFormatContext

    AVFormatContext* ic = NULL;
    AVIOContext* avio = avio_alloc_context((unsigned char*)av_malloc(1024 * 1024), 1024 * 1024, 0, s, avio_read, NULL, avio_seek);
    if (avio)
    {
        ic->pb = avio;
        ic->flags = AVFMT_FLAG_CUSTOM_IO;
    }
    avformat_open_input(&ic, "", NULL, NULL);

    3、销毁资源

    if (ic->avio)
    {
        if (ic->avio->buffer)
        {
            av_free(is->avio->buffer);
        }
        avio_context_free(&is->avio);
        ic->avio = NULL;
    }

    二、ffplay中使用AVIOContext

    1、添加字段

    在VideoState中添加如下字段

    AVIOContext* avio;

    2、定义接口

    /// <summary>
    /// 开始播放
    /// </summary>
    /// <param name="play">播放器对象</param>
    /// <param name="read">自定义输入流,读取数据时的回调</param>
    /// <param name="seek">自定义输入流,定位时的回调</param>
    void ac_play_startViaCustomStream(ACPlay play, ACPlayCustomPacketReadCallback read, ACPlayCustomPacketStreamSeekCallback seek);
    {
        VideoState* s = (VideoState*)play;
        if(read)
        s->avio = avio_alloc_context((unsigned char*)av_malloc(1024 * 1024), 1024 * 1024, 0, s, read, NULL, seek);
        stream_open(s, "", NULL);
    }

    3、关联AVFormatContext

    在read_thread中avformat_open_input的上一行添加如下代码:

    if (is->avio)
    {
        ic->pb = is->avio;
        ic->flags = AVFMT_FLAG_CUSTOM_IO;
    }

    4、销毁资源

    在stream_close中添加如下代码

    if (ic->avio)
    {
        if (ic->avio->buffer)
        {
            av_free(is->avio->buffer);
        }
        avio_context_free(&is->avio);
        ic->avio = NULL;
    }

    到此,相信大家对“FFmpeg怎么利用ffplay实现自定义输入流播放”有了更深的了解,不妨来实际操作一番吧!这里是本站网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

    《FFmpeg怎么利用ffplay实现自定义输入流播放.doc》

    下载本文的Word格式文档,以方便收藏与打印。