avformat_open_input默認是阻塞操作,如果不加控制,等待時間可能會達到30s以上,對於有些情況,等待30s的體驗是無法接受的。
ffmpeg支持interrupt_callback機制,可以對輸入(或輸出)的AVFormatContext的interrupt_callback成員設置,然后再回調函數中做控制。
// 回調函數的參數,用了時間 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 > 8) { // 等待超過8s則中斷 return 1; } } return 0; } // usage Runner input_runner = {0}; AVFormatContext *ifmt_ctx = avformat_alloc_context(); ifmt_ctx->interrupt_callback.callback = interrupt_callback; ifmt_ctx->interrupt_callback.opaque = &input_runner; input_runner.lasttime = time(NULL); // 調用之前初始化時間 ret = avformat_open_input(&ifmt_ctx, url, NULL, NULL); if(ret < 0) { // error }
特別提醒: rtsp 可以使用 timeout 配置參數, rtmp 使用timeout 配置參數會報錯(ffmpeg bug), 所以只能使用 回調來結束 avformat_open_input的阻塞行為
參考:
https://www.suninf.net/2017/02/avformat_open_input-interrupt-callback.html
https://www.cnblogs.com/wainiwann/p/4218341.html