You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用FFMPEG Java调用avformat_open_input无法打开RTMP流,报错无法分配请求地址

问题描述

尝试使用avformat_open_input打开RTMP流时,始终抛出“Cannot assign requested address”错误。RTMP URL确认正确,因为可以通过VLC播放器和FFmpeg命令行正常拉流:

ffmpeg -i rtmp://1.1.1.1/app/teststream -vcodec copy -acodec copy output.mp4

使用的依赖是org.bytedeco:ffmpeg:5.1.2-1.5.8(ffmpeg-5.1.2-1.5.8.jar),相关代码如下:

int timeout = 2500;
setConnectionTimeout(timeout);

AVDictionary optionsDictionary = new AVDictionary();

String timeoutStr = String.valueOf(this.timeoutMicroSeconds);
av_dict_set(optionsDictionary, "timeout", timeoutStr, 0);

int analyzeDurationUs = 1500 * 1000;
String analyzeDuration = String.valueOf(analyzeDurationUs);
av_dict_set(optionsDictionary, "analyzeduration", analyzeDuration, 0);

int ret;

if ((ret = avformat_open_input(inputFormatContext, streamUrl, null, optionsDictionary)) < 0) {
  // ERROR Cannot assign requested address
}
排查与解决方案

以下是几个可能的原因及对应解决办法:

1. Timeout参数单位错误

FFmpeg的timeout选项单位是微秒,如果代码中this.timeoutMicroSeconds实际值过小(比如仅2500微秒,即2.5毫秒),会导致连接超时触发错误。

  • 修正:明确设置正确的微秒值,比如2.5秒对应2500 * 1000:
    String timeoutStr = String.valueOf(2500 * 1000);
    av_dict_set(optionsDictionary, "timeout", timeoutStr, 0);
    

2. AVDictionary初始化方式错误

ByTeco的AVDictionary直接用new AVDictionary()可能未正确分配底层FFmpeg结构,导致参数无法传递。

  • 修正:使用FFmpeg提供的av_dict_alloc()创建字典:
    AVDictionary optionsDictionary = av_dict_alloc();
    

3. 缺少RTMP协议专属参数

部分RTMP流需要强制TCP传输或设置socket层超时,否则可能出现地址分配失败。

  • 补充参数:
    av_dict_set(optionsDictionary, "rtmp_tcp", "1", 0); // 强制使用TCP模式
    av_dict_set(optionsDictionary, "stimeout", String.valueOf(2500 * 1000), 0); // socket超时(微秒)
    

4. 输入上下文未正确初始化

确保inputFormatContext已通过avformat_alloc_context()完成初始化,否则会导致底层调用异常。

  • 修正初始化代码:
    AVFormatContext inputFormatContext = avformat_alloc_context();
    

5. 依赖库平台兼容性问题

单独引入org.bytedeco:ffmpeg可能缺少对应平台的原生RTMP支持库,导致协议无法正常工作。

  • 修正:替换为平台依赖包,自动适配运行环境:
    <!-- Maven依赖示例 -->
    <dependency>
        <groupId>org.bytedeco</groupId>
        <artifactId>ffmpeg-platform</artifactId>
        <version>5.1.2-1.5.8</version>
    </dependency>
    

内容的提问来源于stack exchange,提问作者lastpeony4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 23:46:13