微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 O_NONBLOCK 块从流中读取

如何解决使用 O_NONBLOCK 块从流中读取

我正在像这样使用 popen 运行 ffmpeg:

    cmd = [self.ffmpeg]+self.ffmpeg_params+[ "-y","-i",self.uri,"-vf",vf,"-f","rawvideo","-pix_fmt","bgr24","-an","-sn","-"]
    self.proc = sp.Popen(cmd,stdout=sp.PIPE,stderr=sp.PIPE,bufsize=10)

然后我使用 self.read() 从标准输出读取帧,如下所示:

   def non_block_read(output):
      fd = output.fileno()
      fl = fcntl.fcntl(fd,fcntl.F_GETFL)
      fcntl.fcntl(fd,fcntl.F_SETFL,fl | os.O_NONBLOCK)
      try:
         print("will block here")
         r = output.read()
         print("this never happens :(")
         return r
      except:
        print("exception")
        return ""
    
    def read(self):
        non_block_read(self.proc.stderr)
        x = self.proc.stdout.read(int(self.w * self.h * 3))
        if len(x) < self.w * self.h * 3:
            self.terminate()
            return None
        img = np.frombuffer(x,dtype=np.uint8).reshape((h,w,3))
        self.cnt += 1
        return img

在今天之前,这段代码运行良好,ffmpeg 解码了视频,我正在从标准输出读取像素。为了避免 stderr 溢出,我在每帧之前使用非阻塞读取读取它。现在我观察到奇怪的行为,当 non_block_read 在 read() 调用中被阻塞时。为什么会发生这种情况?我没有更改系统中的任何内容,这才刚刚开始发生。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。