日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

FFmpeg實戰之利用ffplay實現自定義輸入流播放_C 語言

作者:CodeOfCC ? 更新時間: 2023-01-17 編程語言

前言

使用ffplay播放視頻,有時我們只能獲取到byte數據,比如Windows的嵌入資源只能拿到在內存中的視頻文件數據,或者是自定義協議網絡傳輸的視頻,這個時候我們就需要實現一個流數據輸入接口來進行播放了,ffmpeg的AVIOContext就支持這一功能,我們只需要對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;
}

總結

以上就是今天要講的內容,之所以去實現這樣的功能是因為筆者曾經工作中,遇到過相關使用場景,在程序啟動時播放mp4嵌入資源,將其讀取出來保存文件在播放顯然不是很好的方案,而且ffmpeg本身支持自定義輸入流,所以很容易就將此功能添加到ffplay上了。總的來說,這個功能有一定的使用場景而且實現也不算復雜。

原文鏈接:https://blog.csdn.net/u013113678/article/details/125363296

欄目分類
最近更新