File size: 12,331 Bytes
ea55f45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*

* Copyright 2017-2024 NVIDIA Corporation.  All rights reserved.

*

* Please refer to the NVIDIA end user license agreement (EULA) associated

* with this source code for terms and conditions that govern your use of

* this software. Any use, reproduction, disclosure, or distribution of

* this software and related documentation outside the terms of the EULA

* is strictly prohibited.

*

*/

#pragma once

#include <iostream>
#include <algorithm>
#include <string.h>
#include <stdlib.h>
#include <mutex>
#include <thread>
#include <chrono>
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/freeglut_ext.h>
#include <cuda.h>
#include <cudaGL.h>
#include "../Utils/NvCodecUtils.h"
#include "../Utils/Logger.h"
#include "FramePresenter.h"

class FramePresenterGLUT;
static FramePresenterGLUT *pInstance;

/**

* @brief OpenGL utility class to display decoded frames using OpenGL textures

*/
class FramePresenterGLUT : public FramePresenter
{
public:
    /**

    *   @brief  FramePresenterGLUT constructor function. This will launch a rendering thread which will be fed by decoded frames

    *   @param  cuContext - CUDA Context handle

    *   @param  nWidth - Width of OpenGL texture

    *   @param  nHeight - Height of OpenGL texture

    */
    FramePresenterGLUT(CUcontext cuContext, int nWidth, int nHeight) :
        cuContext(cuContext), nWidth(nWidth), nHeight(nHeight)
    {
        pthMessageLoop = new NvThread(std::thread(ThreadProc, this));

        // This loop will ensure that OpenGL/glew/glut initialization is finished before we return from this constructor
        while (!pInstance) {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }
    }

    /**

    *   @brief  Destructor function. Also breaks glutMainLoopEvent

    */
    ~FramePresenterGLUT() {
        bStop = true;
        pthMessageLoop->join();
        delete pthMessageLoop;
    }

    /**

    *   @brief  Writes CUdeviceptr handle which is later used for OpenGL rendering

    *   @param  pdpFrame - Pointer to frame data into which decoded frame is written

    *   @param  pnPitch - Pointer to pitch value. This function will write pitch value based on nWidth

    *   @return False if dpFrame is NULL or rendering loop is exited

    *   @return True when input params are successfully updated

    */
    bool GetDeviceFrameBuffer(CUdeviceptr *pdpFrame, int *pnPitch) {
        if (bStop || !dpFrame) {
            return false;
        }

        *pdpFrame = (CUdeviceptr) dpFrame;
        *pnPitch = nWidth * 4;
        return true;
    }

    void SetText(std::string strText) {
        this->strText = strText;
    }

     /**

     *   @brief  Function to check whether underlying vendor is NVIDIA or not

     *   @return True if OpenGL vendor is NVIDIA

     *   @return False if OpenGL vendor is not NVIDIA

     */
     bool isVendorNvidia() {
        return this->vendorStatus;
     }

     void initWindowSystem() {
         // No op in GLUT
     }

     void initOpenGLResources() {
         // No op in GLUT
     }

     void releaseWindowSystem() {
         // No op in GLUT
     }

     void ReleaseDeviceFrameBuffer() {
        // No op in GLUT
     }

     int getWidth() {
        return this->nWidth;
     }

private:
     /**

     *   @brief  Thread launcher function. Launches the graphics initialization code

     *   @param  This - Pointer to FramePresenterGLUT object

     *   @return void

     */
     static void ThreadProc(FramePresenterGLUT *This) {
        This->Run();
    }

     /**

     *   @brief  Registered with glutDisplayFunc() as rendering function

     *   @return void

     */
     static void DisplayProc() {
        if (!pInstance) {
            return;
        }
        pInstance->Render();
    }

    static void CloseWindowProc() {
        if (!pInstance) {
            return;
        }
        // Enable the flag to break glutMainLoopEvent
        pInstance->bStop = true;
    }

    /**

    *   @brief  This function is responsible for OpenGL/glew/glut initialization and also for initiating display loop

    *   @return void

    */
    void Run() {
        int w = nWidth, h = nHeight;

        // Calculate the ratio to restrict viewport dimensions to 1280x720
        double r = (std::max)(nWidth / 1280.0, nHeight / 720.0);
        if (r > 1.0) {
            w = (int)(nWidth / r);
            h = (int)(nHeight / r);
        }

        int argc = 1;
        const char *argv[] = {"dummy"};
        glutInit(&argc, (char **)argv);
        glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
        glutInitWindowSize(w, h);
        glutCreateWindow("FramePresenterGLUT");
        glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);

        char * vendor = (char*) glGetString(GL_VENDOR);

        if (!strcmp(vendor, "NVIDIA Corporation")) {
            this->vendorStatus = true;
        } else {
            // To prevent infinite loop in constructor, initialize pInstance
            pInstance = this;
            this->vendorStatus = false;
            return;
        }

        glViewport(0, 0, w, h);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);

        glewInit();
        // Prepare OpenGL buffer object for uploading texture data
        glGenBuffersARB(1, &pbo);
        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
        glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, nWidth * nHeight * 4, NULL, GL_STREAM_DRAW_ARB);
        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

        // Create OpenGL texture and upload frame data
        glGenTextures(1, &tex);
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, tex);
        glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);

        // Create and initialize fragment program
        static const char *code =
            "!!ARBfp1.0\n"
            "TEX result.color, fragment.texcoord, texture[0], RECT; \n"
            "END";
        glGenProgramsARB(1, &shader);
        glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader);
        glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen(code), (GLubyte *)code);

        // Register display function
        glutDisplayFunc(DisplayProc);
        // Register window close event callback function
        glutCloseFunc(CloseWindowProc);

        ck(cuCtxSetCurrent(cuContext));
        ck(cuMemAlloc(&dpFrame, nWidth * nHeight * 4));
        ck(cuMemsetD8(dpFrame, 0, nWidth * nHeight * 4));

        pInstance = this;

        // Launch the rendering loop
        while (!bStop) {
            glutMainLoopEvent();
        }
        pInstance = NULL;

        ck(cuMemFree(dpFrame));

        glDeleteBuffersARB(1, &pbo);
        glDeleteTextures(1, &tex);
        glDeleteProgramsARB(1, &shader);
    }

    /**

    *   @brief  Rendering function called by glut

    *   @return void

    */
    void Render(void) {

        // Register the OpenGL buffer object with CUDA and map a CUdeviceptr onto it
        // The decoder code will receive this CUdeviceptr and copy the decoded frame into the associated device memory allocation
        CUgraphicsResource cuResource;
        ck(cuGraphicsGLRegisterBuffer(&cuResource, pbo, CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD));
        ck(cuGraphicsMapResources(1, &cuResource, 0));
        CUdeviceptr dpBackBuffer;
        size_t nSize = 0;
        ck(cuGraphicsResourceGetMappedPointer(&dpBackBuffer, &nSize, cuResource));

        CUDA_MEMCPY2D m = { 0 };
        m.srcMemoryType = CU_MEMORYTYPE_DEVICE;

        // Source is dpFrame into which Decode() function writes data of individual frame present in BGRA32 format
        // Destination is OpenGL buffer object mapped as a CUDA resource
        m.srcDevice = dpFrame;
        m.srcPitch = nWidth * 4;
        m.dstMemoryType = CU_MEMORYTYPE_DEVICE;
        m.dstDevice = dpBackBuffer;
        m.dstPitch = nSize / nHeight;
        m.WidthInBytes = nWidth * 4;
        m.Height = nHeight;
        ck(cuMemcpy2DAsync(&m, 0));

        ck(cuGraphicsUnmapResources(1, &cuResource, 0));
        ck(cuGraphicsUnregisterResource(cuResource));

        // Bind OpenGL buffer object and upload the data
        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, tex);
        glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, nWidth, nHeight, GL_BGRA, GL_UNSIGNED_BYTE, 0);
        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

        glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader);
        glEnable(GL_FRAGMENT_PROGRAM_ARB);
        glDisable(GL_DEPTH_TEST);

        // Specify vertex and texture co-ordinates
        glBegin(GL_QUADS);
        glTexCoord2f(0, (GLfloat)nHeight);
        glVertex2f(0, 0);
        glTexCoord2f((GLfloat)nWidth, (GLfloat)nHeight);
        glVertex2f(1, 0);
        glTexCoord2f((GLfloat)nWidth, 0);
        glVertex2f(1, 1);
        glTexCoord2f(0, 0);
        glVertex2f(0, 1);
        glEnd();
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
        glDisable(GL_FRAGMENT_PROGRAM_ARB);

        if (!strText.empty()) {
            PrintText(0, strText, 0, 0, true);
        }

        glutSwapBuffers();
        glutPostRedisplay();
    }

    static void PrintText(int iFont, std::string strText, int x, int y, bool bFillBackground) {
        struct {void *font; int d1; int d2;} fontData[] = {
            /*0*/ GLUT_BITMAP_9_BY_15,        13, 4,
            /*1*/ GLUT_BITMAP_8_BY_13,        11, 4,
            /*2*/ GLUT_BITMAP_TIMES_ROMAN_10, 9,  3,
            /*3*/ GLUT_BITMAP_TIMES_ROMAN_24, 20, 7,
            /*4*/ GLUT_BITMAP_HELVETICA_10,   10, 3,
            /*5*/ GLUT_BITMAP_HELVETICA_12,   11, 4,
            /*6*/ GLUT_BITMAP_HELVETICA_18,   16, 5,
        };
        const int nFont = sizeof(fontData) / sizeof(fontData[0]);

        if (iFont >= nFont) {
            iFont = 0;
        }
        void *font = fontData[iFont].font;
        int d1 = fontData[iFont].d1, d2 = fontData[iFont].d2, d = d1 + d2,
            w = glutGet(GLUT_WINDOW_WIDTH), h = glutGet(GLUT_WINDOW_HEIGHT);

        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        glLoadIdentity();
        glOrtho(0.0, w, 0.0, h, 0.0, 1.0);

        std::stringstream ss(strText);
        std::string str;
        int iLine = 0;
        while (std::getline(ss, str)) {
            glColor3f(1.0, 1.0, 1.0);
            if (bFillBackground) {
                glRasterPos2i(x, h - y - iLine * d - d1);
                for (char c : str) {
                    glutBitmapCharacter(font, c);
                }
                GLint pos[4];
                glGetIntegerv(GL_CURRENT_RASTER_POSITION, pos);
                glRecti(x, h - y - iLine * d, pos[0], h - y - (iLine + 1) * d);
                glColor3f(0.0, 0.0, 0.0);
            }
            glRasterPos2i(x, h - y - iLine * d - d1);
            for (char c : str) {
                glutBitmapCharacter(font, c);
            }
            iLine++;
        }

        glPopMatrix();
    }

private:
    bool bStop = false;         /*!< Variable to control rendering loop */
    int nWidth = 0, nHeight = 0;/*!< Dimensions of the frame being decoded */
    CUcontext cuContext = NULL;
    CUdeviceptr dpFrame = 0;    /*!< CUdeviceptr referenced by main thread to write decoded frames into */
    NvThread *pthMessageLoop = NULL;
    std::string strText;
    GLuint pbo;                 /*!< Buffer object to upload texture data */
    GLuint tex;                 /*!< OpenGL texture handle */
    GLuint shader;
    bool vendorStatus = false;  /*!< true if OpenGL vendor is NVIDIA, false otherwise */

};