converters.c 26.9 KB
Newer Older
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
/*****************************************************************************
 * converters.c: OpenGL converters for common video formats
 *****************************************************************************
 * Copyright (C) 2016 VLC authors and VideoLAN
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <assert.h>
26 27
#include <limits.h>
#include <stdlib.h>
28

29
#include <vlc_common.h>
30
#include <vlc_memory.h>
31
#include <vlc_memstream.h>
32 33 34 35 36 37 38 39 40
#include "internal.h"

#ifndef GL_RED
#define GL_RED 0
#endif
#ifndef GL_R16
#define GL_R16 0
#endif

41 42 43 44
#ifndef GL_LUMINANCE16
#define GL_LUMINANCE16 0
#endif

45 46 47 48 49
#ifndef GL_UNPACK_ROW_LENGTH
#define GL_UNPACK_ROW_LENGTH 0x0CF2
#define NEED_GL_EXT_unpack_subimage
#endif

50 51 52 53 54 55 56 57 58 59 60
#ifdef VLCGL_HAS_PBO
struct picture_sys_t
{
    const opengl_tex_converter_t *tc;
    GLuint      buffers[PICTURE_PLANE_MAX];
    size_t      bytes[PICTURE_PLANE_MAX];
    GLsync      fence;
    unsigned    index;
};
#endif

61 62
struct priv
{
63
    bool   has_unpack_subimage;
64 65
    void * texture_temp_buf;
    size_t texture_temp_buf_size;
66 67 68 69 70 71
#ifdef VLCGL_HAS_PBO
    struct {
        picture_t *pics[VLCGL_PICTURE_MAX];
        unsigned long long list;
    } ongpu;
#endif
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
#if !defined(USE_OPENGL_ES2)
static int GetTexFormatSize(int target, int tex_format, int tex_internal,
                            int tex_type)
{
    GLint tex_param_size;
    switch (tex_format)
    {
        case GL_RED:
            tex_param_size = GL_TEXTURE_RED_SIZE;
            break;
        case GL_LUMINANCE:
            tex_param_size = GL_TEXTURE_LUMINANCE_SIZE;
            break;
        default:
            return -1;
    }
    GLuint texture;

    glGenTextures(1, &texture);
    glBindTexture(target, texture);
    glTexImage2D(target, 0, tex_internal, 64, 64, 0, tex_format, tex_type, NULL);
    GLint size = 0;
    glGetTexLevelParameteriv(target, 0, tex_param_size, &size);

    glDeleteTextures(1, &texture);
    return size;
}
#endif

103 104 105 106 107 108 109 110 111
static int
tc_yuv_base_init(opengl_tex_converter_t *tc, GLenum tex_target,
                 vlc_fourcc_t chroma, video_color_space_t yuv_space,
                 bool *swap_uv, const char *swizzle_per_tex[])
{
    const vlc_chroma_description_t *desc = vlc_fourcc_GetChromaDescription(chroma);
    if (desc == NULL)
        return VLC_EGENERIC;

Thomas Guillem's avatar
Thomas Guillem committed
112
    GLint oneplane_texfmt, oneplane16_texfmt, twoplanes_texfmt;
113 114 115 116 117 118

#if !defined(USE_OPENGL_ES2)
    if (HasExtension(tc->glexts, "GL_ARB_texture_rg"))
    {
        oneplane_texfmt = GL_RED;
        oneplane16_texfmt = GL_R16;
Thomas Guillem's avatar
Thomas Guillem committed
119
        twoplanes_texfmt = GL_RG;
120 121 122 123 124 125
    }
    else
#endif
    {
        oneplane_texfmt = GL_LUMINANCE;
        oneplane16_texfmt = GL_LUMINANCE16;
Thomas Guillem's avatar
Thomas Guillem committed
126
        twoplanes_texfmt = GL_LUMINANCE_ALPHA;
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
    }

    float yuv_range_correction = 1.0;
    if (desc->plane_count == 3)
    {
        GLint internal = 0;
        if (desc->pixel_size == 1)
            internal = oneplane_texfmt;
#if !defined(USE_OPENGL_ES2)
        else if (desc->pixel_size == 2)
        {
            if (oneplane16_texfmt == 0
             || GetTexFormatSize(tex_target, oneplane_texfmt, oneplane16_texfmt,
                                 GL_UNSIGNED_SHORT) != 16)
                return VLC_EGENERIC;

            internal = oneplane16_texfmt;
            yuv_range_correction = (float)((1 << 16) - 1)
                                 / ((1 << desc->pixel_bits) - 1);
        }
#endif
        else
            return VLC_EGENERIC;

        assert(internal != 0);

153 154
        tc->tex_count = 3;
        for (unsigned i = 0; i < tc->tex_count; ++i )
155 156
        {
            tc->texs[i] = (struct opengl_tex_cfg) {
157 158
                { desc->p[i].w.num, desc->p[i].w.den },
                { desc->p[i].h.num, desc->p[i].h.den },
159 160 161 162 163 164 165
                internal, oneplane_texfmt, GL_UNSIGNED_BYTE
            };
        }

        if (oneplane_texfmt == GL_RED)
            swizzle_per_tex[0] = swizzle_per_tex[1] = swizzle_per_tex[2] = "r";
    }
Thomas Guillem's avatar
Thomas Guillem committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    else if (desc->plane_count == 2)
    {
        if (desc->pixel_size != 1)
            return VLC_EGENERIC;

        tc->tex_count = 2;
        tc->texs[0] = (struct opengl_tex_cfg) {
            { 1, 1 }, { 1, 1 }, oneplane_texfmt, oneplane_texfmt, GL_UNSIGNED_BYTE
        };
        tc->texs[1] = (struct opengl_tex_cfg) {
            { 1, 2 }, { 1, 2 }, twoplanes_texfmt, twoplanes_texfmt, GL_UNSIGNED_BYTE
        };

        if (oneplane_texfmt == GL_RED)
        {
            swizzle_per_tex[0] = "r";
            swizzle_per_tex[1] = "rg";
        }
        else
        {
            swizzle_per_tex[0] = NULL;
            swizzle_per_tex[1] = "xa";
        }
    }
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
    else
        return VLC_EGENERIC;

    /* [R/G/B][Y U V O] from TV range to full range
     * XXX we could also do hue/brightness/constrast/gamma
     * by simply changing the coefficients
     */
    static const float matrix_bt601_tv2full[12] = {
        1.164383561643836,  0.0000,             1.596026785714286, -0.874202217873451 ,
        1.164383561643836, -0.391762290094914, -0.812967647237771,  0.531667823499146 ,
        1.164383561643836,  2.017232142857142,  0.0000,            -1.085630789302022 ,
    };
    static const float matrix_bt709_tv2full[12] = {
        1.164383561643836,  0.0000,             1.792741071428571, -0.972945075016308 ,
        1.164383561643836, -0.21324861427373,  -0.532909328559444,  0.301482665475862 ,
        1.164383561643836,  2.112401785714286,  0.0000,            -1.133402217873451 ,
    };

    const float *matrix;
    switch (yuv_space)
    {
        case COLOR_SPACE_BT601:
            matrix = matrix_bt601_tv2full;
            break;
        default:
            matrix = matrix_bt709_tv2full;
    };

    for (int i = 0; i < 4; i++) {
        float correction = i < 3 ? yuv_range_correction : 1.f;
        /* We place coefficient values for coefficient[4] in one array from
         * matrix values. Notice that we fill values from top down instead
         * of left to right.*/
        for (int j = 0; j < 4; j++)
            tc->yuv_coefficients[i*4+j] = j < 3 ? correction * matrix[j*4+i] : 0.f;
    }

    tc->chroma = chroma;
    tc->yuv_color = true;

Thomas Guillem's avatar
Thomas Guillem committed
230 231
    *swap_uv = chroma == VLC_CODEC_YV12 || chroma == VLC_CODEC_YV9 ||
               chroma == VLC_CODEC_NV21;
232 233 234 235 236 237 238 239 240 241 242 243 244
    return VLC_SUCCESS;
}

static int
tc_rgba_base_init(opengl_tex_converter_t *tc, GLenum tex_target,
                  vlc_fourcc_t chroma)
{
    (void) tex_target;

    if (chroma != VLC_CODEC_RGBA && chroma != VLC_CODEC_RGB32)
        return VLC_EGENERIC;

    tc->chroma = VLC_CODEC_RGBA;
245
    tc->tex_count = 1;
246
    tc->texs[0] = (struct opengl_tex_cfg) {
247
        { 1, 1 }, { 1, 1 }, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    };
    return VLC_SUCCESS;
}

static int
tc_base_fetch_locations(opengl_tex_converter_t *tc, GLuint program)
{
    if (tc->yuv_color)
    {
        tc->uloc.Coefficients = tc->api->GetUniformLocation(program,
                                                            "Coefficients");
        if (tc->uloc.Coefficients == -1)
            return VLC_EGENERIC;
    }

263
    for (unsigned int i = 0; i < tc->tex_count; ++i)
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    {
        char name[sizeof("TextureX")];
        snprintf(name, sizeof(name), "Texture%1u", i);
        tc->uloc.Texture[i] = tc->api->GetUniformLocation(program, name);
        if (tc->uloc.Texture[i] == -1)
            return VLC_EGENERIC;
    }

    tc->uloc.FillColor = tc->api->GetUniformLocation(program, "FillColor");
    if (tc->uloc.FillColor == -1)
        return VLC_EGENERIC;
    return VLC_SUCCESS;
}

static void
tc_base_prepare_shader(const opengl_tex_converter_t *tc,
                       const GLsizei *tex_width, const GLsizei *tex_height,
                       float alpha)
{
    (void) tex_width; (void) tex_height;

    if (tc->yuv_color)
        tc->api->Uniform4fv(tc->uloc.Coefficients, 4, tc->yuv_coefficients);

288
    for (unsigned i = 0; i < tc->tex_count; ++i)
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
        tc->api->Uniform1i(tc->uloc.Texture[i], i);

    tc->api->Uniform4f(tc->uloc.FillColor, 1.0f, 1.0f, 1.0f, alpha);
}

GLuint
opengl_fragment_shader_init(opengl_tex_converter_t *tc, GLenum tex_target,
                            vlc_fourcc_t chroma, video_color_space_t yuv_space)
{
    const char *swizzle_per_tex[PICTURE_PLANE_MAX] = { NULL, };
    const bool is_yuv = vlc_fourcc_IsYUV(chroma);
    bool yuv_swap_uv = false;
    int ret;
    if (is_yuv)
        ret = tc_yuv_base_init(tc, tex_target, chroma, yuv_space,
                               &yuv_swap_uv, swizzle_per_tex);
    else
        ret = tc_rgba_base_init(tc, tex_target, chroma);

    if (ret != VLC_SUCCESS)
        return 0;

    const char *sampler, *lookup, *coord_name;
    switch (tex_target)
    {
        case GL_TEXTURE_2D:
            sampler = "sampler2D";
            lookup  = "texture2D";
            coord_name = "TexCoord";
            break;
        default:
            vlc_assert_unreachable();
    }

    struct vlc_memstream ms;
    if (vlc_memstream_open(&ms) != 0)
        return 0;

#define ADD(x) vlc_memstream_puts(&ms, x)
#define ADDF(x, ...) vlc_memstream_printf(&ms, x, ##__VA_ARGS__)

    ADD("#version " GLSL_VERSION "\n" PRECISION);

332
    for (unsigned i = 0; i < tc->tex_count; ++i)
333 334 335 336 337 338 339 340 341 342 343
        ADDF("uniform %s Texture%u;"
             "varying vec2 TexCoord%u;", sampler, i, i);

    if (is_yuv)
        ADD("uniform vec4 Coefficients[4];");

    ADD("uniform vec4 FillColor;"
        "void main(void) {"
        "float val;vec4 colors;");

    unsigned color_idx = 0;
344
    for (unsigned i = 0; i < tc->tex_count; ++i)
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    {
        const char *swizzle = swizzle_per_tex[i];
        if (swizzle)
        {
            size_t swizzle_count = strlen(swizzle);
            ADDF("colors = %s(Texture%u, %s%u);", lookup, i, coord_name, i);
            for (unsigned j = 0; j < swizzle_count; ++j)
            {
                ADDF("val = colors.%c;"
                     "vec4 color%u = vec4(val, val, val, 1);",
                     swizzle[j], color_idx);
                color_idx++;
                assert(color_idx <= PICTURE_PLANE_MAX);
            }
        }
        else
        {
            ADDF("vec4 color%u = %s(Texture%u, %s%u);",
                 color_idx, lookup, i, coord_name, i);
            color_idx++;
            assert(color_idx <= PICTURE_PLANE_MAX);
        }
    }
    unsigned color_count = color_idx;
    assert(yuv_space == COLOR_SPACE_UNDEF || color_count == 3);

    if (is_yuv)
        ADD("vec4 result = (color0 * Coefficients[0]) + Coefficients[3];");
    else
        ADD("vec4 result = color0;");

    for (unsigned i = 1; i < color_count; ++i)
    {
        unsigned color_idx;
        if (yuv_swap_uv)
        {
            assert(color_count == 3);
            color_idx = (i % 2) + 1;
        }
        else
            color_idx = i;

        if (is_yuv)
            ADDF("result = (color%u * Coefficients[%u]) + result;", color_idx, i);
        else
            ADDF("result = color%u + result;", color_idx);
    }

    ADD("gl_FragColor = result * FillColor;"
        "}");

#undef ADD
#undef ADDF

    if (vlc_memstream_close(&ms) != 0)
        return 0;

    GLuint fragment_shader = tc->api->CreateShader(GL_FRAGMENT_SHADER);
    if (fragment_shader == 0)
    {
        free(ms.ptr);
        return 0;
    }
    GLint length = ms.length;
    tc->api->ShaderSource(fragment_shader, 1, (const char **)&ms.ptr, &length);
    tc->api->CompileShader(fragment_shader);
    free(ms.ptr);

    tc->tex_target = tex_target;

    tc->pf_fetch_locations = tc_base_fetch_locations;
    tc->pf_prepare_shader = tc_base_prepare_shader;

    return fragment_shader;
}

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
#ifdef VLCGL_HAS_PBO
static int
pbo_map(const opengl_tex_converter_t *tc, picture_t *pic)
{
    picture_sys_t *picsys = pic->p_sys;

    tc->api->GenBuffers(pic->i_planes, picsys->buffers);

    const GLbitfield access = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT |
                              GL_MAP_PERSISTENT_BIT;
    for (int i = 0; i < pic->i_planes; ++i)
    {
        tc->api->BindBuffer(GL_PIXEL_UNPACK_BUFFER, picsys->buffers[i]);
        tc->api->BufferStorage(GL_PIXEL_UNPACK_BUFFER, picsys->bytes[i], NULL,
                               access);

        pic->p[i].p_pixels =
            tc->api->MapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, picsys->bytes[i],
                                    access);

        if (pic->p[i].p_pixels == NULL)
        {
            msg_Err(tc->parent, "could not map PBO buffers");
            for (i = i - 1; i >= 0; --i)
            {
                tc->api->BindBuffer(GL_PIXEL_UNPACK_BUFFER,
                                    picsys->buffers[i]);
                tc->api->UnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
            }
            tc->api->DeleteBuffers(pic->i_planes, picsys->buffers);
            memset(picsys->buffers, 0, PICTURE_PLANE_MAX * sizeof(GLuint));
            return VLC_EGENERIC;
        }
    }
    return VLC_SUCCESS;
}

/** Find next (bit) set */
static int fnsll(unsigned long long x, unsigned i)
{
    if (i >= CHAR_BIT * sizeof (x))
        return 0;
    return ffsll(x & ~((1ULL << i) - 1));
}

static void
pbo_release_gpupics(const opengl_tex_converter_t *tc, bool force)
{
    struct priv *priv = tc->priv;

    /* Release all pictures that are not used by the GPU anymore */
    for (unsigned i = ffsll(priv->ongpu.list); i;
         i = fnsll(priv->ongpu.list, i))
    {
        assert(priv->ongpu.pics[i - 1] != NULL);

        picture_t *pic = priv->ongpu.pics[i - 1];
        picture_sys_t *picsys = pic->p_sys;

        assert(picsys->fence != NULL);
        GLenum wait = force ? GL_ALREADY_SIGNALED
                            : tc->api->ClientWaitSync(picsys->fence, 0, 0);

        if (wait == GL_ALREADY_SIGNALED || wait == GL_CONDITION_SATISFIED)
        {
            tc->api->DeleteSync(picsys->fence);
            picsys->fence = NULL;

            priv->ongpu.list &= ~(1ULL << (i - 1));
            priv->ongpu.pics[i - 1] = NULL;
            picture_Release(pic);
        }
    }
}

static int
pbo_common_update(const opengl_tex_converter_t *tc, const GLuint *textures,
498 499
                  const GLsizei *tex_width, const GLsizei *tex_height,
                  picture_t *pic)
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
{
    struct priv *priv = tc->priv;
    picture_sys_t *picsys = pic->p_sys;

    for (int i = 0; i < pic->i_planes; i++)
    {
        tc->api->BindBuffer(GL_PIXEL_UNPACK_BUFFER, picsys->buffers[i]);
        if (picsys->fence == NULL)
            tc->api->FlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, 0,
                                            picsys->bytes[i]);
        glActiveTexture(GL_TEXTURE0 + i);
        glClientActiveTexture(GL_TEXTURE0 + i);
        glBindTexture(tc->tex_target, textures[i]);

        glPixelStorei(GL_UNPACK_ROW_LENGTH,
                      pic->p[i].i_pitch / pic->p[i].i_pixel_pitch);

517
        glTexSubImage2D(tc->tex_target, 0, 0, 0, tex_width[i], tex_height[i],
518
                        tc->texs[i].format, tc->texs[i].type, NULL);
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
    }

    bool hold;
    if (picsys->fence == NULL)
        hold = true;
    else
    {
        /* The picture is already held */
        hold = false;
        tc->api->DeleteSync(picsys->fence);
    }

    picsys->fence = tc->api->FenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
    if (pic->p_sys->fence == NULL)
    {
        /* Error (corner case): don't hold the picture */
        hold = false;
    }

    pbo_release_gpupics(tc, false);

    if (hold)
    {
        /* Hold the picture while it's used by the GPU */
        unsigned index = pic->p_sys->index;

        priv->ongpu.list |= 1ULL << index;
        assert(priv->ongpu.pics[index] == NULL);
        priv->ongpu.pics[index] = pic;
        picture_Hold(pic);
    }

    /* turn off pbo */
    tc->api->BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);

    return VLC_SUCCESS;
}

static void
picture_destroy_cb(picture_t *pic)
{
    picture_sys_t *picsys = pic->p_sys;
    const opengl_tex_converter_t *tc = picsys->tc;

    if (picsys->buffers[0] != 0)
    {
        for (int i = 0; i < pic->i_planes; ++i)
        {
            tc->api->BindBuffer(GL_PIXEL_UNPACK_BUFFER, picsys->buffers[i]);
            tc->api->UnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
        }
        tc->api->DeleteBuffers(pic->i_planes, picsys->buffers);
    }
    free(picsys);
    free(pic);
}

static picture_pool_t *
tc_common_get_pool(const opengl_tex_converter_t *tc, const video_format_t *fmt,
578
                   unsigned requested_count, GLuint *textures)
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
{
    struct priv *priv = tc->priv;
    picture_t *pictures[VLCGL_PICTURE_MAX];
    unsigned count;
    (void) textures;

    priv->ongpu.list = 0;

    for (count = 0; count < requested_count; count++)
    {
        picture_sys_t *picsys = calloc(1, sizeof(*picsys));
        if (unlikely(picsys == NULL))
            break;
        picsys->tc = tc;
        picsys->index = count;
        picture_resource_t rsc = {
            .p_sys = picsys,
            .pf_destroy = picture_destroy_cb,
        };

        picture_t *pic = pictures[count] = picture_NewFromResource(fmt, &rsc);
        if (pic == NULL)
        {
            free(picsys);
            break;
        }
        if (picture_Setup(pic, fmt))
        {
            picture_Release(pic);
            break;
        }

        assert(pic->i_planes > 0
612
            && (unsigned) pic->i_planes == tc->tex_count);
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

        for (int i = 0; i < pic->i_planes; ++i)
        {
            const plane_t *p = &pic->p[i];

            if( p->i_pitch < 0 || p->i_lines <= 0 ||
                (size_t)p->i_pitch > SIZE_MAX/p->i_lines )
                goto error;
            picsys->bytes[i] = (p->i_pitch * p->i_lines) + 15 / 16 * 16;
            assert(picsys->bytes[i] == pictures[0]->p_sys->bytes[i]);
        }

        if (pbo_map(tc, pic) != VLC_SUCCESS)
        {
            picture_Release(pic);
            break;
        }
    }

    /* We need minumum 2 pbo buffers */
    if (count <= 1)
        goto error;

    /* turn off pbo */
    tc->api->BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);

    /* Wrap the pictures into a pool */
    picture_pool_t *pool = picture_pool_New(count, pictures);
    if (!pool)
        goto error;
    return pool;

error:
    for (unsigned i = 0; i < count; i++)
        picture_Release(pictures[i]);

    return NULL;
}
#endif /* VLCGL_HAS_PBO */

653
static int
654 655 656
tc_common_allocate_texture(const opengl_tex_converter_t *tc, GLuint texture,
                           unsigned tex_idx, const GLsizei tex_width,
                           const GLsizei tex_height)
657
{
658
    (void) texture;
659

660 661 662
    glTexImage2D(tc->tex_target, 0, tc->texs[tex_idx].internal,
                 tex_width, tex_height, 0, tc->texs[tex_idx].format,
                 tc->texs[tex_idx].type, NULL);
663 664 665 666
    return VLC_SUCCESS;
}

static int
667
upload_plane(const opengl_tex_converter_t *tc, unsigned tex_idx,
668
             GLsizei width, GLsizei height,
669 670 671
             unsigned pitch, unsigned pixel_pitch, const void *pixels)
{
    struct priv *priv = tc->priv;
672 673
    GLenum tex_format = tc->texs[tex_idx].format;
    GLenum tex_type = tc->texs[tex_idx].type;
674 675 676 677

    /* This unpack alignment is the default, but setting it just in case. */
    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

678
    if (!priv->has_unpack_subimage)
679
    {
680 681 682 683
#define ALIGN(x, y) (((x) + ((y) - 1)) & ~((y) - 1))
        unsigned dst_width = width;
        unsigned dst_pitch = ALIGN(dst_width * pixel_pitch, 4);
        if (pitch != dst_pitch)
684
        {
685 686 687 688
            size_t buf_size = dst_pitch * height * pixel_pitch;
            const uint8_t *source = pixels;
            uint8_t *destination;
            if (priv->texture_temp_buf_size < buf_size)
689
            {
690 691 692 693 694 695 696 697
                priv->texture_temp_buf =
                    realloc_or_free(priv->texture_temp_buf, buf_size);
                if (priv->texture_temp_buf == NULL)
                {
                    priv->texture_temp_buf_size = 0;
                    return VLC_ENOMEM;
                }
                priv->texture_temp_buf_size = buf_size;
698
            }
699
            destination = priv->texture_temp_buf;
700

701
            for (GLsizei h = 0; h < height ; h++)
702 703 704 705 706
            {
                memcpy(destination, source, width * pixel_pitch);
                source += pitch;
                destination += dst_pitch;
            }
707
            glTexSubImage2D(tc->tex_target, 0, 0, 0, width, height,
708 709 710
                            tex_format, tex_type, priv->texture_temp_buf);
        }
        else
711
        {
712
            glTexSubImage2D(tc->tex_target, 0, 0, 0, width, height,
713
                            tex_format, tex_type, pixels);
714
        }
715 716 717
#undef ALIGN
    }
    else
718 719
    {
        glPixelStorei(GL_UNPACK_ROW_LENGTH, pitch / pixel_pitch);
720
        glTexSubImage2D(tc->tex_target, 0, 0, 0, width, height,
721 722 723 724 725 726
                        tex_format, tex_type, pixels);
    }
    return VLC_SUCCESS;
}

static int
727
tc_common_update(const opengl_tex_converter_t *tc, GLuint *textures,
728
                 const GLsizei *tex_width, const GLsizei *tex_height,
729
                 picture_t *pic, const size_t *plane_offset)
730
{
731 732
#ifdef VLCGL_HAS_PBO
    if (pic->p_sys != NULL)
733
        return pbo_common_update(tc, textures, tex_width, tex_height, pic);
734 735
#endif

736
    int ret = VLC_SUCCESS;
737
    for (unsigned i = 0; i < tc->tex_count && ret == VLC_SUCCESS; i++)
738
    {
739
        assert(textures[i] != 0);
740 741 742 743 744 745 746
        glActiveTexture(GL_TEXTURE0 + i);
        glClientActiveTexture(GL_TEXTURE0 + i);
        glBindTexture(tc->tex_target, textures[i]);
        const void *pixels = plane_offset != NULL ?
                             &pic->p[i].p_pixels[plane_offset[i]] :
                             pic->p[i].p_pixels;

747
        ret = upload_plane(tc, i, tex_width[i], tex_height[i],
748 749 750 751 752 753 754 755 756 757
                           pic->p[i].i_pitch, pic->p[i].i_pixel_pitch, pixels);
    }
    return ret;
}

static void
tc_common_release(const opengl_tex_converter_t *tc)
{
    struct priv *priv = tc->priv;
    free(priv->texture_temp_buf);
758

759 760 761 762
#ifdef VLCGL_HAS_PBO
    pbo_release_gpupics(tc, true);
#endif

763 764 765 766
    free(tc->priv);
}

static int
767
common_init(opengl_tex_converter_t *tc)
768
{
769
    struct priv *priv = tc->priv = calloc(1, sizeof(struct priv));
770 771 772 773 774
    if (unlikely(priv == NULL))
        return VLC_ENOMEM;

    tc->pf_update       = tc_common_update;
    tc->pf_release      = tc_common_release;
775
    tc->pf_allocate_texture = tc_common_allocate_texture;
776

777 778 779 780 781 782 783 784 785
#ifdef VLCGL_HAS_PBO
    const bool supports_pbo = tc->api->BufferStorage
        && tc->api->MapBufferRange && tc->api->FlushMappedBufferRange
        && tc->api->UnmapBuffer && tc->api->FenceSync && tc->api->DeleteSync
        && tc->api->ClientWaitSync
        && HasExtension(tc->glexts, "GL_ARB_pixel_buffer_object")
        && HasExtension(tc->glexts, "GL_ARB_buffer_storage");
    if (supports_pbo)
        tc->pf_get_pool = tc_common_get_pool;
786 787
    msg_Dbg(tc->parent, "PBO support (direct rendering): %s",
            supports_pbo ? "On" : "Off");
788 789
#endif

790 791 792 793 794 795 796
#ifdef NEED_GL_EXT_unpack_subimage
    priv->has_unpack_subimage = HasExtension(tc->glexts,
                                             "GL_EXT_unpack_subimage");
#else
    priv->has_unpack_subimage = true;
#endif

797 798 799
    return VLC_SUCCESS;
}

800
GLuint
801 802
opengl_tex_converter_generic_init(const video_format_t *fmt,
                                  opengl_tex_converter_t *tc)
803
{
804 805
    GLuint fragment_shader = 0;
    if (vlc_fourcc_IsYUV(fmt->i_chroma))
806
    {
807 808 809 810
        GLint max_texture_units = 0;
        glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_texture_units);
        if (max_texture_units < 3)
            return 0;
811

812 813
        const vlc_fourcc_t *list = vlc_fourcc_GetYUVFallback(fmt->i_chroma);
        while (*list && fragment_shader == 0)
814
        {
815 816 817 818
            fragment_shader =
                opengl_fragment_shader_init(tc, GL_TEXTURE_2D, *list,
                                            fmt->space);
            list++;
819
        }
820 821
        if (fragment_shader == 0)
            return 0;
822
    }
823
    else
824 825 826 827 828 829 830
    {
        fragment_shader =
            opengl_fragment_shader_init(tc, GL_TEXTURE_2D, fmt->i_chroma,
                                       COLOR_SPACE_UNDEF);
        if (fragment_shader == 0)
            return 0;
    }
831

832
    if (common_init(tc) != VLC_SUCCESS)
833
    {
834
        tc->api->DeleteShader(fragment_shader);
835
        return 0;
836 837
    }

838
    return fragment_shader;
839 840
}

841
static int
842
tc_xyz12_fetch_locations(opengl_tex_converter_t *tc, GLuint program)
843
{
844 845
    tc->uloc.Texture[0] = tc->api->GetUniformLocation(program, "Texture0");
    return tc->uloc.Texture[0] != -1 ? VLC_SUCCESS : VLC_EGENERIC;
846 847
}

848
static void
849 850 851
tc_xyz12_prepare_shader(const opengl_tex_converter_t *tc,
                        const GLsizei *tex_width, const GLsizei *tex_height,
                        float alpha)
852
{
853
    (void) tex_width; (void) tex_height; (void) alpha;
854
    tc->api->Uniform1i(tc->uloc.Texture[0], 0);
855 856
}

857
GLuint
858 859 860 861
opengl_tex_converter_xyz12_init(const video_format_t *fmt,
                                opengl_tex_converter_t *tc)
{
    if (fmt->i_chroma != VLC_CODEC_XYZ12)
862
        return 0;
863

864
    tc->chroma  = VLC_CODEC_XYZ12;
865
    tc->tex_count = 1;
866 867
    tc->tex_target = GL_TEXTURE_2D;
    tc->texs[0] = (struct opengl_tex_cfg) {
868
        { 1, 1 }, { 1, 1 }, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT
869
    };
870

871
    tc->pf_fetch_locations = tc_xyz12_fetch_locations;
872 873
    tc->pf_prepare_shader = tc_xyz12_prepare_shader;

874 875 876
    if (common_init(tc) != VLC_SUCCESS)
        return 0;

877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
    /* Shader for XYZ to RGB correction
     * 3 steps :
     *  - XYZ gamma correction
     *  - XYZ to RGB matrix conversion
     *  - reverse RGB gamma correction
     */
    static const char *code =
        "#version " GLSL_VERSION "\n"
        PRECISION
        "uniform sampler2D Texture0;"
        "uniform vec4 xyz_gamma = vec4(2.6);"
        "uniform vec4 rgb_gamma = vec4(1.0/2.2);"
        /* WARN: matrix Is filled column by column (not row !) */
        "uniform mat4 matrix_xyz_rgb = mat4("
        "    3.240454 , -0.9692660, 0.0556434, 0.0,"
        "   -1.5371385,  1.8760108, -0.2040259, 0.0,"
        "    -0.4985314, 0.0415560, 1.0572252,  0.0,"
        "    0.0,      0.0,         0.0,        1.0 "
        " );"

897
        "varying vec2 TexCoord0;"
898 899 900
        "void main()"
        "{ "
        " vec4 v_in, v_out;"
901
        " v_in  = texture2D(Texture0, TexCoord0);"
902 903 904 905 906 907 908
        " v_in = pow(v_in, xyz_gamma);"
        " v_out = matrix_xyz_rgb * v_in ;"
        " v_out = pow(v_out, rgb_gamma) ;"
        " v_out = clamp(v_out, 0.0, 1.0) ;"
        " gl_FragColor = v_out;"
        "}";

909 910
    GLuint fragment_shader = tc->api->CreateShader(GL_FRAGMENT_SHADER);
    if (fragment_shader == 0)
911
    {
912
        tc_common_release(tc);
913
        return 0;
914
    }
915 916 917
    tc->api->ShaderSource(fragment_shader, 1, &code, NULL);
    tc->api->CompileShader(fragment_shader);
    return fragment_shader;
918
}