如何在libavformat代码中实现连接被peer重置时自动重连?
在libavformat中实现HTTPS流自动重连功能
我用以下C++代码通过HTTPS打开网络文件:
avformat_open_input(&m_format, "https://www.example.com/file.mp4", nullptr, nullptr);
代码能正常运行,但偶尔会出现连接被重置的情况,日志如下:
[tls @ 0x7f600ba690] Error in the pull function.
[tls @ 0x7f600ba690] IO error: Connection reset by peer
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f6007e450] Packet corrupt (stream = 0, dts = 24188928).
[aac @ 0x7f60324800] Input buffer exhausted before END element found
观察到FFmpeg CLI通过-reconnect参数可以实现自动重连,对应的日志会显示:
[tls @ 0x6e3b440] Error in the pull function.
[tls @ 0x6e3b440] IO error: Connection reset by peer
[https @ 0x6e37900] Will reconnect at 720896 in 0 second(s), error=Connection reset by peer.
现在需要在libavformat代码中实现同样的自动重连功能,具体方法如下:
实现步骤
libavformat中通过设置AVDictionary参数来开启重连,在调用avformat_open_input前完成配置:
- 初始化字典并添加重连相关配置
AVDictionary *opts = nullptr; // 开启自动重连核心开关 av_dict_set(&opts, "reconnect", "1", 0); // 设置最大重连尝试次数(可选,默认无限制) av_dict_set(&opts, "reconnect_max_streams", "10", 0); // 设置重连前的最大等待秒数(避免频繁重试,可选) av_dict_set(&opts, "reconnect_delay_max", "5", 0); // 允许在流结束时也尝试重连(适用于直播场景,可选) av_dict_set(&opts, "reconnect_at_eof", "1", 0);
- 调用
avformat_open_input时传入配置字典
int ret = avformat_open_input(&m_format, "https://www.example.com/file.mp4", nullptr, &opts); // 释放未被使用的字典条目 av_dict_free(&opts);
- 错误恢复补充
如果读取过程中遇到连接重置类错误,可结合avformat_seek_file定位到断开前的位置,配合重连后的流继续播放,确保播放连续性。
关键参数说明
reconnect: 核心开关,设为"1"开启自动重连,默认"0"关闭reconnect_max_streams: 限制最大重连尝试次数,防止无限重试reconnect_delay_max: 控制重连间隔上限,避免短时间内频繁发起连接请求reconnect_at_eof: 针对直播流场景,允许在流标记结束时仍尝试重连
内容的提问来源于stack exchange,提问作者user24897675
相关产品推荐
相关产品推荐

