aboutsummaryrefslogtreecommitdiff
path: root/ri/src/linux/riEGLOS.cpp
blob: 1b46c6b33b6a93973d417e0d1ae27b155eac5938 (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
/*------------------------------------------------------------------------
 *
 * EGL 1.3
 * -------
 *
 * Copyright (c) 2007 The Khronos Group Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and /or associated documentation files
 * (the "Materials "), to deal in the Materials without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Materials,
 * and to permit persons to whom the Materials are furnished to do so,
 * subject to the following conditions: 
 *
 * The above copyright notice and this permission notice shall be included 
 * in all copies or substantial portions of the Materials. 
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR
 * THE USE OR OTHER DEALINGS IN THE MATERIALS.
 *
 *//**
 * \file
 * \brief	Generic OS EGL functionality (not thread safe, no window rendering)
 * \note
  *//*-------------------------------------------------------------------*/

#include <stdio.h>
#include <unistd.h>   
#include <stdio.h>   
#include <fcntl.h>   
#include <stdlib.h>
#include <linux/fb.h>   
#include <sys/mman.h>   
 #include <sys/ioctl.h>

#include "egl.h"
#include "riImage.h"
#include <pthread.h>
#include <sys/errno.h>
#include <GLES2/gl2.h>
#include "esUtil.h"

#ifdef MINIEGL_DEBUG
#define DBG(M, ...) printf("[MINIEGL][%s]:" M "\n", __func__, ##__VA_ARGS__)
#else
#define DBG(M, ...)
#endif

#define MINIEGL_ERROR
#ifdef SHIM_ERROR
#define _ERR(M, ...) fprintf(stderr, "[MINIEGL][%s] %d: " M "\n", __func__, __LINE__, ##__VA_ARGS__)
#else
#define _ERR(M, ...)
#endif

typedef struct
{
// Handle to a program object
GLuint programObject;

} UserData;

namespace OpenVGRI
{

/*-------------------------------------------------------------------*//*!
* \brief	
* \param	
* \return	
* \note		
*//*-------------------------------------------------------------------*/

void* OSGetCurrentThreadID(void)
{
	return (void*)pthread_self();   //TODO this is not safe
}

/*-------------------------------------------------------------------*//*!
* \brief	
* \param	
* \return	
* \note		
*//*-------------------------------------------------------------------*/
static pthread_mutex_t mutex;
static int mutexRefCount = 0;
static bool mutexInitialized = false;
//acquired mutex cannot be deinited
//
void OSDeinitMutex(void)
{
	RI_ASSERT(mutexInitialized);
	RI_ASSERT(mutexRefCount == 0);

    int ret = pthread_mutex_destroy(&mutex);
    RI_ASSERT(ret != EINVAL);   //assert that the mutex has been initialized
    RI_ASSERT(ret != EAGAIN);   //assert that the maximum number of recursive locks hasn't been exceeded
    RI_ASSERT(!ret);    //check that there aren't other errors
    RI_UNREF(ret);
    
}
void OSAcquireMutex(void)
{
    if(!mutexInitialized)
    {
        int ret;
        pthread_mutexattr_t attr;
        ret = pthread_mutexattr_init(&attr);    //initially not locked
        RI_ASSERT(!ret);    //check that there aren't any errors
        ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);    //count the number of recursive locks
        RI_ASSERT(!ret);    //check that there aren't any errors
        ret = pthread_mutex_init(&mutex, &attr);
        pthread_mutexattr_destroy(&attr);
        RI_ASSERT(!ret);    //check that there aren't more errors
        RI_UNREF(ret);
        mutexInitialized = true;
    }
    int ret = pthread_mutex_lock(&mutex);
    RI_ASSERT(ret != EINVAL);   //assert that the mutex has been initialized
    RI_ASSERT(ret != EAGAIN);   //assert that the maximum number of recursive locks hasn't been exceeded
    RI_ASSERT(ret != EDEADLK);  //recursive mutexes shouldn't return this
    RI_ASSERT(!ret);    //check that there aren't other errors
    RI_UNREF(ret);
    mutexRefCount++;
}

void OSReleaseMutex(void)
{
    RI_ASSERT(mutexInitialized);
    mutexRefCount--;
    RI_ASSERT(mutexRefCount >= 0);
    int ret = pthread_mutex_unlock(&mutex);
    RI_ASSERT(ret != EPERM);    //assert that the current thread owns the mutex
    RI_ASSERT(!ret);    //check that there aren't more errors
    RI_UNREF(ret);
}

/*-------------------------------------------------------------------*//*!
* \brief    
* \param    
* \return   
* \note     
*//*-------------------------------------------------------------------*/

static bool isBigEndian()
{
    static const RIuint32 v = 0x12345678u;
    const RIuint8* p = (const RIuint8*)&v;
    RI_ASSERT (*p == (RIuint8)0x12u || *p == (RIuint8)0x78u);
    return (*p == (RIuint8)(0x12)) ? true : false;
}

/*-------------------------------------------------------------------*//*!
* \brief	
* \param	
* \return	
* \note		
*//*-------------------------------------------------------------------*/

#define FB_DEVICE   "/dev/fb0"

struct OSWindowContext
{
	ESContext *esContext;
	GLuint programObject;
	GLuint vertexShader;
	GLuint fragmentShader;
    EGLNativeWindowType window;
    unsigned int*       tmp;
    int                 tmpWidth;
    int                 tmpHeight;
/*    int                 fbfd;
    unsigned long       screensize;
    unsigned long       windowsize;
    char*               fbp;
    unsigned int*       tmp;
    int                 tmpWidth;
    int                 tmpHeight;
    struct              fb_var_screeninfo vinfo;   
    struct              fb_fix_screeninfo finfo; */
    
};

// Uniform index.
enum {
UNIFORM_VIDEOFRAME,
UNIFORM_INPUTCOLOR,
UNIFORM_THRESHOLD,
NUM_UNIFORMS
};
GLint uniforms[NUM_UNIFORMS];

// Attribute index.
enum {
ATTRIB_VERTEX,
ATTRIB_TEXTUREPOSITON,
NUM_ATTRIBUTES
};

static const GLfloat squareVertices[] = {
  -1.0f, -1.0f,
   1.0f, -1.0f,
  -1.0f,  1.0f,
   1.0f,  1.0f,
};

static const GLfloat textureVertices[] = {
    1.0f, 1.0f,
    1.0f, 0.0f,
    0.0f,  1.0f,
    0.0f,  0.0f,
};

GLuint LoadShader ( GLenum type, const char *shaderSrc )
{
   GLuint shader;
   GLint compiled;

   // Create the shader object
   shader = glCreateShader ( type );

   if ( shader == 0 )
    return 0;

   // Load the shader source
   glShaderSource ( shader, 1,(const GLchar * const *) shaderSrc, NULL );

   // Compile the shader
   glCompileShader ( shader );

   // Check the compile status
   glGetShaderiv ( shader, GL_COMPILE_STATUS, &compiled );

   if ( !compiled )
   {
      GLint infoLen = 0;

      glGetShaderiv ( shader, GL_INFO_LOG_LENGTH, &infoLen );

      if ( infoLen > 1 )
      {
         char* infoLog =(char *) malloc (sizeof(char) * infoLen );

         glGetShaderInfoLog ( shader, infoLen, NULL, infoLog );
         esLogMessage ( "Error compiling shader:\n%s\n", infoLog );

         free ( infoLog );
      }

      glDeleteShader ( shader );
      return 0;
   }

   return shader;

}



int OSGLESinit (void* v) {
OSWindowContext * ctx = (OSWindowContext *)v;
GLbyte vShaderStr[] = 
"attribute vec4 position; \n"
"attribute vec4 inputTextureCoordinate; \n"
" \n"
"varying vec2 textureCoordinate; \n"
" \n"
"void main() \n"
"{\n"
"    gl_Position = position;\n"
"    textureCoordinate = inputTextureCoordinate.xy;\n"
"}\n"
" \n";

GLbyte fShaderStr[] =
"varying highp vec2 textureCoordinate; \n"
" \n"
"uniform sampler2D openvgFrame; \n"
" \n"
"void main() \n"
"{ \n"
"    gl_FragColor = texture2D(openvgFrame, textureCoordinate); \n"
"} \n";

GLuint vertexShader;
GLuint fragmentShader;
GLuint programObject;
GLint linked;

	// Load the vertex/fragment shaders
	vertexShader = LoadShader(GL_VERTEX_SHADER,(const char *) vShaderStr );
	fragmentShader = LoadShader(GL_FRAGMENT_SHADER, (const char *)fShaderStr );

    programObject = glCreateProgram( );

	if ( programObject == 0 )
		return 0;

	glAttachShader(programObject, vertexShader );
	glAttachShader(programObject, fragmentShader );

    glBindAttribLocation(programObject, ATTRIB_VERTEX, "position");
    glBindAttribLocation(programObject, ATTRIB_TEXTUREPOSITON, "inputTextureCoordinate");

	glLinkProgram(programObject);

	glGetProgramiv ( programObject, GL_LINK_STATUS, &linked );

   if ( !linked ) 
   {   
      GLint infoLen = 0;

      glGetProgramiv ( programObject, GL_INFO_LOG_LENGTH, &infoLen );

      if ( infoLen > 1 )
      {
         char* infoLog =(char *) malloc (sizeof(char) * infoLen );

         glGetProgramInfoLog ( programObject, infoLen, NULL, infoLog );
         esLogMessage ( "Error linking program:\n%s\n", infoLog );

         free ( infoLog );
      }

      glDeleteProgram ( programObject );
      return GL_FALSE;
   }


	glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );

	ctx->programObject = programObject;
	ctx->vertexShader = vertexShader;
	ctx->fragmentShader = fragmentShader;
}


void* OSCreateWindowContext(EGLNativeWindowType window)
{
    try
    {
        OSWindowContext* ctx = RI_NEW(OSWindowContext, ());
        ctx->esContext = RI_NEW(ESContext, ());
        ctx->window = window;

        ctx->tmp = NULL;
        ctx->tmpWidth = window->width;
        ctx->tmpHeight = window->height;
/*
		OSGLESinit(ctx);

        // Open the framebuffer fb for reading and writing   
        ctx->fbfd = open("/dev/fb0", O_RDWR);   
        if (!ctx->fbfd) {   
            _ERR("Error: cannot open framebuffer device.\n");   
            return NULL;
        }   
        DBG("The framebuffer device was opened successfully.\n");


        // Get fixed screen information   
        if (ioctl(ctx->fbfd, FBIOGET_FSCREENINFO, &ctx->finfo)) {   
            _ERR("Error reading fixed information.\n");   
            return NULL;  
        }

        // Get variable screen information   
        if (ioctl(ctx->fbfd, FBIOGET_VSCREENINFO, &ctx->vinfo)) {   
            _ERR("Error reading variable information.\n");   
            return NULL;  
        }   

        // Figure out the size of the screen in bytes   
        ctx->screensize = ctx->vinfo.xres * ctx->vinfo.yres * ctx->vinfo.bits_per_pixel / 8;  

        // Figure out the size of the screen in bytes   
        ctx->windowsize = window->width * window->height * ctx->vinfo.bits_per_pixel / 8; 
   
        DBG("%dx%d, %dbpp, screen size = %d\n",  ctx->vinfo.xres, 
                                                ctx->vinfo.yres, 
                                                ctx->vinfo.bits_per_pixel, 
                                                ctx->screensize );  

        DBG("%dx%d, %dbpp, window size = %d\n", window->width, 
                                                window->height, 
                                                ctx->vinfo.bits_per_pixel, 
                                                ctx->windowsize ); 

        // Map the device to memory   
        ctx->fbp = (char *)mmap(0, ctx->screensize, PROT_READ | PROT_WRITE, MAP_SHARED,   
                                ctx->fbfd, 0);   
        if ((int)ctx->fbp == -1) {   
            _ERR("Error: failed to map framebuffer device to memory.\n");   
            return NULL;  
        }   
        DBG("The framebuffer device was mapped to memory successfully.\n");    
*/

        return ctx;
    }
    catch(std::bad_alloc)
    {
        return NULL;
    }
}

void OSDestroyWindowContext(void* context)
{

    OSWindowContext* ctx = (OSWindowContext*) context;

    if(ctx)
    {
/*        if(ctx->fbp) {
            munmap(ctx->fbp, ctx->screensize);
        }
        close(ctx->fbfd);
        RI_DELETE_ARRAY(ctx->tmp);
        RI_DELETE(ctx); */
    }
}

bool OSIsWindow(const void* context)
{
    OSWindowContext* ctx = (OSWindowContext*)context;
    if(ctx)
    {
        //TODO implement
        return true;
    }
    return false;
}

void OSGetWindowSize(const void* context, int& width, int& height)
{
    OSWindowContext* ctx = (OSWindowContext*)context;
    if(ctx)
    {
        width = ctx->esContext->width;
        height = ctx->esContext->height;
    }
    else
    {
        width = 0;
        height = 0;
    }
}

void OSBlitToWindow(void* context, const Drawable* drawable)
{
    OSWindowContext* ctx = (OSWindowContext*)context;
    VGImageFormat f;
    unsigned int w = drawable->getWidth();
    unsigned int h = drawable->getHeight();
    unsigned int y = 0;
    unsigned int    *fb_loc;
    unsigned int    *ctx_loc;
	GLuint videoFrameTexture;
	GLuint FrameBufferVGTexture;

    if(ctx)
    {
        printf("drawable: %dx%d\n", drawable->getWidth(), drawable->getHeight());  

 /*       int w = drawable->getWidth();
        int h = drawable->getHeight();

        printf("drawable: %dx%d\n", drawable->getWidth(), drawable->getHeight());  
*/
        if(!ctx->tmp || ctx->tmpWidth != w || ctx->tmpHeight != h)
        {
            RI_DELETE_ARRAY(ctx->tmp);
            ctx->tmp = NULL;
            try
            {
                ctx->tmp = RI_NEW_ARRAY(unsigned int, w*h); //throws bad_alloc
                ctx->tmpWidth = w;
                ctx->tmpHeight = h;
            }
            catch(std::bad_alloc)
            {
                _ERR("context temp memory alloc fail.\n"); 
                
            }
        }

        if(ctx->tmp)
        {
        f = VG_sARGB_8888;
        vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h);


	glGenTextures(1, &videoFrameTexture);
	glBindTexture(GL_TEXTURE_2D, videoFrameTexture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// This is necessary for non-power-of-two textures
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);




/*		glViewport(0, 0, w, h);
		glDisable(GL_DEPTH_TEST);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity(); */


		glActiveTexture(GL_TEXTURE0);
		glGenTextures(2, &FrameBufferVGTexture);
		glBindTexture(GL_TEXTURE_2D, FrameBufferVGTexture);

		glUniform1i(uniforms[UNIFORM_VIDEOFRAME], 0);   

		glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, 0, 0, squareVertices);
		glEnableVertexAttribArray(ATTRIB_VERTEX);
		glVertexAttribPointer(ATTRIB_TEXTUREPOSITON, 2, GL_FLOAT, 0, 0, textureVertices);
		glEnableVertexAttribArray(ATTRIB_TEXTUREPOSITON);

		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);






        //NOTE: we assume here that the display is always in sRGB color space

//            f = VG_sXBGR_8888;
//     --->             f = VG_sARGB_8888;
//            if(isBigEndian())
//               f = VG_sRGBX_8888;
        
        vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h);
//		glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, ctx->tmp);
        }

		eglSwapBuffers(ctx->esContext->eglDisplay, ctx->esContext->eglSurface);

/*
        if(ctx->fbp)
        {

            fb_loc = (unsigned int *)ctx->fbp;
            ctx_loc = ctx->tmp+w*(h-1);
            DBG("==fb_loc: %x, ctx_loc:%x ==", fb_loc, ctx_loc);  
            for( y = 0; y < h; y++){
                fb_loc += ctx->vinfo.xres;
                memcpy(fb_loc, ctx_loc, w*sizeof(unsigned int));
                ctx_loc -= w; 
            }
        }
	*/

	

    }
}

EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id)
{
    RI_UNREF(display_id);
    return (EGLDisplay)1;    //support only a single display
}

}   //namespace OpenVGRI