forked from NVIDIA/VideoProcessingFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SampleOpenGL.py
351 lines (308 loc) · 11.2 KB
/
SampleOpenGL.py
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
#
# Copyright 2022 @Yves33, @sandhawalia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Starting from Python 3.8 DLL search policy has changed.
# We need to add path to CUDA DLLs explicitly.
import os
import sys
import time
import argparse
import numpy as np
import pycuda
from pathlib import Path
import ctypes
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import PyNvCodec as nvc
from utils import get_logger
logger = get_logger(__file__)
if os.name == "nt":
# Add CUDA_PATH env variable
cuda_path = os.environ["CUDA_PATH"]
if cuda_path:
os.add_dll_directory(cuda_path)
else:
logger.error("CUDA_PATH environment variable is not set.")
logger.error("Can't set CUDA DLLs search path.")
exit(1)
# Add PATH as well for minor CUDA releases
sys_path = os.environ["PATH"]
if sys_path:
paths = sys_path.split(";")
for path in paths:
if os.path.isdir(path):
os.add_dll_directory(path)
else:
logger.error("PATH environment variable is not set.")
exit(1)
class FPSLogger:
def __init__(self, interval):
self.interval = interval
self.framecount = 0
self.seconds = time.time_ns() / 1e9
def log(self, titlebar=True, fmt="fps : {0}"):
self.framecount += 1
if self.seconds + self.interval < time.time_ns() / 1e9:
self.fps = self.framecount / self.interval
self.framecount = 0
self.seconds = time.time_ns() / 1e9
if titlebar:
glutSetWindowTitle(fmt.format(self.fps))
else:
logger.info(fmt.format(self.fps))
class OpenGLApplication:
def __init__(
self,
encoded_video_file: str,
gpu_id: int = 0,
width: int = 500,
height: int = 500,
):
self.cpu = False
# Setup up display window
self.setup_display(width, height)
# Loading drivers + compiling shaders, Done once?
self.setup_opengl()
# Setup decoder and downsampler
self.setup_vpf(encoded_video_file, gpu_id)
#
self.create_textures()
#
self.cuda_gl_handshake()
def setup_display(self, width, height):
logger.info(f"Setting up display {width}x{height}")
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
glutInitWindowSize(width, height)
glutInitWindowPosition(0, 0)
glutCreateWindow(b"Simple PyOpenGL example")
logger.info(f"Done setting up display {width}x{height}")
def setup_opengl(self):
self.program = self.compile_shaders()
import pycuda.autoinit
import pycuda.gl.autoinit
self.vao = GLuint()
glCreateVertexArrays(1, self.vao)
def setup_vpf(self, encoded_video_file, gpu_id):
self.nv_dec = nvc.PyNvDecoder(encoded_video_file, gpu_id)
self.width, self.height = self.nv_dec.Width(), self.nv_dec.Height()
self.cc_ctx = nvc.ColorspaceConversionContext(
self.nvDec.ColorSpace(), self.nv_dec.ColorRange()
)
if self.nv_dec.ColorSpace() != nvc.ColorSpace.BT_709:
self.nv_yuv = nvc.PySurfaceConverter(
self.width, self.height, self.nv_dec.Format(), nvc.PixelFormat.YUV420, 0
)
self.nv_cvt = nvc.PySurfaceConverter(
self.width, self.height, self.nvYuv.Format(), nvc.PixelFormat.RGB, 0
)
else:
self.nv_yuv = None
self.nv_cvt = nvc.PySurfaceConverter(
self.width, self.height, self.nv_dec.Format(), nvc.PixelFormat.RGB, 0
)
self.nv_down = nvc.PySurfaceDownloader(
self.width, self.height, self.nv_cvt.Format(), 0
)
self.data = np.zeros((self.width * self.height, 3), np.uint8)
def create_textures(self):
## create texture for GL display
self.texture = glGenTextures(1)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.texture)
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGB,
self.width,
self.height,
0,
GL_RGB,
GL_UNSIGNED_BYTE,
ctypes.c_void_p(0),
)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glBindTexture(GL_TEXTURE_2D, 0)
self.cuda_img = pycuda.gl.RegisteredImage(
int(self.texture), GL_TEXTURE_2D, pycuda.gl.graphics_map_flags.NONE
) # WRITE_DISCARD)
def cuda_gl_handshake(self):
self.pbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, self.pbo)
glBufferData(GL_ARRAY_BUFFER, self.data, GL_DYNAMIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, 0)
import pycuda.autoinit
import pycuda.gl.autoinit
self.cuda_pbo = pycuda.gl.RegisteredBuffer(int(self.pbo))
self.vao = 0
glGenVertexArrays(1, self.vao)
glBindVertexArray(self.vao)
def compile_shaders(self):
vertex_shader_source = """
#version 450 core
out vec2 uv;
void main( void)
{
// Declare a hard-coded array of positions
const vec2 vertices[4] = vec2[4](vec2(-0.5, 0.5),
vec2( 0.5, 0.5),
vec2( 0.5, -0.5),
vec2(-0.5, -0.5));
// Index into our array using gl_VertexID
uv=vertices[gl_VertexID]+vec2(0.5,0.5);
gl_Position = vec4(2*vertices[gl_VertexID],1.0,1.0);
}
"""
vertex_shader = glCreateShader(GL_VERTEX_SHADER)
glShaderSource(vertex_shader, vertex_shader_source)
glCompileShader(vertex_shader)
fragment_shader_source = """
#version 450 core
uniform sampler2D s;
in vec2 uv;
out vec4 color;
void main(void)
{
color = vec4(texture(s, uv));
}
"""
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER)
glShaderSource(fragment_shader, fragment_shader_source)
glCompileShader(fragment_shader)
program = glCreateProgram()
glAttachShader(program, vertex_shader)
glAttachShader(program, fragment_shader)
glLinkProgram(program)
# --- Clean up now that we don't need these shaders anymore.
glDeleteShader(vertex_shader)
glDeleteShader(fragment_shader)
return program
def render(self, method: str = "GPUTEX"):
glClearBufferfv(GL_COLOR, 0, (0, 0, 0))
## bind program
glUseProgram(self.program)
## get one frame
rawSurface = self.nv_dec.DecodeSingleSurface()
if self.nv_yuv != None:
yuvSurface = self.nv_yuv.Execute(rawSurface, self.cc_ctx)
cvtSurface = self.nv_cvt.Execute(yuvSurface, self.cc_ctx)
else:
cvtSurface = self.nv_cvt.Execute(rawSurface, self.cc_ctx)
## texture update through cpu and system memory
if self.cpu:
## Download surface data to CPU, then update GL texture with these data
success = self.nv_down.DownloadSingleSurface(cvtSurface, self.data)
if not success:
logger.warn("Could not download Cuda Surface to CPU")
return
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.texture)
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
self.width,
self.height,
GL_RGB,
GL_UNSIGNED_BYTE,
self.data,
)
else:
## cuda copy from surface.Plane_Ptr() to pbo, then update texture from PBO
src_plane = cvtSurface.PlanePtr()
buffer_mapping = self.cuda_pbo.map()
buffptr, buffsize = buffer_mapping.device_ptr_and_size()
cpy = pycuda.driver.Memcpy2D()
cpy.set_src_device(src_plane.GpuMem())
cpy.set_dst_device(buffptr)
cpy.width_in_bytes = src_plane.Width()
cpy.src_pitch = src_plane.Pitch()
cpy.dst_pitch = self.width * 3
cpy.height = src_plane.Height()
cpy(aligned=True)
# pycuda.driver.Context.synchronize() ## not required?
buffer_mapping.unmap()
## opengl update texture from pbo
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.texture)
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, int(self.pbo))
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
self.width,
self.height,
GL_RGB,
GL_UNSIGNED_BYTE,
ctypes.c_void_p(0),
)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.texture)
## send uniforms to program and draw quad
glUniform(glGetUniformLocation(self.program, b"s"), 0)
glDrawArrays(GL_QUADS, 0, 4)
## Display
glutSwapBuffers()
def keypressed(self, key, x, y):
if key.decode("utf-8") == "q":
glutLeaveMainLoop()
elif key.decode("utf-8") == "c":
self.cpu = True
elif key.decode("utf-8") == "g":
self.cpu = False
def animate(self):
glutPostRedisplay()
def run(self, verbose: bool = False):
glutIdleFunc(self.animate)
glutDisplayFunc(self.render)
glutMainLoop()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
"This sample decodes input video to OpenGL Texture.\n"
+ "Requires the GL Utility Toolkit (GLUT) and pyCUDA compiled with GL support\n"
+ "Controls: c -> toggles cpu path (CUDA->cpu->OpenGL)\n"
+ " g -> toggles gpu path (CUDA->OpenGL)\n"
+ " q -> exit demo."
)
parser.add_argument(
"-g",
"--gpu-id",
type=int,
required=True,
help="GPU id, check nvidia-smi",
)
parser.add_argument(
"-e",
"--encoded-file-path",
type=Path,
required=True,
help="Encoded video file (read from)",
)
parser.add_argument(
"-v", "--verbose", default=False, action="store_true", help="Verbose"
)
args = parser.parse_args()
app = OpenGLApplication(
args.gpu_id,
args.encoded_file_path.as_posix(),
)
app.run(verbose=args.verbose)
exit(0)