ffmpeg hls拉流超时问题

参考:
解决ffmpeg打开流各种超时问题
ffmpeg拉流长时间堵塞解决方式
ffmpeg 协议选项参数解释

问题,拉流hls报以下错误

[hls @ 000001bc59476000] Opening 'http://39.135.138.59:18890/PLTV/88888910/224/3221225644/1647845325-1-1644624937.hls.ts?ssr_hostlv1=39.134.116.2:18890&ssr_host=117.169.122.137:8080' for reading
[hls @ 000001bc59476000] Failed to open segment 1644624937 of playlist 0

在不设置回调,只指定 timeout 参数后并无效果,设置 rw_timeout 后会导致一直失败重读,设置回调后才可以真正判断超时,设置方式如下

AVDictionary* opts = NULL;
if (startWith(srcPath, "rtsp://"))
{
	// 设置rtsp拉流超时时间
	bool is_tcp = true; // 设置tcp or udp,默认一般优先tcp再尝试udp
	av_dict_set(&opts, "rtsp_transport", is_tcp ? "tcp" : "udp", 0); 
	av_dict_set(&opts, "stimeout", "10000000", 0); // 设置超时10秒
}
else
{
	// 设置udp,http超时
	av_dict_set(&opts, "timeout", "10000000", 0); // 设置超时10秒
}
// rw_timeout 网络读写操作最大等待时间,微妙
av_dict_set(&opts, "rw_timeout", "10000000", 0);

// 设置av_read_frame 超时回调
in_fmt = avformat_alloc_context();
in_fmt->interrupt_callback.callback = read_interrupt_callback;
in_fmt->interrupt_callback.opaque = this;
read_start_time = time(NULL); // 每次读流之前记录一下起始时间

if (avformat_open_input(&in_fmt, srcPath.c_str(), NULL, &opts) < 0) {
	logger.error("avformat_open_input fail");
	return;
}

回调函数

int read_interrupt_callback(void *ctx)
{
    using namespace xl::picture;

    if (!ctx) return 0;    
    Demo *d = (Demo*)ctx;
    
    uint64_t end = time(NULL);
    if (end - d->read_start_time >= 10)
    {
        return 1; // 退出阻塞
    }
    return 0; // 继续阻塞
}
posted @ 2022-03-21 16:11  jixhua  阅读(1447)  评论(6编辑  收藏  举报