【初学ffmpeg】ffmpeg从url解析流并保存yuv文件 以及 设置超时

代码部分可参照

ffmpeg解码保存为yuv

因为 avformat_open_input 可以直接打开url,把上面代码部分的filepath换成url地址即可。

代码虽然可以运行,且能保存成yuv文件,但是会一直阻塞在 av_read_frame中,无法终止进程,且 avformat_open_input也会阻塞很久。所以使用了超时机制。

interrupt_callback 是个回调函数,返回0时为正常,如果返回1了,那么相关阻塞的函数就会返回而不再继续阻塞。

// 回调函数的参数,用了时间
typedef struct {
    time_t lasttime;
} Runner;

// 回调函数
static int interrupt_callback(void *p) {
    Runner *r = (Runner *)p;
    if (r->lasttime > 0) {
        if (time(NULL) - r->lasttime > 5) {
            // 等待超过5s则中断
            return 1;
        }
    }

    return 0;
}

在avformat_open_input之前设置pFormatCtx的回调函数, opaque是传递的参数,并把时间变量设置成time(NULL)

    Runner timeOutTools;
    auto pFormatCtx = avformat_alloc_context();
    pFormatCtx->interrupt_callback.callback = interrupt_callback;
    pFormatCtx->interrupt_callback.opaque = &timeOutTools;
    timeOutTools.lasttime = time(NULL);
    if(avformat_open_input(&pFormatCtx,filepath,NULL, NULL)!=0){
        printf("Couldn't open input stream.\n");
        return -1;
    }

 

在循环读取frame的时候也需要每次循环设置一次time(NULL), 使回调函数重新计算是否需要中断阻塞。否则read几秒就直接终止了。

while(av_read_frame(pFormatCtx, packet)>=0){
        timeOutTools.lasttime = time(NULL);
        ......
}

注意:

        使用time函数时,需要包含头文件<time.h>或<ctime>,但是可能会与ffmpeg的头文件<time.h>冲突,我没有找到比较好的解决方法,是直接把 ffmpeg的头文件 <time.h>改了个名,才编译通过。 希望各位大佬有其他好的方法可以告知一下 (我使用的IDE是CLION)

参考:https://blog.csdn.net/qq_41824928/article/details/103611366

参考:https://www.suninf.net/2017/02/avformat_open_input-interrupt-callback.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值