ffmpeg av_read_frame()需要很长时间才能停止

yuy*_*eng 8 ffmpeg

我使用ffmpeg解码RTSP视频.它喜欢:当它在文件末尾时,它会在av_read_frame()中长时间阻塞,为什么?

pog*_*kiy 8

各种原因可能导致长时间阻塞.但您可以控制I/O层的处理时间.

使用该结构AVFormatContext::interrupt_callback设置中断处理程序.

class timeout_handler {
  public:
    timeout_handler(unsigned int t) : timeout_ms_(TimeoutMs){}

    void reset(unsigned int 0) {
      timeout_ms_ = TimeoutMs;
      lastTime_ = my_get_local_time();
    }

    bool is_timeout(){
      const my_time_duration actualDelay = my_get_local_time() - lastTime_;
      return actualDelay > timeout_ms_;
    }

    static int check_interrupt(void * t) {
       return t && static_cast<timeout_handler *>(t)->is_timeout();
    }

 public:
   unsigned int timeout_ms_;
   my_time_t lastTime_;      
 };


 /// .................
 AVFormatContext * ic;
 timeout_handler * th = new timeout_handler(kDefaultTimeout);
 /// .................
 ic->interrupt_callback.opaque = (void*)th ;
 ic->interrupt_callback.callback = &timeout_handler::check_interrupt;
 /// open input
 // avformat_open_input(ic, ... );
 // etc

 /// .................
 /// before any I/O operations, for example:
 th->reset(kDefaultTimeout);
 int e = AVERROR(EAGAIN);
 while (AVERROR(EAGAIN) == e) 
  e = av_read_frame(ic, &packet);
 // If the time exceeds the limit, then the process interruped at the next IO operation.   
Run Code Online (Sandbox Code Playgroud)