summaryrefslogtreecommitdiffstats
path: root/src/plugins/multimedia/ffmpeg/qffmpeghwaccel_vaapi.cpp
blob: 2bb857f41b5bc5fd88bdf990ea92984c81daec7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qffmpeghwaccel_vaapi_p.h"

#if !QT_CONFIG(vaapi)
#error "Configuration error"
#endif

#include <va/va.h>

#include <qvideoframeformat.h>
#include "qffmpegvideobuffer_p.h"
#include "private/qvideotexturehelper_p.h"

#include <private/qrhi_p.h>
#include <private/qrhigles2_p.h>

#include <qguiapplication.h>
#include <qpa/qplatformnativeinterface.h>

#include <qopenglfunctions.h>

//#define VA_EXPORT_USE_LAYERS

#if __has_include("drm/drm_fourcc.h")
#include <drm/drm_fourcc.h>
#elif __has_include("libdrm/drm_fourcc.h")
#include <libdrm/drm_fourcc.h>
#else
// keep things building without drm_fourcc.h
#define fourcc_code(a, b, c, d) ((uint32_t)(a) | ((uint32_t)(b) << 8) | \
                                 ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))

#define DRM_FORMAT_RGBA8888     fourcc_code('R', 'A', '2', '4') /* [31:0] R:G:B:A 8:8:8:8 little endian */
#define DRM_FORMAT_RGB888       fourcc_code('R', 'G', '2', '4') /* [23:0] R:G:B little endian */
#define DRM_FORMAT_RG88         fourcc_code('R', 'G', '8', '8') /* [15:0] R:G 8:8 little endian */
#define DRM_FORMAT_ABGR8888     fourcc_code('A', 'B', '2', '4') /* [31:0] A:B:G:R 8:8:8:8 little endian */
#define DRM_FORMAT_BGR888       fourcc_code('B', 'G', '2', '4') /* [23:0] B:G:R little endian */
#define DRM_FORMAT_GR88         fourcc_code('G', 'R', '8', '8') /* [15:0] G:R 8:8 little endian */
#define DRM_FORMAT_R8           fourcc_code('R', '8', ' ', ' ') /* [7:0] R */
#define DRM_FORMAT_R16          fourcc_code('R', '1', '6', ' ') /* [15:0] R little endian */
#define DRM_FORMAT_RGB565       fourcc_code('R', 'G', '1', '6') /* [15:0] R:G:B 5:6:5 little endian */
#define DRM_FORMAT_RG1616       fourcc_code('R', 'G', '3', '2') /* [31:0] R:G 16:16 little endian */
#define DRM_FORMAT_GR1616       fourcc_code('G', 'R', '3', '2') /* [31:0] G:R 16:16 little endian */
#define DRM_FORMAT_BGRA1010102  fourcc_code('B', 'A', '3', '0') /* [31:0] B:G:R:A 10:10:10:2 little endian */
#endif

extern "C" {
#include <libavutil/hwcontext_vaapi.h>
}

#include <va/va_drm.h>
#include <va/va_drmcommon.h>

#include <EGL/egl.h>
#include <EGL/eglext.h>

#include <unistd.h>

#include <qloggingcategory.h>

static Q_LOGGING_CATEGORY(qLHWAccelVAAPI, "qt.multimedia.ffmpeg.hwaccelvaapi");

namespace QFFmpeg {

static const quint32 *fourccFromPixelFormat(const QVideoFrameFormat::PixelFormat format)
{
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
    const quint32 rgba_fourcc = DRM_FORMAT_ABGR8888;
    const quint32 rg_fourcc = DRM_FORMAT_GR88;
    const quint32 rg16_fourcc = DRM_FORMAT_GR1616;
#else
    const quint32 rgba_fourcc = DRM_FORMAT_RGBA8888;
    const quint32 rg_fourcc = DRM_FORMAT_RG88;
    const quint32 rg16_fourcc = DRM_FORMAT_RG1616;
#endif

//    qCDebug(qLHWAccelVAAPI) << "Getting DRM fourcc for pixel format" << format;

    switch (format) {
    case QVideoFrameFormat::Format_Invalid:
    case QVideoFrameFormat::Format_IMC1:
    case QVideoFrameFormat::Format_IMC2:
    case QVideoFrameFormat::Format_IMC3:
    case QVideoFrameFormat::Format_IMC4:
    case QVideoFrameFormat::Format_SamplerExternalOES:
    case QVideoFrameFormat::Format_Jpeg:
    case QVideoFrameFormat::Format_SamplerRect:
        return nullptr;

    case QVideoFrameFormat::Format_ARGB8888:
    case QVideoFrameFormat::Format_ARGB8888_Premultiplied:
    case QVideoFrameFormat::Format_XRGB8888:
    case QVideoFrameFormat::Format_BGRA8888:
    case QVideoFrameFormat::Format_BGRA8888_Premultiplied:
    case QVideoFrameFormat::Format_BGRX8888:
    case QVideoFrameFormat::Format_ABGR8888:
    case QVideoFrameFormat::Format_XBGR8888:
    case QVideoFrameFormat::Format_RGBA8888:
    case QVideoFrameFormat::Format_RGBX8888:
    case QVideoFrameFormat::Format_AYUV:
    case QVideoFrameFormat::Format_AYUV_Premultiplied:
    case QVideoFrameFormat::Format_UYVY:
    case QVideoFrameFormat::Format_YUYV:
    {
        static constexpr quint32 format[] = { rgba_fourcc, 0, 0, 0 };
        return format;
    }

    case QVideoFrameFormat::Format_Y8:
    {
        static constexpr quint32 format[] = { DRM_FORMAT_R8, 0, 0, 0 };
        return format;
    }
    case QVideoFrameFormat::Format_Y16:
    {
        static constexpr quint32 format[] = { DRM_FORMAT_R16, 0, 0, 0 };
        return format;
    }

    case QVideoFrameFormat::Format_YUV420P:
    case QVideoFrameFormat::Format_YUV422P:
    case QVideoFrameFormat::Format_YV12:
    {
        static constexpr quint32 format[] = { DRM_FORMAT_R8, DRM_FORMAT_R8, DRM_FORMAT_R8, 0 };
        return format;
    }
    case QVideoFrameFormat::Format_YUV420P10:
    {
        static constexpr quint32 format[] = { DRM_FORMAT_R16, DRM_FORMAT_R16, DRM_FORMAT_R16, 0 };
        return format;
    }

    case QVideoFrameFormat::Format_NV12:
    case QVideoFrameFormat::Format_NV21:
    {
        static constexpr quint32 format[] = { DRM_FORMAT_R8, rg_fourcc, 0, 0 };
        return format;
    }

    case QVideoFrameFormat::Format_P010:
    case QVideoFrameFormat::Format_P016:
    {
        static constexpr quint32 format[] = { DRM_FORMAT_R16, rg16_fourcc, 0, 0 };
        return format;
    }
    }
    return nullptr;
}

class VAAPITextureSet : public TextureSet
{
public:
    ~VAAPITextureSet();
    qint64 textureHandle(int plane) override {
        return textures[plane];
    }

    QRhi *rhi = nullptr;
    QOpenGLContext *glContext = nullptr;
    int nPlanes = 0;
    GLuint textures[4] = {};
};


VAAPITextureConverter::VAAPITextureConverter(QRhi *rhi)
    : TextureConverterBackend(nullptr)
{
    qCDebug(qLHWAccelVAAPI) << ">>>> Creating VAAPI HW accelerator";

    if (!rhi || rhi->backend() != QRhi::OpenGLES2) {
        qWarning() << "VAAPITextureConverter: No rhi or non openGL based RHI";
        this->rhi = nullptr;
        return;
    }

    auto *nativeHandles = static_cast<const QRhiGles2NativeHandles *>(rhi->nativeHandles());
    glContext = nativeHandles->context;
    if (!glContext) {
        qCDebug(qLHWAccelVAAPI) << "    no GL context, disabling";
        return;
    }
    const QString platform = QGuiApplication::platformName();
    QPlatformNativeInterface *pni = QGuiApplication::platformNativeInterface();
    eglDisplay = pni->nativeResourceForIntegration("egldisplay");
    qCDebug(qLHWAccelVAAPI) << "     platform is" << platform << eglDisplay;

    if (!eglDisplay) {
        qCDebug(qLHWAccelVAAPI) << "    no egl display, disabling";
        return;
    }
    eglImageTargetTexture2D = eglGetProcAddress("glEGLImageTargetTexture2DOES");
    if (!eglDisplay) {
        qCDebug(qLHWAccelVAAPI) << "    no eglImageTargetTexture2D, disabling";
        return;
    }

    // everything ok, indicate that we can do zero copy
    this->rhi = rhi;
}

VAAPITextureConverter::~VAAPITextureConverter()
{
}

//#define VA_EXPORT_USE_LAYERS
TextureSet *VAAPITextureConverter::getTextures(AVFrame *frame)
{
//        qCDebug(qLHWAccelVAAPI) << "VAAPIAccel::getTextures";
    if (frame->format != AV_PIX_FMT_VAAPI || !eglDisplay) {
        qCDebug(qLHWAccelVAAPI) << "format/egl error" << frame->format << eglDisplay;
        return nullptr;
    }

    if (!frame->hw_frames_ctx)
        return nullptr;

    auto *fCtx = (AVHWFramesContext *)frame->hw_frames_ctx->data;
    auto *ctx = fCtx->device_ctx;
    if (!ctx)
        return nullptr;

    auto *vaCtx = (AVVAAPIDeviceContext *)ctx->hwctx;
    auto vaDisplay = vaCtx->display;
    if (!vaDisplay) {
        qCDebug(qLHWAccelVAAPI) << "    no VADisplay, disabling";
        return nullptr;
    }

    VASurfaceID vaSurface = (uintptr_t)frame->data[3];

    VADRMPRIMESurfaceDescriptor prime;
    if (vaExportSurfaceHandle(vaDisplay, vaSurface,
                              VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2,
                              VA_EXPORT_SURFACE_READ_ONLY |
#ifdef VA_EXPORT_USE_LAYERS
                                  VA_EXPORT_SURFACE_SEPARATE_LAYERS,
#else
                                  VA_EXPORT_SURFACE_COMPOSED_LAYERS,
#endif
                              &prime) != VA_STATUS_SUCCESS)
    {
        qWarning() << "vaExportSurfaceHandle failed";
        return nullptr;
    }
    // ### Check that prime.fourcc is what we expect
    vaSyncSurface(vaDisplay, vaSurface);

//        qCDebug(qLHWAccelVAAPI) << "VAAPIAccel: vaSufraceDesc: width/height" << prime.width << prime.height << "num objects"
//                 << prime.num_objects << "num layers" << prime.num_layers;

    QOpenGLFunctions functions(glContext);

    AVPixelFormat fmt = HWAccel::format(frame);
    bool needsConversion;
    auto qtFormat = QFFmpegVideoBuffer::toQtPixelFormat(fmt, &needsConversion);
    auto *drm_formats = fourccFromPixelFormat(qtFormat);
    if (!drm_formats || needsConversion) {
        qWarning() << "can't use DMA transfer for pixel format" << fmt << qtFormat;
        return nullptr;
    }

    auto *desc = QVideoTextureHelper::textureDescription(qtFormat);
    int nPlanes = 0;
    for (; nPlanes < 5; ++nPlanes) {
        if (drm_formats[nPlanes] == 0)
            break;
    }
    Q_ASSERT(nPlanes == desc->nplanes);
    nPlanes = desc->nplanes;
//        qCDebug(qLHWAccelVAAPI) << "VAAPIAccel: nPlanes" << nPlanes;

    rhi->makeThreadLocalNativeContextCurrent();

    EGLImage images[4];
    GLuint glTextures[4] = {};
    functions.glGenTextures(nPlanes, glTextures);
    for (int i = 0;  i < nPlanes;  ++i) {
#ifdef VA_EXPORT_USE_LAYERS
#define LAYER i
#define PLANE 0
        if (prime.layers[i].drm_format != drm_formats[i]) {
            qWarning() << "expected DRM format check failed expected"
                       << Qt::hex << drm_formats[i] << "got" << prime.layers[i].drm_format;
        }
#else
#define LAYER 0
#define PLANE i
#endif

        EGLAttrib img_attr[] = {
            EGL_LINUX_DRM_FOURCC_EXT,      (EGLint)drm_formats[i],
            EGL_WIDTH,                     desc->widthForPlane(frame->width, i),
            EGL_HEIGHT,                    desc->heightForPlane(frame->height, i),
            EGL_DMA_BUF_PLANE0_FD_EXT,     prime.objects[prime.layers[LAYER].object_index[PLANE]].fd,
            EGL_DMA_BUF_PLANE0_OFFSET_EXT, (EGLint)prime.layers[LAYER].offset[PLANE],
            EGL_DMA_BUF_PLANE0_PITCH_EXT,  (EGLint)prime.layers[LAYER].pitch[PLANE],
            EGL_NONE
        };
        images[i] = eglCreateImage(eglDisplay, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, img_attr);
        if (!images[i]) {
            qWarning() << "eglCreateImage failed for plane" << i << Qt::hex << eglGetError();
            return nullptr;
        }
        functions.glActiveTexture(GL_TEXTURE0 + i);
        functions.glBindTexture(GL_TEXTURE_2D, glTextures[i]);

        PFNGLEGLIMAGETARGETTEXTURE2DOESPROC eglImageTargetTexture2D = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)this->eglImageTargetTexture2D;
        eglImageTargetTexture2D(GL_TEXTURE_2D, images[i]);
        if (glGetError()) {
            qWarning() << "eglImageTargetTexture2D failed";
        }
    }

    for (int i = 0;  i < (int)prime.num_objects;  ++i)
        close(prime.objects[i].fd);

    for (int i = 0;  i < nPlanes;  ++i) {
        functions.glActiveTexture(GL_TEXTURE0 + i);
        functions.glBindTexture(GL_TEXTURE_2D, 0);
        eglDestroyImage(eglDisplay, images[i]);
    }

    VAAPITextureSet *textureSet = new VAAPITextureSet;
    textureSet->nPlanes = nPlanes;
    textureSet->rhi = rhi;
    textureSet->glContext = glContext;

    for (int i = 0; i < 4; ++i)
        textureSet->textures[i] = glTextures[i];
//        qCDebug(qLHWAccelVAAPI) << "VAAPIAccel: got textures" << textures[0] << textures[1] << textures[2] << textures[3];

    return textureSet;
}

VAAPITextureSet::~VAAPITextureSet()
{
    if (rhi) {
        rhi->makeThreadLocalNativeContextCurrent();
        QOpenGLFunctions functions(glContext);
        functions.glDeleteTextures(nPlanes, textures);
    }
}

}

QT_END_NAMESPACE