python - 使用 QThread 动态创建 QImage 帧到 ffmpeg 标准输入

标签 python ffmpeg pyqt5 pipe qprocess

我正在尝试使用在单独线程上动态创建的帧使用 ffmpeg 创建视频文件。
虽然我可以创建这些帧并将它们存储在磁盘/内存上,但我想避免该 channel ,因为帧的数量/大小可能很高,并且可以使用不同的格式或选项创建许多“作业”。但是,同样重要的是,我想更好地理解这背后的逻辑,因为我承认我对线程/处理的实际工作方式并没有非常深入的了解。
现在我正在尝试在 QThread 对象中创建 QProcess ,然后在进程启动后立即运行图像创建线程,但它似乎不起作用:没有创建文件,我什至没有从标准错误中获取任何输出(但我知道我应该这样做,因为如果我不使用线程我可以得到它)。
不幸的是,由于我对 QProcess 如何处理线程和管道(显然,所有可能的 ffmpeg 选项)知之甚少,我真的不明白如何实现这一点。
除了显然创建了输出文件之外,预期的结果是能够启动编码(并且可能同时排队更多编码),同时保持 UI 响应并获得当前处理状态的通知。

import re
from PyQt5 import QtCore, QtGui, QtWidgets

logRegExp = r'(?:(n:\s+)(?P<frame>\d+)\s).*(?:(pts_time:\s*)(?P<time>\d+.\d*))'

class Encoder(QtCore.QThread):
    completed = QtCore.pyqtSignal()
    frameDone = QtCore.pyqtSignal(object)
    def __init__(self, width=1280, height=720, frameCount=100):
        super().__init__()
        self.width = width
        self.height = height
        self.frameCount = frameCount

    def start(self):
        self.currentLog = ''
        self.currentData = bytes()
        self.process = QtCore.QProcess()
        self.process.setReadChannel(self.process.StandardError)
        self.process.finished.connect(self.completed)
        self.process.readyReadStandardError.connect(self.stderr)
        self.process.started.connect(super().start)
        self.process.start('ffmpeg', [
            '-y', 
            '-f', 'png_pipe', 
            '-i', '-', 
            '-c:v', 'libx264', 
            '-b:v', '800k', 
            '-an', 
            '-vf', 'showinfo',
            '/tmp/test.h264', 
        ])

    def stderr(self):
        self.currentLog += str(self.process.readAllStandardError(), 'utf-8')
        *lines, self.currentLog = self.currentLog.split('\n')
        for line in lines:
            print('STDERR: {}'.format(line))
            match = re.search(logRegExp, line)
            if match:
                data = match.groupdict()
                self.frameDone.emit(int(data['frame']))

    def run(self):
        font = QtGui.QFont()
        font.setPointSize(80)
        rect = QtCore.QRect(0, 0, self.width, self.height)
        for frame in range(1, self.frameCount + 1):
            img = QtGui.QImage(QtCore.QSize(self.width, self.height), QtGui.QImage.Format_ARGB32)
            img.fill(QtCore.Qt.white)
            qp = QtGui.QPainter(img)
            qp.setFont(font)
            qp.setPen(QtCore.Qt.black)
            qp.drawText(rect, QtCore.Qt.AlignCenter, 'Frame {}'.format(frame))
            qp.end()
            img.save(self.process, 'PNG')
        print('frame creation complete')


class Test(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        layout = QtWidgets.QVBoxLayout(self)
        self.startButton = QtWidgets.QPushButton('Start')
        layout.addWidget(self.startButton)

        self.frameLabel = QtWidgets.QLabel()
        layout.addWidget(self.frameLabel)

        self.process = Encoder()
        self.process.completed.connect(lambda: self.startButton.setEnabled(True))
        self.process.frameDone.connect(self.frameLabel.setNum)
        self.startButton.clicked.connect(self.create)

    def create(self):
        self.startButton.setEnabled(False)
        self.process.start()


import sys
app = QtWidgets.QApplication(sys.argv)
test = Test()
test.show()
sys.exit(app.exec_())
如果我在 run() 末尾添加以下行,那么文件实际上是被创建的,我得到了stderr输出,但是我可以看到它是在for循环完成后处理的,这显然不是预期的结果:
    self.process.closeWriteChannel()
    self.process.waitForFinished()
    self.process.terminate()
奖励:我在 Linux 上,我不知道它在 Windows 上的工作方式是否不同(我想它在 MacOS 上的工作方式类似),但无论如何我想知道是否存在差异以及如何处理跟他们。

最佳答案

事实证明,我是部分正确和错误的。

  • ffmpeg 具有多个级别和数量的内部缓冲,具体取决于输入/输出格式、过滤器和编解码器:我只是没有创建足够的帧来看到这种情况发生;
  • 与 QProcess 的交互应该发生在创建它的线程中;
  • 出于这个原因,数据不能从不同的线程直接写入写入 channel ,因此必须使用信号来代替;
  • 写入所有数据后,必须关闭写入 channel (从其同一线程)以确保完成编码;

  • 考虑到上述情况,我只使用线程创建图像,然后用保存的每个图像的 QByteArray 发出信号;最后,在图像创建完成后,我等待实际完成(基于 showinfo 过滤器输出),以便线程实际上被认为已完成。在多个作业的情况下,可以使用一些优化来排队进一步创建图像,但考虑到它可能不会提高性能,我更喜欢当前的方法。
    这是修改后的代码,我用不同的格式进行了测试,它似乎按预期工作。
    import re
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    logRegExp = r'(?:(n:\s+)(?P<frame>\d+)\s).*(?:(pts_time:\s*)(?P<time>\d+.\d*))'
    
    class Encoder(QtCore.QThread):
        completed = QtCore.pyqtSignal()
        frameDone = QtCore.pyqtSignal(object)
        imageReady = QtCore.pyqtSignal(object)
        def __init__(self):
            super().__init__()
            self.imageReady.connect(self.writeImage)
            self.queue = []
    
            self.process = QtCore.QProcess()
            self.process.setReadChannel(self.process.StandardError)
            self.process.finished.connect(self.processQueue)
            self.process.readyReadStandardError.connect(self.stderr)
            self.process.started.connect(self.start)
    
        def addJob(self, width=1280, height=720, frameCount=500, format='h264', *opts):
            self.queue.append((width, height, frameCount, format, opts))
            if not self.process.state():
                self.processQueue()
    
        def writeImage(self, image):
            self.process.write(image)
            self.imageCount += 1
            if self.imageCount == self.frameCount:
                self.process.closeWriteChannel()
    
        def processQueue(self):
            if not self.queue:
                return
            self.currentLog = ''
            self.lastFrameWritten = -1
            self.imageCount = 0
            self.width, self.height, self.frameCount, format, opts = self.queue.pop(0)
            args = [
                '-y', 
                '-f', 'png_pipe', 
                '-i', '-',
            ]
            if opts:
                args += [str(o) for o in opts]
            args += [
                '-an', 
                '-vf', 'showinfo',
                '/tmp/test.{}'.format(format), 
            ]
            self.process.start('ffmpeg', args)
    
        def stderr(self):
            self.currentLog += str(self.process.readAllStandardError(), 'utf-8')
            *lines, self.currentLog = self.currentLog.split('\n')
            for line in lines:
                match = re.search(logRegExp, line)
                if match:
                    data = match.groupdict()
                    self.lastFrameWritten = int(data['frame'])
                    self.frameDone.emit(self.lastFrameWritten + 1)
                else:
                    print(line)
    
        def run(self):
            font = QtGui.QFont()
            font.setPointSize(80)
            rect = QtCore.QRect(0, 0, self.width, self.height)
            for frame in range(1, self.frameCount + 1):
                img = QtGui.QImage(QtCore.QSize(self.width, self.height), 
                    QtGui.QImage.Format_ARGB32)
                img.fill(QtCore.Qt.white)
                qp = QtGui.QPainter(img)
                qp.setFont(font)
                qp.setPen(QtCore.Qt.black)
                qp.drawText(rect, QtCore.Qt.AlignCenter, 'Frame {}'.format(frame))
                qp.end()
                ba = QtCore.QByteArray()
                buffer = QtCore.QBuffer(ba)
                img.save(buffer, 'PNG')
                self.imageReady.emit(ba)
            while self.lastFrameWritten < self.frameCount - 1:
                self.sleep(.5)
            self.completed.emit()
    
    
    class Test(QtWidgets.QWidget):
        def __init__(self):
            super().__init__()
            layout = QtWidgets.QVBoxLayout(self)
            self.startButton = QtWidgets.QPushButton('Start')
            layout.addWidget(self.startButton)
    
            self.frameLabel = QtWidgets.QLabel()
            layout.addWidget(self.frameLabel)
    
            self.encoder = Encoder()
            self.encoder.completed.connect(lambda: self.startButton.setEnabled(True))
            self.encoder.frameDone.connect(self.frameLabel.setNum)
            self.startButton.clicked.connect(self.create)
    
        def create(self):
            self.startButton.setEnabled(False)
            self.encoder.addJob()
    
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        test = Test()
        test.show()
        sys.exit(app.exec_())
    

    关于python - 使用 QThread 动态创建 QImage 帧到 ffmpeg 标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67460992/

    相关文章:

    html - BlackBerry HTML5 流媒体的编码设置是什么?

    python - PyQt4 代码不适用于 PyQt5 (QHeaderView)

    python - 遵循照片应用程序教程时出现 Django models.py 错误

    windows - FFMPEG 的输入参数

    Python time.gmtime() 返回比系统时间提前 5 小时的时间

    unix - 通过 ffmpeg 命令将文件的扩展名转换为不同的目录

    qt - QHeaderView:根据列的内容大小拉伸(stretch)或调整大小到内容

    python - 如何检查是否按下了键盘修饰符(Shift、Ctrl 或 Alt)?

    python - 如何将分数格式的英尺和英寸转换为小数?

    python - sqlite数据库放在python命令行项目的什么地方