summaryrefslogtreecommitdiffstats
path: root/video/out/gl_common.c
blob: 49fd078f6c7c8f0d01f08c633e8a4a7c1e31c767 (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
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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
578
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
612
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
/*
 * common OpenGL routines
 *
 * copyleft (C) 2005-2010 Reimar Döffinger <Reimar.Doeffinger@gmx.de>
 * Special thanks go to the xine team and Matthias Hopf, whose video_out_opengl.c
 * gave me lots of good ideas.
 *
 * This file is part of MPlayer.
 *
 * MPlayer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * MPlayer 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * You can alternatively redistribute this file 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.
 */

/**
 * \file gl_common.c
 * \brief OpenGL helper functions used by vo_gl.c and vo_gl2.c
 */

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include <assert.h>
#include "talloc.h"
#include "gl_common.h"
#include "common/common.h"
#include "options/options.h"
#include "options/m_option.h"

//! \defgroup glgeneral OpenGL general helper functions

// GLU has this as gluErrorString (we don't use GLU, as it is legacy-OpenGL)
static const char *gl_error_to_string(GLenum error)
{
    switch (error) {
    case GL_INVALID_ENUM: return "INVALID_ENUM";
    case GL_INVALID_VALUE: return "INVALID_VALUE";
    case GL_INVALID_OPERATION: return "INVALID_OPERATION";
    case GL_INVALID_FRAMEBUFFER_OPERATION:
        return "INVALID_FRAMEBUFFER_OPERATION";
    case GL_OUT_OF_MEMORY: return "OUT_OF_MEMORY";
    default: return "unknown";
    }
}

void glCheckError(GL *gl, struct mp_log *log, const char *info)
{
    for (;;) {
        GLenum error = gl->GetError();
        if (error == GL_NO_ERROR)
            break;
        mp_msg(log, MSGL_ERR, "%s: OpenGL error %s.\n", info,
               gl_error_to_string(error));
    }
}

//! \defgroup glcontext OpenGL context management helper functions

//! \defgroup gltexture OpenGL texture handling helper functions

//! \defgroup glconversion OpenGL conversion helper functions

/**
 * \brief adjusts the GL_UNPACK_ALIGNMENT to fit the stride.
 * \param stride number of bytes per line for which alignment should fit.
 * \ingroup glgeneral
 */
void glAdjustAlignment(GL *gl, int stride)
{
    GLint gl_alignment;
    if (stride % 8 == 0)
        gl_alignment = 8;
    else if (stride % 4 == 0)
        gl_alignment = 4;
    else if (stride % 2 == 0)
        gl_alignment = 2;
    else
        gl_alignment = 1;
    gl->PixelStorei(GL_UNPACK_ALIGNMENT, gl_alignment);
    gl->PixelStorei(GL_PACK_ALIGNMENT, gl_alignment);
}

struct feature {
    int id;
    const char *name;
};

static const struct feature features[] = {
    {MPGL_CAP_GL,               "Basic OpenGL"},
    {MPGL_CAP_GL_LEGACY,        "Legacy OpenGL"},
    {MPGL_CAP_GL2,              "OpenGL 2.0"},
    {MPGL_CAP_GL21,             "OpenGL 2.1"},
    {MPGL_CAP_GL3,              "OpenGL 3.0"},
    {MPGL_CAP_FB,               "Framebuffers"},
    {MPGL_CAP_VAO,              "VAOs"},
    {MPGL_CAP_SRGB_TEX,         "sRGB textures"},
    {MPGL_CAP_SRGB_FB,          "sRGB framebuffers"},
    {MPGL_CAP_FLOAT_TEX,        "Float textures"},
    {MPGL_CAP_TEX_RG,           "RG textures"},
    {MPGL_CAP_NO_SW,            "NO_SW"},
    {0},
};

static void list_features(int set, struct mp_log *log, int msgl, bool invert)
{
    char b[1024] = {0};
    for (const struct feature *f = &features[0]; f->id; f++) {
        if (invert == !(f->id & set))
            mp_snprintf_cat(b, sizeof(b), " [%s]", f->name);
    }
    mp_msg(log, msgl, "%s\n", b);
}

// This guesses if the current GL context is a suspected software renderer.
static bool is_software_gl(GL *gl)
{
    const char *renderer = gl->GetString(GL_RENDERER);
    const char *vendor = gl->GetString(GL_VENDOR);
    return !(renderer && vendor) ||
           strcmp(renderer, "Software Rasterizer") == 0 ||
           strstr(renderer, "llvmpipe") ||
           strcmp(vendor, "Microsoft Corporation") == 0 ||
           strcmp(renderer, "Mesa X11") == 0;
}

#define FN_OFFS(name) offsetof(GL, name)

#define DEF_FN(name)            {FN_OFFS(name), {"gl" # name}}
#define DEF_FN_NAMES(name, ...) {FN_OFFS(name), {__VA_ARGS__}}

struct gl_function {
    ptrdiff_t offset;
    char *funcnames[7];
};

struct gl_functions {
    const char *extension;      // introduced with this extension in any version
    int provides;               // bitfield of MPGL_CAP_* constants
    int ver_core;               // introduced as required function
    int ver_removed;            // removed as required function (no replacement)
    bool partial_ok;            // loading only some functions is ok
    const struct gl_function *functions;
};

#define MAX_FN_COUNT 50         // max functions per gl_functions section

static const struct gl_functions gl_functions[] = {
    // GL functions which are always available anywhere at least since 1.1
    {
        .ver_core = MPGL_VER(1, 1),
        .provides = MPGL_CAP_GL,
        .functions = (const struct gl_function[]) {
            DEF_FN(Viewport),
            DEF_FN(Clear),
            DEF_FN(GenTextures),
            DEF_FN(DeleteTextures),
            DEF_FN(TexEnvi),
            DEF_FN(ClearColor),
            DEF_FN(Enable),
            DEF_FN(Disable),
            DEF_FN(DrawBuffer),
            DEF_FN(DepthMask),
            DEF_FN(BlendFunc),
            DEF_FN(Flush),
            DEF_FN(Finish),
            DEF_FN(PixelStorei),
            DEF_FN(TexImage1D),
            DEF_FN(TexImage2D),
            DEF_FN(TexSubImage2D),
            DEF_FN(GetTexImage),
            DEF_FN(TexParameteri),
            DEF_FN(TexParameterf),
            DEF_FN(TexParameterfv),
            DEF_FN(GetIntegerv),
            DEF_FN(GetBooleanv),
            DEF_FN(ColorMask),
            DEF_FN(ReadPixels),
            DEF_FN(ReadBuffer),
            DEF_FN(DrawArrays),
            DEF_FN(GetString),
            DEF_FN(GetError),
            DEF_FN(GetTexLevelParameteriv),
            {0}
        },
    },
    // GL 2.0-3.x functions
    {
        .ver_core = MPGL_VER(2, 0),
        .provides = MPGL_CAP_GL2,
        .functions = (const struct gl_function[]) {
            DEF_FN(GenBuffers),
            DEF_FN(DeleteBuffers),
            DEF_FN(BindBuffer),
            DEF_FN(MapBuffer),
            DEF_FN(UnmapBuffer),
            DEF_FN(BufferData),
            DEF_FN(ActiveTexture),
            DEF_FN(BindTexture),
            DEF_FN(GetAttribLocation),
            DEF_FN(EnableVertexAttribArray),
            DEF_FN(DisableVertexAttribArray),
            DEF_FN(VertexAttribPointer),
            DEF_FN(UseProgram),
            DEF_FN(GetUniformLocation),
            DEF_FN(CompileShader),
            DEF_FN(CreateProgram),
            DEF_FN(CreateShader),
            DEF_FN(ShaderSource),
            DEF_FN(LinkProgram),
            DEF_FN(AttachShader),
            DEF_FN(DeleteShader),
            DEF_FN(DeleteProgram),
            DEF_FN(GetShaderInfoLog),
            DEF_FN(GetShaderiv),
            DEF_FN(GetProgramInfoLog),
            DEF_FN(GetProgramiv),
            DEF_FN(BindAttribLocation),
            DEF_FN(Uniform1f),
            DEF_FN(Uniform2f),
            DEF_FN(Uniform3f),
            DEF_FN(Uniform1i),
            DEF_FN(UniformMatrix2fv),
            DEF_FN(UniformMatrix3fv),
            DEF_FN(TexImage3D),
            // Added in OpenGL 1.4, but vo_opengl_old doesn't need it
            DEF_FN(BlendFuncSeparate),
            {0},
        },
    },
    // GL 2.1-3.x functions (also: GLSL 120 shaders)
    {
        .ver_core = MPGL_VER(2, 1),
        .provides = MPGL_CAP_GL21,
        .functions = (const struct gl_function[]) {
            DEF_FN(UniformMatrix4x3fv),
            {0}
        },
    },
    // GL 3.x core only functions.
    {
        .ver_core = MPGL_VER(3, 0),
        .provides = MPGL_CAP_GL3 | MPGL_CAP_SRGB_TEX | MPGL_CAP_SRGB_FB,
        .functions = (const struct gl_function[]) {
            DEF_FN(GetStringi),
            {0}
        },
    },
    // Framebuffers, extension in GL 2.x, core in GL 3.x core.
    {
        .ver_core = MPGL_VER(3, 0),
        .extension = "GL_ARB_framebuffer_object",
        .provides = MPGL_CAP_FB,
        .functions = (const struct gl_function[]) {
            DEF_FN(BindFramebuffer),
            DEF_FN(GenFramebuffers),
            DEF_FN(DeleteFramebuffers),
            DEF_FN(CheckFramebufferStatus),
            DEF_FN(FramebufferTexture2D),
            {0}
        },
    },
    // Framebuffers, alternative extension name.
    {
        .ver_removed = MPGL_VER(3, 0), // don't touch these fn names in 3.x
        .extension = "GL_EXT_framebuffer_object",
        .provides = MPGL_CAP_FB,
        .functions = (const struct gl_function[]) {
            DEF_FN_NAMES(BindFramebuffer, "glBindFramebufferEXT"),
            DEF_FN_NAMES(GenFramebuffers, "glGenFramebuffersEXT"),
            DEF_FN_NAMES(DeleteFramebuffers, "glDeleteFramebuffersEXT"),
            DEF_FN_NAMES(CheckFramebufferStatus, "glCheckFramebufferStatusEXT"),
            DEF_FN_NAMES(FramebufferTexture2D, "glFramebufferTexture2DEXT"),
            {0}
        },
    },
    // VAOs, extension in GL 2.x, core in GL 3.x core.
    {
        .ver_core = MPGL_VER(3, 0),
        .extension = "GL_ARB_vertex_array_object",
        .provides = MPGL_CAP_VAO,
        .functions = (const struct gl_function[]) {
            DEF_FN(GenVertexArrays),
            DEF_FN(BindVertexArray),
            DEF_FN(DeleteVertexArrays),
            {0}
        }
    },
    // sRGB textures, extension in GL 2.x, core in GL 3.x core.
    {
        .ver_core = MPGL_VER(3, 0),
        .extension = "GL_EXT_texture_sRGB",
        .provides = MPGL_CAP_SRGB_TEX,
        .functions = (const struct gl_function[]) {{0}},
    },
    // sRGB framebuffers, extension in GL 2.x, core in GL 3.x core.
    {
        .ver_core = MPGL_VER(3, 0),
        .extension = "GL_EXT_framebuffer_sRGB",
        .provides = MPGL_CAP_SRGB_FB,
        .functions = (const struct gl_function[]) {{0}},
    },
    // Float textures, extension in GL 2.x, core in GL 3.x core.
    {
        .ver_core = MPGL_VER(3, 0),
        .extension = "GL_ARB_texture_float",
        .provides = MPGL_CAP_FLOAT_TEX,
        .functions = (const struct gl_function[]) {{0}},
    },
    // GL_RED / GL_RG textures, extension in GL 2.x, core in GL 3.x core.
    {
        .ver_core = MPGL_VER(3, 0),
        .extension = "GL_ARB_texture_rg",
        .provides = MPGL_CAP_TEX_RG,
        .functions = (const struct gl_function[]) {{0}},
    },
    // Swap control, always an OS specific extension
    {
        .extension = "_swap_control",
        .functions = (const struct gl_function[]) {
            DEF_FN_NAMES(SwapInterval, "glXSwapIntervalSGI", "glXSwapInterval",
                         "wglSwapIntervalSGI", "wglSwapInterval",
                         "wglSwapIntervalEXT"),
            {0}
        },
    },
    {
        .extension = "GLX_SGI_video_sync",
        .functions = (struct gl_function[]) {
            DEF_FN_NAMES(GetVideoSync, "glXGetVideoSyncSGI"),
            DEF_FN_NAMES(WaitVideoSync, "glXWaitVideoSyncSGI"),
            {0},
        },
    },
    // GL legacy functions in GL 1.x - 2.x, removed from GL 3.x
    {
        .ver_core = MPGL_VER(1, 1),
        .ver_removed = MPGL_VER(3, 0),
        .provides = MPGL_CAP_GL_LEGACY,
        .functions = (const struct gl_function[]) {
            DEF_FN(Begin),
            DEF_FN(End),
            DEF_FN(MatrixMode),
            DEF_FN(LoadIdentity),
            DEF_FN(Translated),
            DEF_FN(Scaled),
            DEF_FN(Ortho),
            DEF_FN(PushMatrix),
            DEF_FN(PopMatrix),
            DEF_FN(GenLists),
            DEF_FN(DeleteLists),
            DEF_FN(NewList),
            DEF_FN(EndList),
            DEF_FN(CallList),
            DEF_FN(CallLists),
            DEF_FN(Color4ub),
            DEF_FN(Color4f),
            DEF_FN(TexCoord2f),
            DEF_FN(TexCoord2fv),
            DEF_FN(Vertex2f),
            DEF_FN(VertexPointer),
            DEF_FN(ColorPointer),
            DEF_FN(TexCoordPointer),
            DEF_FN(EnableClientState),
            DEF_FN(DisableClientState),
            {0}
        },
    },
    // Loading of old extensions, which are later added to GL 2.0.
    // NOTE: actually we should be checking the extension strings: the OpenGL
    //       library could provide an entry point, but not implement it.
    //       But the previous code didn't do that, and nobody ever complained.
    {
        .ver_removed = MPGL_VER(2, 1),
        .partial_ok = true,
        .functions = (const struct gl_function[]) {
            DEF_FN_NAMES(GenBuffers, "glGenBuffers", "glGenBuffersARB"),
            DEF_FN_NAMES(DeleteBuffers, "glDeleteBuffers", "glDeleteBuffersARB"),
            DEF_FN_NAMES(BindBuffer, "glBindBuffer", "glBindBufferARB"),
            DEF_FN_NAMES(MapBuffer, "glMapBuffer", "glMapBufferARB"),
            DEF_FN_NAMES(UnmapBuffer, "glUnmapBuffer", "glUnmapBufferARB"),
            DEF_FN_NAMES(BufferData, "glBufferData", "glBufferDataARB"),
            DEF_FN_NAMES(ActiveTexture, "glActiveTexture", "glActiveTextureARB"),
            DEF_FN_NAMES(BindTexture, "glBindTexture", "glBindTextureARB", "glBindTextureEXT"),
            DEF_FN_NAMES(MultiTexCoord2f, "glMultiTexCoord2f", "glMultiTexCoord2fARB"),
            DEF_FN_NAMES(TexImage3D, "glTexImage3D"),
            {0}
        },
    },
    // Ancient ARB shaders.
    {
        .extension = "_program",
        .ver_removed = MPGL_VER(3, 0),
        .functions = (const struct gl_function[]) {
            DEF_FN_NAMES(GenPrograms, "glGenProgramsARB"),
            DEF_FN_NAMES(DeletePrograms, "glDeleteProgramsARB"),
            DEF_FN_NAMES(BindProgram, "glBindProgramARB"),
            DEF_FN_NAMES(ProgramString, "glProgramStringARB"),
            DEF_FN_NAMES(GetProgramivARB, "glGetProgramivARB"),
            DEF_FN_NAMES(ProgramEnvParameter4f, "glProgramEnvParameter4fARB"),
            {0}
        },
    },
    // Ancient ATI extensions.
    {
        .extension = "ATI_fragment_shader",
        .ver_removed = MPGL_VER(3, 0),
        .functions = (const struct gl_function[]) {
            DEF_FN_NAMES(BeginFragmentShader, "glBeginFragmentShaderATI"),
            DEF_FN_NAMES(EndFragmentShader, "glEndFragmentShaderATI"),
            DEF_FN_NAMES(SampleMap, "glSampleMapATI"),
            DEF_FN_NAMES(ColorFragmentOp2, "glColorFragmentOp2ATI"),
            DEF_FN_NAMES(ColorFragmentOp3, "glColorFragmentOp3ATI"),
            DEF_FN_NAMES(SetFragmentShaderConstant, "glSetFragmentShaderConstantATI"),
            {0}
        },
    },
    // For gl_hwdec_vdpau.c
    // http://www.opengl.org/registry/specs/NV/vdpau_interop.txt
    {
        .extension = "GL_NV_vdpau_interop",
        .provides = MPGL_CAP_VDPAU,
        .functions = (const struct gl_function[]) {
            // (only functions needed by us)
            DEF_FN(VDPAUInitNV),
            DEF_FN(VDPAUFiniNV),
            DEF_FN(VDPAURegisterOutputSurfaceNV),
            DEF_FN(VDPAUUnregisterSurfaceNV),
            DEF_FN(VDPAUSurfaceAccessNV),
            DEF_FN(VDPAUMapSurfacesNV),
            DEF_FN(VDPAUUnmapSurfacesNV),
            {0}
        },
    },
    // Apple Packed YUV Formats
    // For gl_hwdec_vda.c
    // http://www.opengl.org/registry/specs/APPLE/rgb_422.txt
    {
        .extension = "GL_APPLE_rgb_422",
        .provides = MPGL_CAP_APPLE_RGB_422,
        .functions = (const struct gl_function[]) {
            {0}
        },
    },
};

#undef FN_OFFS
#undef DEF_FN_HARD
#undef DEF_FN
#undef DEF_FN_NAMES


// Fill the GL struct with function pointers and extensions from the current
// GL context. Called by the backend.
// getProcAddress: function to resolve function names, may be NULL
// ext2: an extra extension string
// log: used to output messages
// Note: if you create a CONTEXT_FORWARD_COMPATIBLE_BIT_ARB with OpenGL 3.0,
//       you must append "GL_ARB_compatibility" to ext2.
void mpgl_load_functions(GL *gl, void *(*getProcAddress)(const GLubyte *),
                         const char *ext2, struct mp_log *log)
{
    talloc_free_children(gl);
    *gl = (GL) {
        .extensions = talloc_strdup(gl, ext2 ? ext2 : ""),
    };

    gl->GetString = getProcAddress ? getProcAddress("glGetString") : NULL;
    if (!gl->GetString) {
        mp_err(log, "Can't load OpenGL functions.\n");
        return;
    }

    int major = 0, minor = 0;
    const char *version = gl->GetString(GL_VERSION);
    sscanf(version, "%d.%d", &major, &minor);
    gl->version = MPGL_VER(major, minor);
    mp_verbose(log, "Detected OpenGL %d.%d.\n", major, minor);

    mp_verbose(log, "GL_VENDOR='%s'\n",   gl->GetString(GL_VENDOR));
    mp_verbose(log, "GL_RENDERER='%s'\n", gl->GetString(GL_RENDERER));
    mp_verbose(log, "GL_VERSION='%s'\n",  gl->GetString(GL_VERSION));
    const char *shader = gl->GetString(GL_SHADING_LANGUAGE_VERSION);
    if (shader)
        mp_verbose(log, "GL_SHADING_LANGUAGE_VERSION='%s'\n", shader);

    // Note: This code doesn't handle CONTEXT_FORWARD_COMPATIBLE_BIT_ARB
    //       on OpenGL 3.0 correctly. Apparently there's no way to detect this
    //       situation, because GL_ARB_compatibility is specified only for 3.1
    //       and above.

    bool has_legacy = false;
    if (gl->version >= MPGL_VER(3, 0)) {
        gl->GetStringi = getProcAddress("glGetStringi");
        gl->GetIntegerv = getProcAddress("glGetIntegerv");

        if (!(gl->GetStringi && gl->GetIntegerv))
            return;

        GLint exts;
        gl->GetIntegerv(GL_NUM_EXTENSIONS, &exts);
        for (int n = 0; n < exts; n++) {
            const char *ext = gl->GetStringi(GL_EXTENSIONS, n);
            gl->extensions = talloc_asprintf_append(gl->extensions, " %s", ext);
            if (strcmp(ext, "GL_ARB_compatibility") == 0)
                has_legacy = true;
        }

        // This version doesn't have GL_ARB_compatibility yet, and always
        // includes legacy (except with CONTEXT_FORWARD_COMPATIBLE_BIT_ARB).
        if (gl->version == MPGL_VER(3, 0))
            has_legacy = true;
    } else {
        const char *ext = (char*)gl->GetString(GL_EXTENSIONS);
        gl->extensions = talloc_asprintf_append(gl->extensions, " %s", ext);

        has_legacy = true;
    }

    if (has_legacy)
        mp_verbose(log, "OpenGL legacy compat. found.\n");
    mp_dbg(log, "Combined OpenGL extensions string:\n%s\n", gl->extensions);

    for (int n = 0; n < sizeof(gl_functions) / sizeof(gl_functions[0]); n++) {
        const struct gl_functions *section = &gl_functions[n];

        // With has_legacy, the legacy functions are still available, and
        // functions are never actually removed. (E.g. the context could be at
        // version >= 3.0, but functions like glBegin still exist and work.)
        if (!has_legacy && section->ver_removed &&
            gl->version >= section->ver_removed)
            continue;

        // NOTE: Function entrypoints can exist, even if they do not work.
        //       We must always check extension strings and versions.

        bool exists = false;
        if (section->ver_core)
            exists = gl->version >= section->ver_core;

        if (section->extension && strstr(gl->extensions, section->extension))
            exists = true;

        if (section->partial_ok)
            exists = true; // possibly

        if (!exists)
            continue;

        void *loaded[MAX_FN_COUNT] = {0};
        bool all_loaded = true;

        for (int i = 0; section->functions[i].funcnames[0]; i++) {
            const struct gl_function *fn = &section->functions[i];
            void *ptr = NULL;
            for (int x = 0; fn->funcnames[x]; x++) {
                ptr = getProcAddress((const GLubyte *)fn->funcnames[x]);
                if (ptr)
                    break;
            }
            if (!ptr) {
                all_loaded = false;
                if (!section->partial_ok) {
                    mp_msg(log, MSGL_V, "Required function '%s' not "
                           "found for %s/%d.%d.\n", fn->funcnames[0],
                           section->extension ? section->extension : "native",
                           MPGL_VER_GET_MAJOR(section->ver_core),
                           MPGL_VER_GET_MINOR(section->ver_core));
                    break;
                }
            }
            assert(i < MAX_FN_COUNT);
            loaded[i] = ptr;
        }

        if (all_loaded || section->partial_ok) {
            gl->mpgl_caps |= section->provides;
            for (int i = 0; section->functions[i].funcnames[0]; i++) {
                const struct gl_function *fn = &section->functions[i];
                void **funcptr = (void**)(((char*)gl) + fn->offset);
                if (loaded[i])
                    *funcptr = loaded[i];
            }
        }
    }

    gl->glsl_version = 0;
    if (gl->version >= MPGL_VER(2, 0))
        gl->glsl_version = 110;
    if (gl->version >= MPGL_VER(2, 1))
        gl->glsl_version = 120;
    if (gl->version >= MPGL_VER(3, 0))
        gl->glsl_version = 130;
    // Specifically needed for OSX (normally we request 3.0 contexts only, but
    // OSX always creates 3.2 contexts when requesting a core context).
    if (gl->version >= MPGL_VER(3, 2))
        gl->glsl_version = 150;

    if (!is_software_gl(gl))
        gl->mpgl_caps |= MPGL_CAP_NO_SW;

    mp_verbose(log, "Detected OpenGL features:");
    list_features(gl->mpgl_caps, log, MSGL_V, false);
}

/**
 * \brief return the number of bytes per pixel for the given format
 * \param format OpenGL format
 * \param type OpenGL type
 * \return bytes per pixel
 * \ingroup glgeneral
 *
 * Does not handle all possible variants, just those used by MPlayer
 */
int glFmt2bpp(GLenum format, GLenum type)
{
    int component_size = 0;
    switch (type) {
    case GL_UNSIGNED_BYTE_3_3_2:
    case GL_UNSIGNED_BYTE_2_3_3_REV:
        return 1;
    case GL_UNSIGNED_SHORT_5_5_5_1:
    case GL_UNSIGNED_SHORT_1_5_5_5_REV:
    case GL_UNSIGNED_SHORT_5_6_5:
    case GL_UNSIGNED_SHORT_5_6_5_REV:
        return 2;
    case GL_UNSIGNED_BYTE:
        component_size = 1;
        break;
    case GL_UNSIGNED_SHORT:
        component_size = 2;
        break;
    }
    switch (format) {
    case GL_LUMINANCE:
    case GL_ALPHA:
        return component_size;
    case GL_YCBCR_MESA:
    case GL_RGB_422_APPLE:
        return 2;
    case GL_RGB:
    case GL_BGR:
        return 3 * component_size;
    case GL_RGBA:
    case GL_BGRA:
        return 4 * component_size;
    case GL_RED:
        return component_size;
    case GL_RG:
    case GL_LUMINANCE_ALPHA:
        return 2 * component_size;
    }
    abort(); // unknown
}

/**
 * \brief upload a texture, handling things like stride and slices
 * \param target texture target, usually GL_TEXTURE_2D
 * \param format OpenGL format of data
 * \param type OpenGL type of data
 * \param dataptr data to upload
 * \param stride data stride
 * \param x x offset in texture
 * \param y y offset in texture
 * \param w width of the texture part to upload
 * \param h height of the texture part to upload
 * \param slice height of an upload slice, 0 for all at once
 * \ingroup gltexture
 */
void glUploadTex(GL *gl, GLenum target, GLenum format, GLenum type,
                 const void *dataptr, int stride,
                 int x, int y, int w, int h, int slice)
{
    const uint8_t *data = dataptr;
    int y_max = y + h;
    if (w <= 0 || h <= 0)
        return;
    if (slice <= 0)
        slice = h;
    if (stride < 0) {
        data += (h - 1) * stride;
        stride = -stride;
    }
    // this is not always correct, but should work for MPlayer
    glAdjustAlignment(gl, stride);
    gl->PixelStorei(GL_UNPACK_ROW_LENGTH, stride / glFmt2bpp(format, type));
    for (; y + slice <= y_max; y += slice) {
        gl->TexSubImage2D(target, 0, x, y, w, slice, format, type, data);
        data += stride * slice;
    }
    if (y < y_max)
        gl->TexSubImage2D(target, 0, x, y, w, y_max - y, format, type, data);
}

// Like glUploadTex, but upload a byte array with all elements set to val.
// If scratch is not NULL, points to a resizeable talloc memory block than can
/