diff options
-rw-r--r-- | README.md | 2 | ||||
-rw-r--r-- | TODO | 1 | ||||
-rwxr-xr-x | build.sh | 4 | ||||
-rw-r--r-- | external/NvFBC.h (renamed from include/NvFBC.h) | 0 | ||||
-rw-r--r-- | external/cuda.h (renamed from include/cuda.h) | 0 | ||||
-rw-r--r-- | include/CudaLibrary.hpp | 148 | ||||
-rw-r--r-- | include/GlLibrary.hpp | 146 | ||||
-rw-r--r-- | include/LibraryLoader.hpp | 38 | ||||
-rw-r--r-- | include/NvFBCLibrary.hpp | 3 | ||||
-rw-r--r-- | include/cudaGL.h | 605 | ||||
-rwxr-xr-x | install_ubuntu.sh | 7 | ||||
-rw-r--r-- | project.conf | 9 | ||||
-rw-r--r-- | src/main.cpp | 288 |
13 files changed, 423 insertions, 828 deletions
@@ -18,7 +18,7 @@ Using NvFBC (recording the monitor/screen) is not faster than not using NvFBC (r If you are running an Arch Linux based distro, then you can find gpu screen recorder on aur under the name gpu-screen-recorder-git (`yay -S gpu-screen-recorder-git`).\ If you are running an Ubuntu based distro then run `install_ubuntu.sh` as root: `sudo ./install_ubuntu.sh`.\ -On other distros you need to install dependencies manually and run `build.sh`. Dependencies: `glew glfw3 ffmpeg libx11 libxcomposite libpulse-simple`. You need to additionally have `cuda` installed when you run `gpu-screen-recorder`.\ +On other distros you need to install dependencies manually and run `build.sh`. Dependencies: `libgl (libglvnd), ffmpeg, libx11, libxcomposite, libpulse`. You need to additionally have `cuda` installed when you run `gpu-screen-recorder`.\ If you use a distro that isn't friendly to nvidia, such as fedora, then you can also install gpu-screen-recorder-gtk with flatpak here: [gpu-screen-recorder-flatpak](https://git.dec05eba.com/gpu-screen-recorder-flatpak/about/).\ Recording monitors requires a gpu with NvFBC support (note: this is not required when recording a single window!). Normally only tesla and quadro gpus support this, but by using [nvidia-patch](https://github.com/keylase/nvidia-patch) or [nvlax](https://github.com/illnyang/nvlax) you can do this on all gpus that support nvenc as well (gpus as old as the nvidia 600 series), provided you are not using outdated gpu drivers. @@ -2,7 +2,6 @@ Check for reparent. Only add window to list if its the window is a topmost window. Track window damages and only update then. That is better for output file size. Getting the texture of a window when using a compositor is an nvidia specific limitation. When gpu-screen-recorder supports other gpus then this can be ignored. -Remove dependency on glfw (and glew?). Quickly changing workspace and back while recording under i3 breaks the screen recorder. i3 probably unmaps windows in other workspaces. Nvidia 515.57 supports nvfbc direct capture with mouse capture. Check if driver is equal or newer than this and use mouse capture in such situations (with direct capture) supports nvfbc direct capture with mouse capture. See https://trac.ffmpeg.org/wiki/EncodingForStreamingSites for optimizing streaming. @@ -1,7 +1,7 @@ #!/bin/sh -e -dependencies="glew libavcodec libavformat libavutil x11 xcomposite glfw3 libpulse libswresample" -includes="$(pkg-config --cflags $dependencies) -Iinclude" +dependencies="libavcodec libavformat libavutil x11 xcomposite libpulse libswresample" +includes="$(pkg-config --cflags $dependencies) -Iexternal" libs="$(pkg-config --libs $dependencies) -ldl -pthread -lm" g++ -c src/sound.cpp -O2 $includes g++ -c src/main.cpp -O2 $includes diff --git a/include/NvFBC.h b/external/NvFBC.h index 8990eea..8990eea 100644 --- a/include/NvFBC.h +++ b/external/NvFBC.h diff --git a/include/cuda.h b/external/cuda.h index e6f760c..e6f760c 100644 --- a/include/cuda.h +++ b/external/cuda.h diff --git a/include/CudaLibrary.hpp b/include/CudaLibrary.hpp index 134d19c..e45aa44 100644 --- a/include/CudaLibrary.hpp +++ b/include/CudaLibrary.hpp @@ -1,42 +1,29 @@ #pragma once +#include "LibraryLoader.hpp" + #include <cuda.h> -#include <cudaGL.h> #include <dlfcn.h> #include <stdio.h> -typedef CUresult CUDAAPI (*CUINIT)(unsigned int Flags); -typedef CUresult CUDAAPI (*CUDEVICEGETCOUNT)(int *count); -typedef CUresult CUDAAPI (*CUDEVICEGET)(CUdevice *device, int ordinal); -typedef CUresult CUDAAPI (*CUCTXCREATE_V2)(CUcontext *pctx, unsigned int flags, CUdevice dev); -typedef CUresult CUDAAPI (*CUCTXPUSHCURRENT_V2)(CUcontext ctx); -typedef CUresult CUDAAPI (*CUCTXPOPCURRENT_V2)(CUcontext *pctx); -typedef CUresult CUDAAPI (*CUGETERRORSTRING)(CUresult error, const char **pStr); -typedef CUresult CUDAAPI (*CUMEMSETD8_V2)(CUdeviceptr dstDevice, unsigned char uc, size_t N); -typedef CUresult CUDAAPI (*CUMEMCPY2D_V2)(const CUDA_MEMCPY2D *pCopy); - -typedef CUresult CUDAAPI (*CUGRAPHICSGLREGISTERIMAGE)(CUgraphicsResource *pCudaResource, GLuint image, GLenum target, unsigned int Flags); -typedef CUresult CUDAAPI (*CUGRAPHICSRESOURCESETMAPFLAGS)(CUgraphicsResource resource, unsigned int flags); -typedef CUresult CUDAAPI (*CUGRAPHICSMAPRESOURCES)(unsigned int count, CUgraphicsResource *resources, CUstream hStream); -typedef CUresult CUDAAPI (*CUGRAPHICSUNREGISTERRESOURCE)(CUgraphicsResource resource); -typedef CUresult CUDAAPI (*CUGRAPHICSSUBRESOURCEGETMAPPEDARRAY)(CUarray *pArray, CUgraphicsResource resource, unsigned int arrayIndex, unsigned int mipLevel); +typedef struct CUgraphicsResource_st *CUgraphicsResource; struct Cuda { - CUINIT cuInit; - CUDEVICEGETCOUNT cuDeviceGetCount; - CUDEVICEGET cuDeviceGet; - CUCTXCREATE_V2 cuCtxCreate_v2; - CUCTXPUSHCURRENT_V2 cuCtxPushCurrent_v2; - CUCTXPOPCURRENT_V2 cuCtxPopCurrent_v2; - CUGETERRORSTRING cuGetErrorString; - CUMEMSETD8_V2 cuMemsetD8_v2; - CUMEMCPY2D_V2 cuMemcpy2D_v2; - - CUGRAPHICSGLREGISTERIMAGE cuGraphicsGLRegisterImage; - CUGRAPHICSRESOURCESETMAPFLAGS cuGraphicsResourceSetMapFlags; - CUGRAPHICSMAPRESOURCES cuGraphicsMapResources; - CUGRAPHICSUNREGISTERRESOURCE cuGraphicsUnregisterResource; - CUGRAPHICSSUBRESOURCEGETMAPPEDARRAY cuGraphicsSubResourceGetMappedArray; + CUresult CUDAAPI (*cuInit)(unsigned int Flags); + CUresult CUDAAPI (*cuDeviceGetCount)(int *count); + CUresult CUDAAPI (*cuDeviceGet)(CUdevice *device, int ordinal); + CUresult CUDAAPI (*cuCtxCreate_v2)(CUcontext *pctx, unsigned int flags, CUdevice dev); + CUresult CUDAAPI (*cuCtxPushCurrent_v2)(CUcontext ctx); + CUresult CUDAAPI (*cuCtxPopCurrent_v2)(CUcontext *pctx); + CUresult CUDAAPI (*cuGetErrorString)(CUresult error, const char **pStr); + CUresult CUDAAPI (*cuMemsetD8_v2)(CUdeviceptr dstDevice, unsigned char uc, size_t N); + CUresult CUDAAPI (*cuMemcpy2D_v2)(const CUDA_MEMCPY2D *pCopy); + + CUresult CUDAAPI (*cuGraphicsGLRegisterImage)(CUgraphicsResource *pCudaResource, unsigned int image, unsigned int target, unsigned int Flags); + CUresult CUDAAPI (*cuGraphicsResourceSetMapFlags)(CUgraphicsResource resource, unsigned int flags); + CUresult CUDAAPI (*cuGraphicsMapResources)(unsigned int count, CUgraphicsResource *resources, CUstream hStream); + CUresult CUDAAPI (*cuGraphicsUnregisterResource)(CUgraphicsResource resource); + CUresult CUDAAPI (*cuGraphicsSubResourceGetMappedArray)(CUarray *pArray, CUgraphicsResource resource, unsigned int arrayIndex, unsigned int mipLevel); ~Cuda() { if(library) @@ -52,80 +39,39 @@ struct Cuda { if(!lib) { lib = dlopen("libcuda.so.1", RTLD_LAZY); if(!lib) { - fprintf(stderr, "Error: failed to load libcuda.so and libcuda.so.1, error: %s\n", dlerror()); + fprintf(stderr, "Error: failed to load libcuda.so/libcuda.so.1, error: %s\n", dlerror()); return false; } } - cuInit = (CUINIT)load_symbol(lib, "cuInit"); - if(!cuInit) - goto fail; - - cuDeviceGetCount = (CUDEVICEGETCOUNT)load_symbol(lib, "cuDeviceGetCount"); - if(!cuDeviceGetCount) - goto fail; - - cuDeviceGet = (CUDEVICEGET)load_symbol(lib, "cuDeviceGet"); - if(!cuDeviceGet) - goto fail; - - cuCtxCreate_v2 = (CUCTXCREATE_V2)load_symbol(lib, "cuCtxCreate_v2"); - if(!cuCtxCreate_v2) - goto fail; - - cuCtxPushCurrent_v2 = (CUCTXPUSHCURRENT_V2)load_symbol(lib, "cuCtxPushCurrent_v2"); - if(!cuCtxPushCurrent_v2) - goto fail; - - cuCtxPopCurrent_v2 = (CUCTXPOPCURRENT_V2)load_symbol(lib, "cuCtxPopCurrent_v2"); - if(!cuCtxPopCurrent_v2) - goto fail; - - cuGetErrorString = (CUGETERRORSTRING)load_symbol(lib, "cuGetErrorString"); - if(!cuGetErrorString) - goto fail; - - cuMemsetD8_v2 = (CUMEMSETD8_V2)load_symbol(lib, "cuMemsetD8_v2"); - if(!cuMemsetD8_v2) - goto fail; - - cuMemcpy2D_v2 = (CUMEMCPY2D_V2)load_symbol(lib, "cuMemcpy2D_v2"); - if(!cuMemcpy2D_v2) - goto fail; - - cuGraphicsGLRegisterImage = (CUGRAPHICSGLREGISTERIMAGE)load_symbol(lib, "cuGraphicsGLRegisterImage"); - if(!cuGraphicsGLRegisterImage) - goto fail; - - cuGraphicsResourceSetMapFlags = (CUGRAPHICSRESOURCESETMAPFLAGS)load_symbol(lib, "cuGraphicsResourceSetMapFlags"); - if(!cuGraphicsResourceSetMapFlags) - goto fail; - - cuGraphicsMapResources = (CUGRAPHICSMAPRESOURCES)load_symbol(lib, "cuGraphicsMapResources"); - if(!cuGraphicsMapResources) - goto fail; - - cuGraphicsUnregisterResource = (CUGRAPHICSUNREGISTERRESOURCE)load_symbol(lib, "cuGraphicsUnregisterResource"); - if(!cuGraphicsUnregisterResource) - goto fail; - - cuGraphicsSubResourceGetMappedArray = (CUGRAPHICSSUBRESOURCEGETMAPPEDARRAY)load_symbol(lib, "cuGraphicsSubResourceGetMappedArray"); - if(!cuGraphicsSubResourceGetMappedArray) - goto fail; - - library = lib; - return true; - - fail: - dlclose(lib); - return false; - } -private: - void* load_symbol(void *library, const char *symbol) { - void *sym = dlsym(library, symbol); - if(!sym) - fprintf(stderr, "Error: missing required symbol %s from libcuda.so\n", symbol); - return sym; + dlsym_assign required_dlsym[] = { + { (void**)&cuInit, "cuInit" }, + { (void**)&cuDeviceGetCount, "cuDeviceGetCount" }, + { (void**)&cuDeviceGet, "cuDeviceGet" }, + { (void**)&cuCtxCreate_v2, "cuCtxCreate_v2" }, + { (void**)&cuCtxPushCurrent_v2, "cuCtxPushCurrent_v2" }, + { (void**)&cuCtxPopCurrent_v2, "cuCtxPopCurrent_v2" }, + { (void**)&cuGetErrorString, "cuGetErrorString" }, + { (void**)&cuMemsetD8_v2, "cuMemsetD8_v2" }, + { (void**)&cuMemcpy2D_v2, "cuMemcpy2D_v2" }, + + { (void**)&cuGraphicsGLRegisterImage, "cuGraphicsGLRegisterImage" }, + { (void**)&cuGraphicsResourceSetMapFlags, "cuGraphicsResourceSetMapFlags" }, + { (void**)&cuGraphicsMapResources, "cuGraphicsMapResources" }, + { (void**)&cuGraphicsUnregisterResource, "cuGraphicsUnregisterResource" }, + { (void**)&cuGraphicsSubResourceGetMappedArray, "cuGraphicsSubResourceGetMappedArray" }, + + { NULL, NULL } + }; + + if(dlsym_load_list(lib, required_dlsym)) { + library = lib; + return true; + } else { + fprintf(stderr, "Error: missing required symbols in libcuda.so\n"); + dlclose(lib); + return false; + } } private: void *library = nullptr; diff --git a/include/GlLibrary.hpp b/include/GlLibrary.hpp new file mode 100644 index 0000000..1934db5 --- /dev/null +++ b/include/GlLibrary.hpp @@ -0,0 +1,146 @@ +#pragma once + +#include "LibraryLoader.hpp" + +#include <X11/X.h> +#include <X11/Xutil.h> +#include <dlfcn.h> +#include <stdio.h> + +typedef XID GLXPixmap; +typedef XID GLXDrawable; +typedef XID GLXWindow; + +typedef struct __GLXcontextRec *GLXContext; +typedef struct __GLXFBConfigRec *GLXFBConfig; + +#define GL_TEXTURE_2D 0x0DE1 +#define GL_RGB 0x1907 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WIDTH 0x1000 +#define GL_TEXTURE_HEIGHT 0x1001 +#define GL_NEAREST 0x2600 + +#define GLX_BUFFER_SIZE 2 +#define GLX_DOUBLEBUFFER 5 +#define GLX_RED_SIZE 8 +#define GLX_GREEN_SIZE 9 +#define GLX_BLUE_SIZE 10 +#define GLX_ALPHA_SIZE 11 +#define GLX_DEPTH_SIZE 12 + +#define GLX_RGBA_BIT 0x00000001 +#define GLX_RENDER_TYPE 0x8011 +#define GLX_FRONT_EXT 0x20DE +#define GLX_BIND_TO_TEXTURE_RGB_EXT 0x20D0 +#define GLX_DRAWABLE_TYPE 0x8010 +#define GLX_WINDOW_BIT 0x00000001 +#define GLX_PIXMAP_BIT 0x00000002 +#define GLX_BIND_TO_TEXTURE_TARGETS_EXT 0x20D3 +#define GLX_TEXTURE_2D_BIT_EXT 0x00000002 +#define GLX_TEXTURE_TARGET_EXT 0x20D6 +#define GLX_TEXTURE_2D_EXT 0x20DC +#define GLX_TEXTURE_FORMAT_EXT 0x20D5 +#define GLX_TEXTURE_FORMAT_RGB_EXT 0x20D9 +#define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002 +#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 +#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 +#define GLX_CONTEXT_FLAGS_ARB 0x2094 + +struct GlLibrary { + GLXPixmap (*glXCreatePixmap)(Display *dpy, GLXFBConfig config, Pixmap pixmap, const int *attribList); + void (*glXDestroyPixmap)(Display *dpy, GLXPixmap pixmap); + void (*glXBindTexImageEXT)(Display *dpy, GLXDrawable drawable, int buffer, const int *attrib_list); + void (*glXReleaseTexImageEXT)(Display *dpy, GLXDrawable drawable, int buffer); + GLXFBConfig* (*glXChooseFBConfig)(Display *dpy, int screen, const int *attribList, int *nitems); + XVisualInfo* (*glXGetVisualFromFBConfig)(Display *dpy, GLXFBConfig config); + GLXContext (*glXCreateContextAttribsARB)(Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list); + Bool (*glXMakeContextCurrent)(Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx); + void (*glXDestroyContext)(Display *dpy, GLXContext ctx); + void (*glXSwapBuffers)(Display *dpy, GLXDrawable drawable); + + void (*glXSwapIntervalEXT)(Display *dpy, GLXDrawable drawable, int interval); + int (*glXSwapIntervalMESA)(unsigned int interval); + int (*glXSwapIntervalSGI)(int interval); + + void (*glClearTexImage)(unsigned int texture, unsigned int level, unsigned int format, unsigned int type, const void *data); + + unsigned int (*glGetError)(void); + void (*glClear)(unsigned int mask); + void (*glGenTextures)(int n, unsigned int *textures); + void (*glDeleteTextures)(int n, const unsigned int *texture); + void (*glBindTexture)(unsigned int target, unsigned int texture); + void (*glTexParameteri)(unsigned int target, unsigned int pname, int param); + void (*glGetTexLevelParameteriv)(unsigned int target, int level, unsigned int pname, int *params); + void (*glTexImage2D)(unsigned int target, int level, int internalFormat, int width, int height, int border, unsigned int format, unsigned int type, const void *pixels); + void (*glCopyImageSubData)(unsigned int srcName, unsigned int srcTarget, int srcLevel, int srcX, int srcY, int srcZ, unsigned int dstName, unsigned int dstTarget, int dstLevel, int dstX, int dstY, int dstZ, int srcWidth, int srcHeight, int srcDepth); + + ~GlLibrary() { + if(library) + dlclose(library); + } + + bool load() { + if(library) + return true; + + dlerror(); // clear + void *lib = dlopen("libGL.so.1", RTLD_LAZY); + if(!lib) { + fprintf(stderr, "Error: failed to load libGL.so.1, error: %s\n", dlerror()); + return false; + } + + dlsym_assign optional_dlsym[] = { + { (void**)&glClearTexImage, "glClearTexImage" }, + { (void**)&glXSwapIntervalEXT, "glXSwapIntervalEXT" }, + { (void**)&glXSwapIntervalMESA, "glXSwapIntervalMESA" }, + { (void**)&glXSwapIntervalSGI, "glXSwapIntervalSGI" }, + + { NULL, NULL } + }; + + dlsym_load_list_optional(lib, optional_dlsym); + + dlsym_assign required_dlsym[] = { + { (void**)&glXCreatePixmap, "glXCreatePixmap" }, + { (void**)&glXDestroyPixmap, "glXDestroyPixmap" }, + { (void**)&glXBindTexImageEXT, "glXBindTexImageEXT" }, + { (void**)&glXReleaseTexImageEXT, "glXReleaseTexImageEXT" }, + { (void**)&glXChooseFBConfig, "glXChooseFBConfig" }, + { (void**)&glXGetVisualFromFBConfig, "glXGetVisualFromFBConfig" }, + { (void**)&glXCreateContextAttribsARB, "glXCreateContextAttribsARB" }, + { (void**)&glXMakeContextCurrent, "glXMakeContextCurrent" }, + { (void**)&glXDestroyContext, "glXDestroyContext" }, + { (void**)&glXSwapBuffers, "glXSwapBuffers" }, + + { (void**)&glGetError, "glGetError" }, + { (void**)&glClear, "glClear" }, + { (void**)&glGenTextures, "glGenTextures" }, + { (void**)&glDeleteTextures, "glDeleteTextures" }, + { (void**)&glBindTexture, "glBindTexture" }, + { (void**)&glTexParameteri, "glTexParameteri" }, + { (void**)&glGetTexLevelParameteriv, "glGetTexLevelParameteriv" }, + { (void**)&glTexImage2D, "glTexImage2D" }, + { (void**)&glCopyImageSubData, "glCopyImageSubData" }, + + { NULL, NULL } + }; + + if(dlsym_load_list(lib, required_dlsym)) { + library = lib; + return true; + } else { + fprintf(stderr, "Error: missing required symbols in libGL.so.1\n"); + dlclose(lib); + return false; + } + } +private: + void *library = nullptr; +}; diff --git a/include/LibraryLoader.hpp b/include/LibraryLoader.hpp new file mode 100644 index 0000000..16dc580 --- /dev/null +++ b/include/LibraryLoader.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include <dlfcn.h> +#include <stdio.h> + +typedef struct { + void **func; + const char *name; +} dlsym_assign; + +static void* dlsym_print_fail(void *handle, const char *name, bool required) { + dlerror(); + void *sym = dlsym(handle, name); + char *err_str = dlerror(); + + if(!sym) + fprintf(stderr, "%s: dlsym(handle, \"%s\") failed, error: %s\n", required ? "error" : "warning", name, err_str ? err_str : "(null)"); + + return sym; +} + +/* |dlsyms| should be null terminated */ +static bool dlsym_load_list(void *handle, const dlsym_assign *dlsyms) { + bool success = true; + for(int i = 0; dlsyms[i].func; ++i) { + *dlsyms[i].func = dlsym_print_fail(handle, dlsyms[i].name, true); + if(!*dlsyms[i].func) + success = false; + } + return success; +} + +/* |dlsyms| should be null terminated */ +static void dlsym_load_list_optional(void *handle, const dlsym_assign *dlsyms) { + for(int i = 0; dlsyms[i].func; ++i) { + *dlsyms[i].func = dlsym_print_fail(handle, dlsyms[i].name, false); + } +}
\ No newline at end of file diff --git a/include/NvFBCLibrary.hpp b/include/NvFBCLibrary.hpp index 95f6ae4..b6d5d90 100644 --- a/include/NvFBCLibrary.hpp +++ b/include/NvFBCLibrary.hpp @@ -1,7 +1,6 @@ #pragma once -#include "NvFBC.h" - +#include <NvFBC.h> #include <dlfcn.h> #include <string.h> #include <stdio.h> diff --git a/include/cudaGL.h b/include/cudaGL.h deleted file mode 100644 index 21e972a..0000000 --- a/include/cudaGL.h +++ /dev/null @@ -1,605 +0,0 @@ -/* - * Copyright 1993-2014 NVIDIA Corporation. All rights reserved. - * - * NOTICE TO LICENSEE: - * - * This source code and/or documentation ("Licensed Deliverables") are - * subject to NVIDIA intellectual property rights under U.S. and - * international Copyright laws. - * - * These Licensed Deliverables contained herein is PROPRIETARY and - * CONFIDENTIAL to NVIDIA and is being provided under the terms and - * conditions of a form of NVIDIA software license agreement by and - * between NVIDIA and Licensee ("License Agreement") or electronically - * accepted by Licensee. Notwithstanding any terms or conditions to - * the contrary in the License Agreement, reproduction or disclosure - * of the Licensed Deliverables to any third party without the express - * written consent of NVIDIA is prohibited. - * - * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE - * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE - * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS - * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. - * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED - * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, - * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. - * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE - * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY - * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, - * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS - * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE - * OF THESE LICENSED DELIVERABLES. - * - * U.S. Government End Users. These Licensed Deliverables are a - * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT - * 1995), consisting of "commercial computer software" and "commercial - * computer software documentation" as such terms are used in 48 - * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government - * only as a commercial end item. Consistent with 48 C.F.R.12.212 and - * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all - * U.S. Government End Users acquire the Licensed Deliverables with - * only those rights set forth herein. - * - * Any use of the Licensed Deliverables in individual and commercial - * software must include, in the user documentation and internal - * comments to the code, the above Disclaimer and U.S. Government End - * Users Notice. - */ - -#ifndef CUDAGL_H -#define CUDAGL_H - -#include <cuda.h> -#include <GL/gl.h> - -#if defined(__CUDA_API_VERSION_INTERNAL) || defined(__DOXYGEN_ONLY__) || defined(CUDA_ENABLE_DEPRECATED) -#define __CUDA_DEPRECATED -#elif defined(_MSC_VER) -#define __CUDA_DEPRECATED __declspec(deprecated) -#elif defined(__GNUC__) -#define __CUDA_DEPRECATED __attribute__((deprecated)) -#else -#define __CUDA_DEPRECATED -#endif - -#ifdef CUDA_FORCE_API_VERSION -#error "CUDA_FORCE_API_VERSION is no longer supported." -#endif - -#if defined(__CUDA_API_VERSION_INTERNAL) || defined(CUDA_API_PER_THREAD_DEFAULT_STREAM) - #define __CUDA_API_PER_THREAD_DEFAULT_STREAM - #define __CUDA_API_PTDS(api) api ## _ptds - #define __CUDA_API_PTSZ(api) api ## _ptsz -#else - #define __CUDA_API_PTDS(api) api - #define __CUDA_API_PTSZ(api) api -#endif - -#define cuGLCtxCreate cuGLCtxCreate_v2 -#define cuGLMapBufferObject __CUDA_API_PTDS(cuGLMapBufferObject_v2) -#define cuGLMapBufferObjectAsync __CUDA_API_PTSZ(cuGLMapBufferObjectAsync_v2) -#define cuGLGetDevices cuGLGetDevices_v2 - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \file cudaGL.h - * \brief Header file for the OpenGL interoperability functions of the - * low-level CUDA driver application programming interface. - */ - -/** - * \defgroup CUDA_GL OpenGL Interoperability - * \ingroup CUDA_DRIVER - * - * ___MANBRIEF___ OpenGL interoperability functions of the low-level CUDA - * driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ - * - * This section describes the OpenGL interoperability functions of the - * low-level CUDA driver application programming interface. Note that mapping - * of OpenGL resources is performed with the graphics API agnostic, resource - * mapping interface described in \ref CUDA_GRAPHICS "Graphics Interoperability". - * - * @{ - */ - -#if defined(_WIN32) -#if !defined(WGL_NV_gpu_affinity) -typedef void* HGPUNV; -#endif -#endif /* _WIN32 */ - -/** - * \brief Registers an OpenGL buffer object - * - * Registers the buffer object specified by \p buffer for access by - * CUDA. A handle to the registered object is returned as \p - * pCudaResource. The register flags \p Flags specify the intended usage, - * as follows: - * - * - ::CU_GRAPHICS_REGISTER_FLAGS_NONE: Specifies no hints about how this - * resource will be used. It is therefore assumed that this resource will be - * read from and written to by CUDA. This is the default value. - * - ::CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY: Specifies that CUDA - * will not write to this resource. - * - ::CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD: Specifies that - * CUDA will not read from this resource and will write over the - * entire contents of the resource, so none of the data previously - * stored in the resource will be preserved. - * - * \param pCudaResource - Pointer to the returned object handle - * \param buffer - name of buffer object to be registered - * \param Flags - Register flags - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_INVALID_HANDLE, - * ::CUDA_ERROR_ALREADY_MAPPED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * \notefnerr - * - * \sa - * ::cuGraphicsUnregisterResource, - * ::cuGraphicsMapResources, - * ::cuGraphicsResourceGetMappedPointer, - * ::cudaGraphicsGLRegisterBuffer - */ -CUresult CUDAAPI cuGraphicsGLRegisterBuffer(CUgraphicsResource *pCudaResource, GLuint buffer, unsigned int Flags); - -/** - * \brief Register an OpenGL texture or renderbuffer object - * - * Registers the texture or renderbuffer object specified by \p image for access by CUDA. - * A handle to the registered object is returned as \p pCudaResource. - * - * \p target must match the type of the object, and must be one of ::GL_TEXTURE_2D, - * ::GL_TEXTURE_RECTANGLE, ::GL_TEXTURE_CUBE_MAP, ::GL_TEXTURE_3D, ::GL_TEXTURE_2D_ARRAY, - * or ::GL_RENDERBUFFER. - * - * The register flags \p Flags specify the intended usage, as follows: - * - * - ::CU_GRAPHICS_REGISTER_FLAGS_NONE: Specifies no hints about how this - * resource will be used. It is therefore assumed that this resource will be - * read from and written to by CUDA. This is the default value. - * - ::CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY: Specifies that CUDA - * will not write to this resource. - * - ::CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD: Specifies that - * CUDA will not read from this resource and will write over the - * entire contents of the resource, so none of the data previously - * stored in the resource will be preserved. - * - ::CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST: Specifies that CUDA will - * bind this resource to a surface reference. - * - ::CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER: Specifies that CUDA will perform - * texture gather operations on this resource. - * - * The following image formats are supported. For brevity's sake, the list is abbreviated. - * For ex., {GL_R, GL_RG} X {8, 16} would expand to the following 4 formats - * {GL_R8, GL_R16, GL_RG8, GL_RG16} : - * - GL_RED, GL_RG, GL_RGBA, GL_LUMINANCE, GL_ALPHA, GL_LUMINANCE_ALPHA, GL_INTENSITY - * - {GL_R, GL_RG, GL_RGBA} X {8, 16, 16F, 32F, 8UI, 16UI, 32UI, 8I, 16I, 32I} - * - {GL_LUMINANCE, GL_ALPHA, GL_LUMINANCE_ALPHA, GL_INTENSITY} X - * {8, 16, 16F_ARB, 32F_ARB, 8UI_EXT, 16UI_EXT, 32UI_EXT, 8I_EXT, 16I_EXT, 32I_EXT} - * - * The following image classes are currently disallowed: - * - Textures with borders - * - Multisampled renderbuffers - * - * \param pCudaResource - Pointer to the returned object handle - * \param image - name of texture or renderbuffer object to be registered - * \param target - Identifies the type of object specified by \p image - * \param Flags - Register flags - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_INVALID_HANDLE, - * ::CUDA_ERROR_ALREADY_MAPPED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * \notefnerr - * - * \sa - * ::cuGraphicsUnregisterResource, - * ::cuGraphicsMapResources, - * ::cuGraphicsSubResourceGetMappedArray, - * ::cudaGraphicsGLRegisterImage - */ -CUresult CUDAAPI cuGraphicsGLRegisterImage(CUgraphicsResource *pCudaResource, GLuint image, GLenum target, unsigned int Flags); - -#ifdef _WIN32 -/** - * \brief Gets the CUDA device associated with hGpu - * - * Returns in \p *pDevice the CUDA device associated with a \p hGpu, if - * applicable. - * - * \param pDevice - Device associated with hGpu - * \param hGpu - Handle to a GPU, as queried via ::WGL_NV_gpu_affinity() - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_DEINITIALIZED, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_INVALID_VALUE - * \notefnerr - * - * \sa ::cuGLMapBufferObject, - * ::cuGLRegisterBufferObject, ::cuGLUnmapBufferObject, - * ::cuGLUnregisterBufferObject, ::cuGLUnmapBufferObjectAsync, - * ::cuGLSetBufferObjectMapFlags, - * ::cudaWGLGetDevice - */ -CUresult CUDAAPI cuWGLGetDevice(CUdevice *pDevice, HGPUNV hGpu); -#endif /* _WIN32 */ - -/** - * CUDA devices corresponding to an OpenGL device - */ -typedef enum CUGLDeviceList_enum { - CU_GL_DEVICE_LIST_ALL = 0x01, /**< The CUDA devices for all GPUs used by the current OpenGL context */ - CU_GL_DEVICE_LIST_CURRENT_FRAME = 0x02, /**< The CUDA devices for the GPUs used by the current OpenGL context in its currently rendering frame */ - CU_GL_DEVICE_LIST_NEXT_FRAME = 0x03, /**< The CUDA devices for the GPUs to be used by the current OpenGL context in the next frame */ -} CUGLDeviceList; - -/** - * \brief Gets the CUDA devices associated with the current OpenGL context - * - * Returns in \p *pCudaDeviceCount the number of CUDA-compatible devices - * corresponding to the current OpenGL context. Also returns in \p *pCudaDevices - * at most cudaDeviceCount of the CUDA-compatible devices corresponding to - * the current OpenGL context. If any of the GPUs being used by the current OpenGL - * context are not CUDA capable then the call will return CUDA_ERROR_NO_DEVICE. - * - * The \p deviceList argument may be any of the following: - * - ::CU_GL_DEVICE_LIST_ALL: Query all devices used by the current OpenGL context. - * - ::CU_GL_DEVICE_LIST_CURRENT_FRAME: Query the devices used by the current OpenGL context to - * render the current frame (in SLI). - * - ::CU_GL_DEVICE_LIST_NEXT_FRAME: Query the devices used by the current OpenGL context to - * render the next frame (in SLI). Note that this is a prediction, it can't be guaranteed that - * this is correct in all cases. - * - * \param pCudaDeviceCount - Returned number of CUDA devices. - * \param pCudaDevices - Returned CUDA devices. - * \param cudaDeviceCount - The size of the output device array pCudaDevices. - * \param deviceList - The set of devices to return. - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_NO_DEVICE, - * ::CUDA_ERROR_INVALID_VALUE, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_INVALID_GRAPHICS_CONTEXT - * - * \notefnerr - * - * \sa - * ::cuWGLGetDevice, - * ::cudaGLGetDevices - */ -CUresult CUDAAPI cuGLGetDevices(unsigned int *pCudaDeviceCount, CUdevice *pCudaDevices, unsigned int cudaDeviceCount, CUGLDeviceList deviceList); - -/** - * \defgroup CUDA_GL_DEPRECATED OpenGL Interoperability [DEPRECATED] - * - * ___MANBRIEF___ deprecated OpenGL interoperability functions of the low-level - * CUDA driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ - * - * This section describes deprecated OpenGL interoperability functionality. - * - * @{ - */ - -/** Flags to map or unmap a resource */ -typedef enum CUGLmap_flags_enum { - CU_GL_MAP_RESOURCE_FLAGS_NONE = 0x00, - CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY = 0x01, - CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD = 0x02, -} CUGLmap_flags; - -/** - * \brief Create a CUDA context for interoperability with OpenGL - * - * \deprecated This function is deprecated as of Cuda 5.0. - * - * This function is deprecated and should no longer be used. It is - * no longer necessary to associate a CUDA context with an OpenGL - * context in order to achieve maximum interoperability performance. - * - * \param pCtx - Returned CUDA context - * \param Flags - Options for CUDA context creation - * \param device - Device on which to create the context - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_DEINITIALIZED, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_INVALID_VALUE, - * ::CUDA_ERROR_OUT_OF_MEMORY - * \notefnerr - * - * \sa ::cuCtxCreate, ::cuGLInit, ::cuGLMapBufferObject, - * ::cuGLRegisterBufferObject, ::cuGLUnmapBufferObject, - * ::cuGLUnregisterBufferObject, ::cuGLMapBufferObjectAsync, - * ::cuGLUnmapBufferObjectAsync, ::cuGLSetBufferObjectMapFlags, - * ::cuWGLGetDevice - */ -__CUDA_DEPRECATED CUresult CUDAAPI cuGLCtxCreate(CUcontext *pCtx, unsigned int Flags, CUdevice device ); - -/** - * \brief Initializes OpenGL interoperability - * - * \deprecated This function is deprecated as of Cuda 3.0. - * - * Initializes OpenGL interoperability. This function is deprecated - * and calling it is no longer required. It may fail if the needed - * OpenGL driver facilities are not available. - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_DEINITIALIZED, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_UNKNOWN - * \notefnerr - * - * \sa ::cuGLMapBufferObject, - * ::cuGLRegisterBufferObject, ::cuGLUnmapBufferObject, - * ::cuGLUnregisterBufferObject, ::cuGLMapBufferObjectAsync, - * ::cuGLUnmapBufferObjectAsync, ::cuGLSetBufferObjectMapFlags, - * ::cuWGLGetDevice - */ -__CUDA_DEPRECATED CUresult CUDAAPI cuGLInit(void); - -/** - * \brief Registers an OpenGL buffer object - * - * \deprecated This function is deprecated as of Cuda 3.0. - * - * Registers the buffer object specified by \p buffer for access by - * CUDA. This function must be called before CUDA can map the buffer - * object. There must be a valid OpenGL context bound to the current - * thread when this function is called, and the buffer name is - * resolved by that context. - * - * \param buffer - The name of the buffer object to register. - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_DEINITIALIZED, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_ALREADY_MAPPED - * \notefnerr - * - * \sa ::cuGraphicsGLRegisterBuffer - */ -__CUDA_DEPRECATED CUresult CUDAAPI cuGLRegisterBufferObject(GLuint buffer); - -/** - * \brief Maps an OpenGL buffer object - * - * \deprecated This function is deprecated as of Cuda 3.0. - * - * Maps the buffer object specified by \p buffer into the address space of the - * current CUDA context and returns in \p *dptr and \p *size the base pointer - * and size of the resulting mapping. - * - * There must be a valid OpenGL context bound to the current thread - * when this function is called. This must be the same context, or a - * member of the same shareGroup, as the context that was bound when - * the buffer was registered. - * - * All streams in the current CUDA context are synchronized with the - * current GL context. - * - * \param dptr - Returned mapped base pointer - * \param size - Returned size of mapping - * \param buffer - The name of the buffer object to map - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_DEINITIALIZED, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_INVALID_VALUE, - * ::CUDA_ERROR_MAP_FAILED - * \notefnerr - * - * \sa ::cuGraphicsMapResources - */ -__CUDA_DEPRECATED CUresult CUDAAPI cuGLMapBufferObject(CUdeviceptr *dptr, size_t *size, GLuint buffer); - -/** - * \brief Unmaps an OpenGL buffer object - * - * \deprecated This function is deprecated as of Cuda 3.0. - * - * Unmaps the buffer object specified by \p buffer for access by CUDA. - * - * There must be a valid OpenGL context bound to the current thread - * when this function is called. This must be the same context, or a - * member of the same shareGroup, as the context that was bound when - * the buffer was registered. - * - * All streams in the current CUDA context are synchronized with the - * current GL context. - * - * \param buffer - Buffer object to unmap - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_DEINITIALIZED, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_INVALID_VALUE - * \notefnerr - * - * \sa ::cuGraphicsUnmapResources - */ -__CUDA_DEPRECATED CUresult CUDAAPI cuGLUnmapBufferObject(GLuint buffer); - -/** - * \brief Unregister an OpenGL buffer object - * - * \deprecated This function is deprecated as of Cuda 3.0. - * - * Unregisters the buffer object specified by \p buffer. This - * releases any resources associated with the registered buffer. - * After this call, the buffer may no longer be mapped for access by - * CUDA. - * - * There must be a valid OpenGL context bound to the current thread - * when this function is called. This must be the same context, or a - * member of the same shareGroup, as the context that was bound when - * the buffer was registered. - * - * \param buffer - Name of the buffer object to unregister - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_DEINITIALIZED, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_INVALID_VALUE - * \notefnerr - * - * \sa ::cuGraphicsUnregisterResource - */ -__CUDA_DEPRECATED CUresult CUDAAPI cuGLUnregisterBufferObject(GLuint buffer); - -/** - * \brief Set the map flags for an OpenGL buffer object - * - * \deprecated This function is deprecated as of Cuda 3.0. - * - * Sets the map flags for the buffer object specified by \p buffer. - * - * Changes to \p Flags will take effect the next time \p buffer is mapped. - * The \p Flags argument may be any of the following: - * - ::CU_GL_MAP_RESOURCE_FLAGS_NONE: Specifies no hints about how this - * resource will be used. It is therefore assumed that this resource will be - * read from and written to by CUDA kernels. This is the default value. - * - ::CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY: Specifies that CUDA kernels which - * access this resource will not write to this resource. - * - ::CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD: Specifies that CUDA kernels - * which access this resource will not read from this resource and will - * write over the entire contents of the resource, so none of the data - * previously stored in the resource will be preserved. - * - * If \p buffer has not been registered for use with CUDA, then - * ::CUDA_ERROR_INVALID_HANDLE is returned. If \p buffer is presently - * mapped for access by CUDA, then ::CUDA_ERROR_ALREADY_MAPPED is returned. - * - * There must be a valid OpenGL context bound to the current thread - * when this function is called. This must be the same context, or a - * member of the same shareGroup, as the context that was bound when - * the buffer was registered. - * - * \param buffer - Buffer object to unmap - * \param Flags - Map flags - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_HANDLE, - * ::CUDA_ERROR_ALREADY_MAPPED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * \notefnerr - * - * \sa ::cuGraphicsResourceSetMapFlags - */ -__CUDA_DEPRECATED CUresult CUDAAPI cuGLSetBufferObjectMapFlags(GLuint buffer, unsigned int Flags); - -/** - * \brief Maps an OpenGL buffer object - * - * \deprecated This function is deprecated as of Cuda 3.0. - * - * Maps the buffer object specified by \p buffer into the address space of the - * current CUDA context and returns in \p *dptr and \p *size the base pointer - * and size of the resulting mapping. - * - * There must be a valid OpenGL context bound to the current thread - * when this function is called. This must be the same context, or a - * member of the same shareGroup, as the context that was bound when - * the buffer was registered. - * - * Stream \p hStream in the current CUDA context is synchronized with - * the current GL context. - * - * \param dptr - Returned mapped base pointer - * \param size - Returned size of mapping - * \param buffer - The name of the buffer object to map - * \param hStream - Stream to synchronize - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_DEINITIALIZED, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_INVALID_VALUE, - * ::CUDA_ERROR_MAP_FAILED - * \notefnerr - * - * \sa ::cuGraphicsMapResources - */ -__CUDA_DEPRECATED CUresult CUDAAPI cuGLMapBufferObjectAsync(CUdeviceptr *dptr, size_t *size, GLuint buffer, CUstream hStream); - -/** - * \brief Unmaps an OpenGL buffer object - * - * \deprecated This function is deprecated as of Cuda 3.0. - * - * Unmaps the buffer object specified by \p buffer for access by CUDA. - * - * There must be a valid OpenGL context bound to the current thread - * when this function is called. This must be the same context, or a - * member of the same shareGroup, as the context that was bound when - * the buffer was registered. - * - * Stream \p hStream in the current CUDA context is synchronized with - * the current GL context. - * - * \param buffer - Name of the buffer object to unmap - * \param hStream - Stream to synchronize - * - * \return - * ::CUDA_SUCCESS, - * ::CUDA_ERROR_DEINITIALIZED, - * ::CUDA_ERROR_NOT_INITIALIZED, - * ::CUDA_ERROR_INVALID_CONTEXT, - * ::CUDA_ERROR_INVALID_VALUE - * \notefnerr - * - * \sa ::cuGraphicsUnmapResources - */ -__CUDA_DEPRECATED CUresult CUDAAPI cuGLUnmapBufferObjectAsync(GLuint buffer, CUstream hStream); - -/** @} */ /* END CUDA_GL_DEPRECATED */ -/** @} */ /* END CUDA_GL */ - - -#if defined(__CUDA_API_VERSION_INTERNAL) - #undef cuGLCtxCreate - #undef cuGLMapBufferObject - #undef cuGLMapBufferObjectAsync - #undef cuGLGetDevices - - CUresult CUDAAPI cuGLGetDevices(unsigned int *pCudaDeviceCount, CUdevice *pCudaDevices, unsigned int cudaDeviceCount, CUGLDeviceList deviceList); - CUresult CUDAAPI cuGLMapBufferObject_v2(CUdeviceptr *dptr, size_t *size, GLuint buffer); - CUresult CUDAAPI cuGLMapBufferObjectAsync_v2(CUdeviceptr *dptr, size_t *size, GLuint buffer, CUstream hStream); - CUresult CUDAAPI cuGLCtxCreate(CUcontext *pCtx, unsigned int Flags, CUdevice device ); - CUresult CUDAAPI cuGLMapBufferObject(CUdeviceptr_v1 *dptr, unsigned int *size, GLuint buffer); - CUresult CUDAAPI cuGLMapBufferObjectAsync(CUdeviceptr_v1 *dptr, unsigned int *size, GLuint buffer, CUstream hStream); -#endif /* __CUDA_API_VERSION_INTERNAL */ - -#ifdef __cplusplus -}; -#endif - -#undef __CUDA_DEPRECATED - -#endif diff --git a/install_ubuntu.sh b/install_ubuntu.sh index 21a7826..768475d 100755 --- a/install_ubuntu.sh +++ b/install_ubuntu.sh @@ -11,12 +11,11 @@ cuda_missing="$?" set -e apt-get -y install build-essential nvidia-cuda-dev\ libswresample-dev libavformat-dev libavcodec-dev libavutil-dev\ - libx11-dev libxcomposite-dev\ - libglew-dev libglfw3-dev\ + libgl-dev libx11-dev libxcomposite-dev\ libpulse-dev -dependencies="glew libavcodec libavformat libavutil x11 xcomposite glfw3 libpulse libswresample" -includes="$(pkg-config --cflags $dependencies) -Iinclude" +dependencies="libavcodec libavformat libavutil x11 xcomposite libpulse libswresample" +includes="$(pkg-config --cflags $dependencies) -Iexternal" libs="$(pkg-config --libs $dependencies) -ldl -pthread -lm" g++ -c src/sound.cpp -O2 $includes g++ -c src/main.cpp -O2 $includes diff --git a/project.conf b/project.conf index bb5f463..dc004f2 100644 --- a/project.conf +++ b/project.conf @@ -5,20 +5,13 @@ version = "1.1.0" platforms = ["posix"] [config] -include_dirs = ["include"] +include_dirs = ["external"] [dependencies] -glew = ">=2" libavcodec = ">=58" libavformat = ">=58" libavutil = ">=56.2" x11 = ">=1" xcomposite = ">=0.2" -#xdamage = "1" - -# TODO: Remove this dependency, this is needed right now for glfwMakeContextCurrent -glfw3 = "3" - libpulse = ">=13" - libswresample = ">=3" diff --git a/src/main.cpp b/src/main.cpp index 6f72496..018f614 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -30,15 +30,10 @@ #include <unistd.h> #include <fcntl.h> -#define GLX_GLXEXT_PROTOTYPES -#include <GL/glew.h> -#include <GL/glx.h> -#include <GL/glxext.h> -#include <GLFW/glfw3.h> - #include "../include/sound.hpp" #include "../include/NvFBCLibrary.hpp" #include "../include/CudaLibrary.hpp" +#include "../include/GlLibrary.hpp" #include <X11/extensions/Xcomposite.h> //#include <X11/Xatom.h> @@ -62,8 +57,6 @@ extern "C" { #include <deque> #include <future> -//#include <CL/cl.h> - // TODO: Remove LIBAVUTIL_VERSION_MAJOR checks in the future when ubuntu, pop os LTS etc update ffmpeg to >= 5.0 static const int VIDEO_STREAM_INDEX = 0; @@ -71,6 +64,7 @@ static const int VIDEO_STREAM_INDEX = 0; static thread_local char av_error_buffer[AV_ERROR_MAX_STRING_SIZE]; static Cuda cuda; +static GlLibrary gl; static char* av_error_to_string(int err) { if(av_strerror(err, av_error_buffer, sizeof(av_error_buffer)) < 0) @@ -90,14 +84,14 @@ struct ScopedGLXFBConfig { struct WindowPixmap { Pixmap pixmap = None; GLXPixmap glx_pixmap = None; - GLuint texture_id = 0; - GLuint target_texture_id = 0; + unsigned int texture_id = 0; + unsigned int target_texture_id = 0; - GLint texture_width = 0; - GLint texture_height = 0; + int texture_width = 0; + int texture_height = 0; - GLint texture_real_width = 0; - GLint texture_real_height = 0; + int texture_real_width = 0; + int texture_real_height = 0; Window composite_window = None; }; @@ -204,12 +198,12 @@ static Window get_compositor_window(Display *display) { static void cleanup_window_pixmap(Display *dpy, WindowPixmap &pixmap) { if (pixmap.target_texture_id) { - glDeleteTextures(1, &pixmap.target_texture_id); + gl.glDeleteTextures(1, &pixmap.target_texture_id); pixmap.target_texture_id = 0; } if (pixmap.texture_id) { - glDeleteTextures(1, &pixmap.texture_id); + gl.glDeleteTextures(1, &pixmap.texture_id); pixmap.texture_id = 0; pixmap.texture_width = 0; pixmap.texture_height = 0; @@ -218,8 +212,8 @@ static void cleanup_window_pixmap(Display *dpy, WindowPixmap &pixmap) { } if (pixmap.glx_pixmap) { - glXDestroyPixmap(dpy, pixmap.glx_pixmap); - glXReleaseTexImageEXT(dpy, pixmap.glx_pixmap, GLX_FRONT_EXT); + gl.glXDestroyPixmap(dpy, pixmap.glx_pixmap); + gl.glXReleaseTexImageEXT(dpy, pixmap.glx_pixmap, GLX_FRONT_EXT); pixmap.glx_pixmap = None; } @@ -263,7 +257,7 @@ static bool recreate_window_pixmap(Display *dpy, Window window_id, None}; int c; - GLXFBConfig *configs = glXChooseFBConfig(dpy, 0, pixmap_config, &c); + GLXFBConfig *configs = gl.glXChooseFBConfig(dpy, 0, pixmap_config, &c); if (!configs) { fprintf(stderr, "Failed too choose fb config\n"); return false; @@ -275,7 +269,7 @@ static bool recreate_window_pixmap(Display *dpy, Window window_id, GLXFBConfig config; for (int i = 0; i < c; i++) { config = configs[i]; - XVisualInfo *visual = glXGetVisualFromFBConfig(dpy, config); + XVisualInfo *visual = gl.glXGetVisualFromFBConfig(dpy, config); if (!visual) continue; @@ -299,8 +293,7 @@ static bool recreate_window_pixmap(Display *dpy, Window window_id, return false; } - GLXPixmap glx_pixmap = - glXCreatePixmap(dpy, config, new_window_pixmap, pixmap_attribs); + GLXPixmap glx_pixmap = gl.glXCreatePixmap(dpy, config, new_window_pixmap, pixmap_attribs); if (!glx_pixmap) { fprintf(stderr, "Failed to create glx pixmap\n"); XFreePixmap(dpy, new_window_pixmap); @@ -311,29 +304,29 @@ static bool recreate_window_pixmap(Display *dpy, Window window_id, pixmap.glx_pixmap = glx_pixmap; //glEnable(GL_TEXTURE_2D); - glGenTextures(1, &pixmap.texture_id); - glBindTexture(GL_TEXTURE_2D, pixmap.texture_id); + gl.glGenTextures(1, &pixmap.texture_id); + gl.glBindTexture(GL_TEXTURE_2D, pixmap.texture_id); // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glXBindTexImageEXT(dpy, pixmap.glx_pixmap, GLX_FRONT_EXT, NULL); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, + gl.glXBindTexImageEXT(dpy, pixmap.glx_pixmap, GLX_FRONT_EXT, NULL); + gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // GL_LINEAR ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // GL_LINEAR);//GL_LINEAR_MIPMAP_LINEAR ); //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, + gl.glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &pixmap.texture_width); - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, + gl.glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &pixmap.texture_height); pixmap.texture_real_width = pixmap.texture_width; pixmap.texture_real_height = pixmap.texture_height; if(pixmap.texture_width == 0 || pixmap.texture_height == 0) { - glBindTexture(GL_TEXTURE_2D, 0); + gl.glBindTexture(GL_TEXTURE_2D, 0); pixmap.texture_width = attr.width; pixmap.texture_height = attr.height; @@ -375,31 +368,130 @@ static bool recreate_window_pixmap(Display *dpy, Window window_id, // TODO: Investigate if it's somehow possible to use the pixmap texture // directly, this should improve performance since only less image copy is // then needed every frame. - glGenTextures(1, &pixmap.target_texture_id); - glBindTexture(GL_TEXTURE_2D, pixmap.target_texture_id); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, pixmap.texture_width, + gl.glGenTextures(1, &pixmap.target_texture_id); + gl.glBindTexture(GL_TEXTURE_2D, pixmap.target_texture_id); + gl.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, pixmap.texture_width, pixmap.texture_height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); - int err2 = glGetError(); + unsigned int err2 = gl.glGetError(); //fprintf(stderr, "error: %d\n", err2); // glXBindTexImageEXT(dpy, pixmap.glx_pixmap, GLX_FRONT_EXT, NULL); // glGenerateTextureMipmapEXT(glxpixmap, GL_TEXTURE_2D); // glGenerateMipmap(GL_TEXTURE_2D); - // glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); - // glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + // gl.glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); + // gl.glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, + gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // GL_LINEAR ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // GL_LINEAR);//GL_LINEAR_MIPMAP_LINEAR ); //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glBindTexture(GL_TEXTURE_2D, 0); + gl.glBindTexture(GL_TEXTURE_2D, 0); return pixmap.texture_id != 0 && pixmap.target_texture_id != 0; } +static Window create_opengl_window(Display *display) { + const int attr[] = { + GLX_RENDER_TYPE, GLX_RGBA_BIT, + GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, + GLX_DOUBLEBUFFER, True, + GLX_RED_SIZE, 8, + GLX_GREEN_SIZE, 8, + GLX_BLUE_SIZE, 8, + GLX_ALPHA_SIZE, 8, + GLX_DEPTH_SIZE, 0, + None + }; + + XVisualInfo *visual_info = NULL; + GLXFBConfig fbconfig = NULL; + + int numfbconfigs = 0; + GLXFBConfig *fbconfigs = gl.glXChooseFBConfig(display, DefaultScreen(display), attr, &numfbconfigs); + for(int i = 0; i < numfbconfigs; i++) { + visual_info = gl.glXGetVisualFromFBConfig(display, fbconfigs[i]); + if(!visual_info) + continue; + + fbconfig = fbconfigs[i]; + break; + } + + if(!visual_info) { + fprintf(stderr, "mgl error: no appropriate visual found\n"); + return -1; + } + + // TODO: Core profile? GLX_CONTEXT_CORE_PROFILE_BIT_ARB. + // TODO: Remove need for 4.2 when copy texture function has been removed + int context_attribs[] = { + GLX_CONTEXT_MAJOR_VERSION_ARB, 4, + GLX_CONTEXT_MINOR_VERSION_ARB, 2, + GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, + None + }; + + GLXContext gl_context = gl.glXCreateContextAttribsARB(display, fbconfig, nullptr, True, context_attribs); + if(!gl_context) { + fprintf(stderr, "Error: failed to create gl context\n"); + return None; + } + + Colormap colormap = XCreateColormap(display, DefaultRootWindow(display), visual_info->visual, AllocNone); + if(!colormap) { + fprintf(stderr, "Error: failed to create x11 colormap\n"); + gl.glXDestroyContext(display, gl_context); + } + + XSetWindowAttributes window_attr; + window_attr.colormap = colormap; + + // TODO: Is there a way to remove the need to create a window? + Window window = XCreateWindow(display, DefaultRootWindow(display), 0, 0, 1, 1, 0, visual_info->depth, InputOutput, visual_info->visual, CWColormap, &window_attr); + + if(!window) { + fprintf(stderr, "Error: failed to create gl window\n"); + goto fail; + } + + if(!gl.glXMakeContextCurrent(display, window, window, gl_context)) { + fprintf(stderr, "Error: failed to make gl context current\n"); + goto fail; + } + + return window; + + fail: + XFreeColormap(display, colormap); + gl.glXDestroyContext(display, gl_context); + return None; +} + +/* TODO: check for glx swap control extension string (GLX_EXT_swap_control, etc) */ +static void set_vertical_sync_enabled(Display *display, Window window, bool enabled) { + int result = 0; + + if(gl.glXSwapIntervalEXT) { + gl.glXSwapIntervalEXT(display, window, enabled ? 1 : 0); + } else if(gl.glXSwapIntervalMESA) { + result = gl.glXSwapIntervalMESA(enabled ? 1 : 0); + } else if(gl.glXSwapIntervalSGI) { + result = gl.glXSwapIntervalSGI(enabled ? 1 : 0); + } else { + static int warned = 0; + if (!warned) { + warned = 1; + fprintf(stderr, "Warning: setting vertical sync not supported\n"); + } + } + + if(result != 0) + fprintf(stderr, "Warning: setting vertical sync failed\n"); +} + // |stream| is only required for non-replay mode static void receive_frames(AVCodecContext *av_codec_context, int stream_index, AVStream *stream, AVFrame *frame, AVFormatContext *av_format_context, @@ -408,9 +500,10 @@ static void receive_frames(AVCodecContext *av_codec_context, int stream_index, A int replay_buffer_size_secs, bool &frames_erased, std::mutex &write_output_mutex) { - AVPacket av_packet; - memset(&av_packet, 0, sizeof(av_packet)); for (;;) { + // TODO: Use av_packet_alloc instead because sizeof(av_packet) might not be future proof(?) + AVPacket av_packet; + memset(&av_packet, 0, sizeof(av_packet)); av_packet.data = NULL; av_packet.size = 0; int res = avcodec_receive_packet(av_codec_context, &av_packet); @@ -420,7 +513,7 @@ static void receive_frames(AVCodecContext *av_codec_context, int stream_index, A std::lock_guard<std::mutex> lock(write_output_mutex); if(replay_buffer_size_secs != -1) { - double time_now = glfwGetTime(); + double time_now = clock_get_monotonic_seconds(); double replay_time_elapsed = time_now - replay_start_time; AVPacket new_pack; @@ -442,16 +535,18 @@ static void receive_frames(AVCodecContext *av_codec_context, int stream_index, A av_packet_unref(&av_packet); } else if (res == AVERROR(EAGAIN)) { // we have no packet // fprintf(stderr, "No packet!\n"); + av_packet_unref(&av_packet); break; } else if (res == AVERROR_EOF) { // this is the end of the stream fprintf(stderr, "End of stream!\n"); + av_packet_unref(&av_packet); break; } else { fprintf(stderr, "Unexpected error: %d\n", res); + av_packet_unref(&av_packet); break; } } - //av_packet_unref(&av_packet); } static AVCodecContext* create_audio_codec_context(AVFormatContext *av_format_context, int fps) { @@ -584,7 +679,21 @@ static AVCodecContext *create_video_codec_context(AVFormatContext *av_format_con // stream->time_base = codec_context->time_base; // codec_context->ticks_per_frame = 30; //av_opt_set(codec_context->priv_data, "tune", "hq", 0); - //av_opt_set(codec_context->priv_data, "rc", "vbr", 0); + // TODO: Do this for better file size? also allows setting qmin, qmax per frame? which can then be used to dynamically set bitrate to reduce quality + // if live streaming is slow or if the users harddrive is cant handle writing megabytes of data per second. + #if 0 + char qmin_str[32]; + snprintf(qmin_str, sizeof(qmin_str), "%d", codec_context->qmin); + + char qmax_str[32]; + snprintf(qmax_str, sizeof(qmax_str), "%d", codec_context->qmax); + + av_opt_set(codec_context->priv_data, "cq", qmax_str, 0); + av_opt_set(codec_context->priv_data, "rc", "vbr", 0); + av_opt_set(codec_context->priv_data, "qmin", qmin_str, 0); + av_opt_set(codec_context->priv_data, "qmax", qmax_str, 0); + codec_context->bit_rate = 0; + #endif // Some formats want stream headers to be seperate if (av_format_context->oformat->flags & AVFMT_GLOBALHEADER) @@ -726,7 +835,7 @@ static void usage() { fprintf(stderr, " -c Container format for output file, for example mp4, or flv.\n"); fprintf(stderr, " -f Framerate to record at.\n"); fprintf(stderr, " -a Audio device to record from (pulse audio device). Can be specified multiple times. Each time this is specified a new audio track is added for the specified audio device. Optional, no audio track is added by default.\n"); - fprintf(stderr, " -q Video quality. Should either be 'medium', 'high' or 'ultra'. Optional, set to 'medium' be default.\n"); + fprintf(stderr, " -q Video quality. Should either be 'medium', 'high' or 'ultra'. 'medium' is the recommended as higher values, especially 'ultra' can be placebo most of the time. Optional, set to 'medium' be default.\n"); fprintf(stderr, " -r Replay buffer size in seconds. If this is set, then only the last seconds as set by this option will be stored" " and the video will only be saved when the gpu-screen-recorder is closed. This feature is similar to Nvidia's instant replay feature." " This option has be between 5 and 1200. Note that the replay buffer size will not always be precise, because of keyframes. Optional, disabled by default.\n"); @@ -1198,7 +1307,7 @@ int main(int argc, char **argv) { WindowPixmap window_pixmap; Display *dpy = nullptr; - GLFWwindow *window = nullptr; + Window window = None; if(src_window_id) { dpy = XOpenDisplay(nullptr); if (!dpy) { @@ -1206,6 +1315,11 @@ int main(int argc, char **argv) { return 1; } + //#if defined(DEBUG) + XSetErrorHandler(x11_error_handler); + XSetIOErrorHandler(x11_io_error_handler); + //#endif + bool has_name_pixmap = x11_supports_composite_named_window_pixmap(dpy); if (!has_name_pixmap) { fprintf(stderr, "Error: XCompositeNameWindowPixmap is not supported by " @@ -1228,44 +1342,16 @@ int main(int argc, char **argv) { XCompositeRedirectWindow(dpy, src_window_id, CompositeRedirectAutomatic); - // glXMakeContextCurrent(Display *dpy, GLXDrawable draw, GLXDrawable read, - // GLXContext ctx) - if (!glfwInit()) { - fprintf(stderr, "Error: Failed to initialize glfw\n"); - return 1; - } - - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); - glfwWindowHint(GLFW_VISIBLE, GL_FALSE); - - window = glfwCreateWindow(1, 1, "gpu-screen-recorder", nullptr, nullptr); - if (!window) { - fprintf(stderr, "Error: Failed to create glfw window\n"); - glfwTerminate(); + if(!gl.load()) { + fprintf(stderr, "Error: Failed to load opengl\n"); return 1; } - glfwMakeContextCurrent(window); - glfwSwapInterval(0); - - //#if defined(DEBUG) - XSetErrorHandler(x11_error_handler); - XSetIOErrorHandler(x11_io_error_handler); - //#endif - - glewExperimental = GL_TRUE; - GLenum nGlewError = glewInit(); - if (nGlewError != GLEW_OK) { - fprintf(stderr, "%s - Error initializing GLEW! %s\n", __FUNCTION__, - glewGetErrorString(nGlewError)); + window = create_opengl_window(dpy); + if(!window) return 1; - } - glGetError(); // to clear the error caused deep in GLEW + set_vertical_sync_enabled(dpy, window, false); recreate_window_pixmap(dpy, src_window_id, window_pixmap); if(!record_area) { @@ -1278,11 +1364,6 @@ int main(int argc, char **argv) { window_pixmap.target_texture_id = 0; window_pixmap.texture_width = window_width; window_pixmap.texture_height = window_height; - - if (!glfwInit()) { - fprintf(stderr, "Error: Failed to initialize glfw\n"); - return 1; - } } // Video start @@ -1408,7 +1489,7 @@ int main(int argc, char **argv) { // Release texture // res = cuGraphicsUnmapResources(1, &cuda_graphics_resource, 0); - double start_time = glfwGetTime(); + double start_time = clock_get_monotonic_seconds(); double frame_timer_start = start_time; double window_resize_timer = start_time; bool window_resized = false; @@ -1447,7 +1528,7 @@ int main(int argc, char **argv) { std::mutex write_output_mutex; - double record_start_time = glfwGetTime(); + const double record_start_time = clock_get_monotonic_seconds(); std::deque<AVPacket> frame_data_queue; bool frames_erased = false; @@ -1460,7 +1541,7 @@ int main(int argc, char **argv) { memset(empty_audio, 0, audio_buffer_size); for(AudioTrack &audio_track : audio_tracks) { - audio_track.thread = std::thread([record_start_time, replay_buffer_size_secs, &frame_data_queue, &frames_erased, start_time_pts, &audio_track, empty_audio](AVFormatContext *av_format_context, std::mutex *write_output_mutex) mutable { + audio_track.thread = std::thread([record_start_time, replay_buffer_size_secs, &frame_data_queue, &frames_erased, &audio_track, empty_audio](AVFormatContext *av_format_context, std::mutex *write_output_mutex) mutable { SwrContext *swr = swr_alloc(); if(!swr) { fprintf(stderr, "Failed to create SwrContext\n"); @@ -1546,10 +1627,9 @@ int main(int argc, char **argv) { bool redraw = true; XEvent e; while (running) { - double frame_start = glfwGetTime(); - glfwPollEvents(); + double frame_start = clock_get_monotonic_seconds(); if(window) - glClear(GL_COLOR_BUFFER_BIT); + gl.glClear(GL_COLOR_BUFFER_BIT); redraw = true; @@ -1559,7 +1639,7 @@ int main(int argc, char **argv) { } if (XCheckTypedWindowEvent(dpy, src_window_id, Expose, &e) && e.xexpose.count == 0) { - window_resize_timer = glfwGetTime(); + window_resize_timer = clock_get_monotonic_seconds(); window_resized = true; } @@ -1573,13 +1653,13 @@ int main(int argc, char **argv) { if(e.xconfigure.width != (int)window_width || e.xconfigure.height != (int)window_height) { window_width = std::max(0, e.xconfigure.width); window_height = std::max(0, e.xconfigure.height); - window_resize_timer = glfwGetTime(); + window_resize_timer = clock_get_monotonic_seconds(); window_resized = true; } } const double window_resize_timeout = 1.0; // 1 second - if(window_resized && glfwGetTime() - window_resize_timer >= window_resize_timeout) { + if(window_resized && clock_get_monotonic_seconds() - window_resize_timer >= window_resize_timeout) { window_resized = false; fprintf(stderr, "Resize window!\n"); recreate_window_pixmap(dpy, src_window_id, window_pixmap); @@ -1642,7 +1722,7 @@ int main(int argc, char **argv) { ++fps_counter; - double time_now = glfwGetTime(); + double time_now = clock_get_monotonic_seconds(); double frame_timer_elapsed = time_now - frame_timer_start; double elapsed = time_now - start_time; if (elapsed >= 1.0) { @@ -1704,15 +1784,17 @@ int main(int argc, char **argv) { } if(clamped) { - // Requires opengl 4.4... - glClearTexImage(window_pixmap.target_texture_id, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); + // Requires opengl 4.4... TODO: Replace with earlier opengl if opengl < 4.2 + if(gl.glClearTexImage) + gl.glClearTexImage(window_pixmap.target_texture_id, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); } - glCopyImageSubData( + // Requires opengl 4.2... TODO: Replace with earlier opengl if opengl < 4.2 + gl.glCopyImageSubData( window_pixmap.texture_id, GL_TEXTURE_2D, 0, source_x, source_y, 0, window_pixmap.target_texture_id, GL_TEXTURE_2D, 0, 0, 0, 0, source_width, source_height, 1); - int err = glGetError(); + unsigned int err = gl.glGetError(); if(err != 0) { static bool error_shown = false; if(!error_shown) { @@ -1720,8 +1802,8 @@ int main(int argc, char **argv) { fprintf(stderr, "Error: glCopyImageSubData failed, gl error: %d\n", err); } } - glfwSwapBuffers(window); - // int err = glGetError(); + gl.glXSwapBuffers(dpy, window); + // int err = gl.glGetError(); // fprintf(stderr, "error: %d\n", err); // TODO: Remove this copy, which is only possible by using nvenc directly and encoding window_pixmap.target_texture_id @@ -1789,7 +1871,7 @@ int main(int argc, char **argv) { } // av_frame_free(&frame); - double frame_end = glfwGetTime(); + double frame_end = clock_get_monotonic_seconds(); double frame_sleep_fps = 1.0 / update_fps; double sleep_time = frame_sleep_fps - (frame_end - frame_start); if(sleep_time > 0.0) @@ -1812,10 +1894,8 @@ int main(int argc, char **argv) { if(replay_buffer_size_secs == -1 && !(output_format->flags & AVFMT_NOFILE)) avio_close(av_format_context->pb); - if(dpy) { - XCompositeUnredirectWindow(dpy, src_window_id, CompositeRedirectAutomatic); + if(dpy) XCloseDisplay(dpy); - } unlink(pid_file); free(empty_audio); |