android - QVideoFrame::map() 崩溃

标签 android c++ qt opengl-es android-ndk

我正在尝试使用 QCamera 从相机获取图像。 我认为我应该派生自 QAbstractVideoSurface 并实现 present(),其中代表相机捕获的当前图像的 QVideoFrame 被发送为一个参数。

因为我需要做一些处理,我尝试map()我的框架,用bits()获取数据,做任何我必须做的,然后unmap() 它。但是我在 map()

上崩溃了

这是我得到的错误:

W libTest.so: (null):0 ((null)): Unsupported viewfinder pixel format
D SensorManager: registerListener :: 6, LSM6DSL Acceleration Sensor, 200000, 0,
E libEGL  : call to OpenGL ES API with no current context (logged once per thread)
E GLConsumer: [SurfaceTexture-0-546-0] attachToContext: invalid current EGLDisplay
F libc    : Fatal signal 11 (SIGSEGV), code 1, fault addr 0x4 in tid 663 (qtMainLoopThrea)

我做错了什么?

这是一个完整的应用程序代码:

///////////////////////////////////////////////
//main.cpp
///////////////////////////////////////////////

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "camera_engine.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    CameraEngine camEngine;
    engine.rootContext()->setContextProperty("cameraEngine", &camEngine);

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}


///////////////////////////////////////////////
//camera_engine.h
///////////////////////////////////////////////

#ifndef __CAMERA_ENGINE_H__
#define __CAMERA_ENGINE_H__

#include <QCamera>

#include "image_reader.h"

class CameraEngine : public QObject {
    Q_OBJECT
public:
    explicit CameraEngine(QCamera::Position pos = QCamera::BackFace);
    ~CameraEngine();

public slots:
    void start();
private:
    QCamera mCamera;
    ImageReader mImageReader;
};

#endif  // __CAMERA_ENGINE_H__


///////////////////////////////////////////////
//camera_engine.cpp
///////////////////////////////////////////////

#include "camera_engine.h"

CameraEngine::CameraEngine(QCamera::Position pos) : mCamera(pos)
{
    mCamera.setViewfinder(&mImageReader);

    QCameraViewfinderSettings viewFinderSettings;
    viewFinderSettings.setResolution(640, 480);
    viewFinderSettings.setMinimumFrameRate(30);
    viewFinderSettings.setMaximumFrameRate(30);
    viewFinderSettings.setPixelFormat(QVideoFrame::Format_RGB24);
    mCamera.setViewfinderSettings(viewFinderSettings);
}

CameraEngine::~CameraEngine()
{
    if (mCamera.state() == QCamera::ActiveState) {
        mCamera.stop();
    }
}

void CameraEngine::start()
{
    mCamera.start();
}


///////////////////////////////////////////////
//image_reader.h
///////////////////////////////////////////////

#ifndef CAMERA_IMAGE_READER_H
#define CAMERA_IMAGE_READER_H

#include <QAbstractVideoSurface>

class ImageReader : public QAbstractVideoSurface {
    Q_OBJECT
public:
    ImageReader() = default;
    ~ImageReader() = default;

    virtual bool present(const  QVideoFrame& frame);
    virtual QList<QVideoFrame::PixelFormat> supportedPixelFormats(QAbstractVideoBuffer::HandleType type) const;
};

#endif  // CAMERA_IMAGE_READER_H


///////////////////////////////////////////////
//image_reader.cpp
///////////////////////////////////////////////

#include "image_reader.h"
#include <QDebug>

bool ImageReader::present(const QVideoFrame &frame)
{
    QVideoFrame currentFrame = frame;

    currentFrame.map(QAbstractVideoBuffer::ReadOnly); //crashes here
    // Do something
    currentFrame.unmap();

    return true;
}

QList<QVideoFrame::PixelFormat> ImageReader::supportedPixelFormats(QAbstractVideoBuffer::HandleType type) const
{
    Q_UNUSED(type)
    return QList<QVideoFrame::PixelFormat>() << QVideoFrame::Format_RGB24;
}

///////////////////////////////////////////////
//main.qml
///////////////////////////////////////////////

import QtQuick 2.11
import QtQuick.Controls 2.2

ApplicationWindow {
    id: window

    visible: true
    width: 640
    height: 480

    Component.onCompleted: cameraEngine.start()
}

编辑:所以,我认为这可能是因为我的 QVideoFrame 存储为 OpenGL 纹理,而我的 present() 函数可能没有在 OpenGL 线程上运行,因此找不到 OpenGL ES语境。 有没有办法确保它在正确的线程上运行?

Edit2:我发现了这个:http://doc.qt.io/qt-5/qtquick-scenegraph-openglunderqml-example.html

也许我可以调整此代码以获得有效的 OpenGL ES 上下文。不幸的是我现在没有时间去做。我会在那个星期一尝试,除非有人有更好的建议,然后告诉你结果。

Edit3:所以,显然我的解决方案不是很好,我在 initializeOpenGLFunctions();

上遇到了崩溃 (SIGSEGV)

我看到 Antonio Dias 的回答,使用 VideoOutput 和函数 grabToImage,试过了,它似乎有效,但是,如果我理解正确,grabToImage 在 CPU 内存中“绘制”VideoOutput,我丢失了一些我计划在此过程中使用 QMediaMetaData 获取的元数据。

我也试过直接用NDK,但是摄像头至少要求API level 24,而且设置了我找到的所有相关设置后,好像也用不上。

Edit4:我实际上不知道我做了什么,但我的程序最终使用了正确的 API 级别,所以我现在将使用 NDK 解决方案。

最佳答案

我终于成功了。显然 QCamera 在 Android 上有一些问题,所以我不得不使用 QML Camera,并用 VideoOutput 显示它,并通过应用过滤器我可以得到我的图像。

这个过滤器由两部分组成:一部分来自 QAbstractVideoFilter , 另一个派生自 QVideoFilterRunnable .

代码如下:

////////////////////////////////////////////////////////////////////
// main.cpp
////////////////////////////////////////////////////////////////////

#include <QGuiApplication>
#include <QQmlApplicationEngine>

#include "myfilter.hpp"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    qmlRegisterType<MyFilter>("example.myfilter", 1, 0, "MyFilter");

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}


////////////////////////////////////////////////////////////////////
// myfilter.hpp
////////////////////////////////////////////////////////////////////

#ifndef MYFILTER_H
#define MYFILTER_H

#include <QAbstractVideoFilter>

class MyFilterRunnable : public QVideoFilterRunnable {
public:
    QVideoFrame run(QVideoFrame *input, const QVideoSurfaceFormat &surfaceFormat, RunFlags flags);
};


class MyFilter : public QAbstractVideoFilter
{
public:
    QVideoFilterRunnable* createFilterRunnable();
};

#endif // MYFILTER_H

////////////////////////////////////////////////////////////////////
// myfilter.cpp
////////////////////////////////////////////////////////////////////

#include "myfilter.hpp"

#include <QOpenGLContext>
#include <QOpenGLFunctions>

QVideoFrame MyFilterRunnable::run(QVideoFrame *input, const QVideoSurfaceFormat &surfaceFormat, QVideoFilterRunnable::RunFlags flags)
{
    QImage img(input->width(), input->height(), QImage::Format_RGBA8888);
    bool success = false;
    if (input->handleType() == QAbstractVideoBuffer::GLTextureHandle) {
        GLuint textureId = input->handle().toUInt();
        QOpenGLContext *ctx = QOpenGLContext::currentContext();
        QOpenGLFunctions *f = ctx->functions();
        GLuint fbo;
        f->glGenFramebuffers(1, &fbo);
        GLuint prevFbo;
        f->glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *) &prevFbo);
        f->glBindFramebuffer(GL_FRAMEBUFFER, fbo);
        f->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0);
        f->glReadPixels(0, 0, input->width(), input->height(), GL_RGBA, GL_UNSIGNED_BYTE, img.bits());
        f->glBindFramebuffer(GL_FRAMEBUFFER, prevFbo);
        success = true;
    } // else handle other types

    if( success ) {
        // Process image
        return QVideoFrame(img);
    } else {
        return *input; //Could not apply filter, return unmodified input
    }
}

QVideoFilterRunnable *MyFilter::createFilterRunnable()
{
    return new MyFilterRunnable;
}


////////////////////////////////////////////////////////////////////
// main.qml
////////////////////////////////////////////////////////////////////

import QtQuick 2.11
import QtQuick.Controls 2.2
import QtMultimedia 5.9
import example.myfilter 1.0

ApplicationWindow {
    id: window

    visible: true
    width: 640
    height: 480

    Camera {
        id: camera
    }
    MyFilter {
        id: filter
    }
    VideoOutput {
        source: camera
        autoOrientation: true
        filters: [ filter ]
        anchors.fill: parent
    }
}

(我的run 实现改编自这里:http://code.qt.io/cgit/qt/qtmultimedia.git/tree/examples/multimedia/video/qmlvideofilter_opencl/rgbframehelper.h)

关于android - QVideoFrame::map() 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51102225/

相关文章:

android - 如何在 Android 中创建一个标签为 "@"的按钮?

c++ - 滥用逗号运算符来柯里化(Currying)函数参数

c++ - 在 Qt 中正确使用 C++11 基于范围的 for 循环

android - 将 TextView 与另一个 View 的中心对齐

android - 我如何制作像 Skype 应用程序这样的介绍性标识动画?

c++ - 将类型为 `int` 的临时对象转换为引用安全吗?

c++ - QCustomPlot 中项目的手动矩形选择

c++ - 在 debian64 中编译 Qt 5 失败

android:异常错误的帮助(行号)

c++ - 如何在 O(logn) 中查找 STL 中元素的等级