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、定义接口
////// 开始播放 /// /// 播放器对象 /// 自定义输入流,读取数据时的回调 /// 自定义输入流,定位时的回调 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;
}