0

基于我的工作这个答案,我正在尝试使用 QtQGLWidget来渲染视频,但我遇到了一些问题。当我在我的视频解码线程中解码后立即保存一帧时,结果很好:

完整的框架

但是在绘制它时,它会严重损坏:

损坏的框架

看起来图像正在被复制并且复制没有完成,但是

  1. 我正在使用互斥锁来确保在绘制代码绘制时不会触及图像。

  2. 我传递了一个指向QImage绘图代码的指针,所以它应该是相同的内存块。

在解码线程中,我有以下内容:

/* Read in the frame up here, skipped for brevity */

// Set a new image
auto frameImage = make_shared<QImage>(nextFrame->getPixels(),
                                      nextFrame->getWidth(),
                                      nextFrame->getHeight(),
                                      QImage::Format_RGB888);

canvas->setImage(frameImage);
// Post a new order to repaint.
// Done this way because another thread cannot directly call repaint()
QCoreApplication::postEvent(canvas, new QPaintEvent(canvas->rect()));

然后,在画布中(源自QGLWidget):

void QGLCanvas::setImage(const std::shared_ptr<QImage>& image)
{
    // Keep the QGL canvas from drawing while we change the image
    lock_guard<mutex> pixelLock(pixelsMutex);
    img = image; // img is just a shared_ptr
}

void QGLCanvas::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, 1);

    // Lock the image so that other threads can't access it at the same time
    lock_guard<mutex> pixelLock(pixelsMutex);
    painter.drawImage(this->rect(), *img);
}

这里发生了什么?

4

1 回答 1

1

我忘记了QImage,当给定像素数据时,它是浅拷贝,而不是深拷贝。只要 QImage 存在,就可以通过保留分配的实际帧数据来解决问题,如下所示:

void QGLCanvas::setFrame(const std::shared_ptr<VideoFrame>& newFrame)
{
    // Keep the QGL canvas from drawing while we change the image
    lock_guard<mutex> pixelLock(pixelsMutex);

    // Keep a shared_ptr reference to our frame data
    frame = newFrame;

    // Create a new QImage, which is just a shallow copy of the frame.
    img.reset(new QImage(frame->getPixels(),
                         frame->getWidth(),
                         frame->getHeight(),
                         QImage::Format_RGB888));
}
于 2013-07-02T16:52:57.033 回答