]> git.vomp.tv Git - vompclient.git/blob - osdopenvg.cc
Windows readme and makefile updated!
[vompclient.git] / osdopenvg.cc
1 /*
2     Copyright 2004-2005 Chris Tallon, 2006,2011-2012 Marten Richter
3
4     This file is part of VOMP.
5
6     VOMP is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     VOMP is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with VOMP; if not, write to the Free Software
18     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19 */
20
21
22 #include "osdopenvg.h"
23 #include "mtd.h"
24 #include "videoomx.h"
25 #include "surface.h"
26
27 #include "message.h"
28 #include "command.h"
29 #include "teletxt/txtfont.h"
30
31 #include <sys/syscall.h>
32 #include <fontconfig/fontconfig.h>
33 #include <vector>
34 #include <math.h>
35 #include <bcm_host.h>
36
37
38
39 #define EXTERNALPICTURE(name, fname, fileextension)  extern uint8_t name ## _data[]  asm("_binary_other_"#fname"_"#fileextension"_start"); \
40                                                                                                          extern uint8_t name ## _data_end[]  asm("_binary_other_"#fname"_"#fileextension"_end");
41
42 EXTERNAL_PICTS
43
44 #undef EXTERNALPICTURE
45
46
47 #define  BACKBUFFER_WIDTH 1280
48 #define  BACKBUFFER_HEIGHT 720
49
50
51 OsdOpenVG::OsdOpenVG()
52 {
53   vgmutex.Lock();
54   taskmutex.Lock();
55   lastrendertime=getTimeMS();
56   display_height=0;
57   display_width=0;
58   mode=0;
59   aspect_correction=1.;
60
61   freetype_inited=false;
62   wait_id=1;
63   const char *fontname="Droid Sans:style=Regular";
64   cur_fontname=(char*)malloc(strlen(fontname)+1);
65   strcpy(cur_fontname,fontname);
66
67 #define EXTERNALPICTURE(name, fname, fileextension) static_artwork_begin[sa_ ## name]=name ## _data;
68
69   EXTERNAL_PICTS
70
71 #undef EXTERNALPICTURE
72 #define EXTERNALPICTURE(name, fname, fileextension) static_artwork_end[sa_ ## name]=name ## _data_end;
73
74   EXTERNAL_PICTS
75
76 #undef EXTERNALPICTURE
77 }
78
79 OsdOpenVG::~OsdOpenVG()
80 {
81
82   if (initted)
83   {
84                 shutdown();
85   }
86
87   if (cur_fontname) free(cur_fontname);
88   if (freetype_inited) FT_Done_Face(ft_face);
89   if (!fontnames.size()) {
90           vector<char*>::iterator itty=fontnames.begin();
91           while (itty!=fontnames.end()) {
92                   free((void*)*itty);
93
94                   itty++;
95           }
96   }
97   if (!fontnames_keys.size()) {
98           vector<char*>::iterator itty=fontnames_keys.begin();
99           while (itty!=fontnames_keys.end()) {
100                   free((void*)*itty);
101
102                   itty++;
103           }
104     }
105
106   vgmutex.Unlock();
107   taskmutex.Unlock();
108 }
109
110
111
112 int OsdOpenVG::init(void* device)
113 {
114   if (initted) return 0;
115   reader.init();
116   Video* video = Video::getInstance();
117    //window=*((HWND*)device);
118
119    // May be this device specific part should go to a device specific child class
120
121    //init broadcom chipset (Move to video?)
122
123
124    //First get connection to egl
125    egl_display=eglGetDisplay(EGL_DEFAULT_DISPLAY);
126
127    if (egl_display==EGL_NO_DISPLAY) {
128            Log::getInstance()->log("OSD", Log::WARN, "Could not get egl display! %x",eglGetError());
129            vgmutex.Unlock();
130            return 0;
131    }
132
133
134
135    if (eglInitialize(egl_display, NULL, NULL)==EGL_FALSE) {
136            Log::getInstance()->log("OSD", Log::WARN, "Initialising display failed! %x",eglGetError());
137            vgmutex.Unlock();
138            return 0;
139    }
140
141
142    const char *query_str=eglQueryString(egl_display,EGL_CLIENT_APIS);
143    if (query_str) Log::getInstance()->logLongString("OSD", Log::NOTICE, query_str);
144    else Log::getInstance()->log("OSD", Log::WARN, "Could not query display %x",eglGetError());
145    query_str=eglQueryString(egl_display,EGL_EXTENSIONS);
146    if (query_str)    Log::getInstance()->logLongString("OSD", Log::NOTICE, query_str);
147    else Log::getInstance()->log("OSD", Log::WARN, "Could not query display %x",eglGetError());
148
149    if (eglBindAPI(EGL_OPENVG_API)==EGL_FALSE) {
150            Log::getInstance()->log("OSD", Log::WARN, "Binding openvg api failed! %x",eglGetError());
151            vgmutex.Unlock();
152            return 0;
153    }
154
155    const EGLint attributs[]={
156                  EGL_RED_SIZE,8,EGL_GREEN_SIZE, 8,EGL_BLUE_SIZE, 8,EGL_ALPHA_SIZE, 8,
157          EGL_SURFACE_TYPE, EGL_WINDOW_BIT|EGL_PBUFFER_BIT,
158          EGL_CONFORMANT, EGL_OPENVG_BIT,
159          EGL_NONE
160    }; // Here, we might have to select the resolution!
161
162
163    EGLint number;
164
165    if (eglChooseConfig(egl_display, attributs, &egl_ourconfig, 1, &number)==EGL_FALSE) {
166            Log::getInstance()->log("OSD", Log::WARN, "Choosing egl config failed! %x",eglGetError());
167            vgmutex.Unlock();
168            return 0;
169    }
170
171
172
173    egl_context=eglCreateContext(egl_display,egl_ourconfig,NULL,NULL);
174    if (egl_context==EGL_NO_CONTEXT) {
175            Log::getInstance()->log("OSD", Log::WARN, "Creating egl context failed! %x",eglGetError());
176            vgmutex.Unlock();
177            return 0;
178    }
179
180    // warning broadcom specific, get display size!
181    display_width=display_height=0;
182    if (graphics_get_display_size(0, &display_width, &display_height)<0) {
183            Log::getInstance()->log("OSD", Log::WARN, "Getting display size failed! (BCM API) ");
184            vgmutex.Unlock();
185            return 0;
186    }
187    Log::getInstance()->log("OSD", Log::NOTICE, "Displaysize is %d x %d ",display_width, display_height);
188    VC_RECT_T dst_rect ={0,0,display_width,display_height};
189    VC_RECT_T src_rect={0,0,BACKBUFFER_WIDTH <<16,BACKBUFFER_HEIGHT<<16};
190    VC_RECT_T src_rect_bg={0,0,16<<16,16<<16};
191    VC_RECT_T src_rect_im={0,0,16,16};
192
193    uint32_t back_image_ptr;
194    bcm_backres=vc_dispmanx_resource_create(VC_IMAGE_RGBX32,16,16,&back_image_ptr);
195    unsigned int color[16*16];
196    DrawStyle bg=DrawStyle::WALLPAPER;
197    if (bg.ft!=DrawStyle::GradientLinear) {
198            bg.grad_col[0]=bg;
199    }
200    //memset(color,0xFF,sizeof(unsigned int)*4*8);
201    for (int j=0;j<16;j++) {
202            int helpr=(((15-j)*bg.red)+(j*bg.grad_col[0].red))/15;
203            int helpb=(((15-j)*bg.blue)+(j*bg.grad_col[0].blue))/15;
204            int helpg=(((15-j)*bg.green)+(j*bg.grad_col[0].green))/15;
205            //unsigned int cur_col=help | (help<< 8)  | (help<< 16)  | (0xFF<< 24);
206            unsigned int cur_col=helpr  | (helpg<< (8))  | (helpb<< (16))  | (0xFF<< (24));
207            for (int i=0;i<16;i++) {
208                    color[i+16*j]=cur_col;
209            }
210    }
211    vc_dispmanx_resource_write_data(bcm_backres,VC_IMAGE_RGBX32,16*4,color,&src_rect_im);
212
213    DISPMANX_UPDATE_HANDLE_T  bcm_update;
214    bcm_display=vc_dispmanx_display_open(0);
215    bcm_update=vc_dispmanx_update_start(0);
216    bcm_element=vc_dispmanx_element_add(bcm_update,bcm_display,
217          2,&dst_rect, 0,
218          &src_rect,DISPMANX_PROTECTION_NONE,0, 0, (DISPMANX_TRANSFORM_T) 0);
219
220
221    bcm_background=vc_dispmanx_element_add(bcm_update,bcm_display,
222             0,&dst_rect,bcm_backres ,
223             &src_rect_bg,DISPMANX_PROTECTION_NONE,0, 0, (DISPMANX_TRANSFORM_T) 0);
224
225    vc_dispmanx_update_submit_sync(bcm_update);
226
227
228
229    static EGL_DISPMANX_WINDOW_T nativewindow;
230    nativewindow.element=bcm_element;
231    nativewindow.height=BACKBUFFER_HEIGHT;
232    nativewindow.width=BACKBUFFER_WIDTH;
233
234    egl_surface = eglCreateWindowSurface(egl_display,egl_ourconfig, &nativewindow,NULL );
235    if (egl_surface==EGL_NO_SURFACE) {
236            Log::getInstance()->log("OSD", Log::WARN, "Creating egl window surface failed!");
237            vgmutex.Unlock();
238            return 0;
239    }
240    Log::getInstance()->log("OSD", Log::DEBUG, "Making egl current in1%d",syscall(SYS_gettid));
241    if (eglMakeCurrent(egl_display, egl_surface, egl_surface, egl_context)== EGL_FALSE) {
242            Log::getInstance()->log("OSD", Log::WARN, "Making egl Current failed");
243            vgmutex.Unlock();
244                    return 0;
245    }
246    // Test stuff
247
248    query_str=(const char*)vgGetString(VG_VERSION) ;
249    if (query_str) Log::getInstance()->logLongString("OSD", Log::NOTICE, query_str);
250    else Log::getInstance()->log("OSD", Log::WARN, "Could not query display %x",vgGetError());
251
252    query_str=(const char*)vgGetString(VG_VENDOR) ;
253    if (query_str) Log::getInstance()->logLongString("OSD", Log::NOTICE, query_str);
254    else Log::getInstance()->log("OSD", Log::WARN, "Could not query display %x",vgGetError());
255
256    query_str=(const char*)vgGetString(VG_RENDERER) ;
257    if (query_str) Log::getInstance()->logLongString("OSD", Log::NOTICE, query_str);
258    else Log::getInstance()->log("OSD", Log::WARN, "Could not query display %x",vgGetError());
259
260    query_str=(const char*)vgGetString(VG_EXTENSIONS) ;
261    if (query_str) Log::getInstance()->logLongString("OSD", Log::NOTICE, query_str);
262    else Log::getInstance()->log("OSD", Log::WARN, "Could not query display %x",vgGetError());
263
264   aspect_correction= ((float)BACKBUFFER_HEIGHT)/576.f/(((float)BACKBUFFER_WIDTH)/720.f);
265   initPaths();
266   if (!fontnames.size()) {
267           //inspired by and copied from vdr's code
268           FcInit();
269           FcObjectSet *objset= FcObjectSetBuild(FC_FAMILY, FC_STYLE, NULL);
270           FcPattern * pattern=FcPatternCreate();
271           FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
272           FcFontSet* fonts = FcFontList(NULL, pattern, objset);
273           for (int i=0; i<fonts->nfont;i++) {
274                   char *s = (char *)FcNameUnparse(fonts->fonts[i]);
275
276                   if (s) {
277                           char *c= strchr(s,':');
278                           if (c) {
279                                   char *s2= strchr(c+1,',');
280                                   if (s2) *s2=0;
281                           }
282                           char *p=strchr(s,',');
283                           if (p) {
284                                   if (!c) *p=0;
285                                   else memmove(p,c,strlen(c)+1);
286                           }
287                           char *key=(char*)malloc(strlen(s)+1);
288                           strcpy(key,s);
289                           fontnames_keys.push_back(key);
290                           char *s2=strstr(s,"style=");
291                           if (s2) {
292                                   memmove(s2,s2+6,strlen(s2+6)+1);
293                           }
294                           fontnames.push_back(s);
295                   }
296           }
297           FcFontSetDestroy(fonts);
298           FcPatternDestroy(pattern);
299           FcObjectSetDestroy(objset);
300   }
301
302   if (!loadFont(false)) {
303           return 0;
304   }
305   vgttfont=vgCreateFont(0);
306   vgttpaint=vgCreatePaint();
307   vgSetParameteri( vgttpaint, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
308   vgSetColor(vgttpaint,0xffffffff);
309
310   eglSwapInterval(egl_display, 1 );
311
312   Log::getInstance()->log("OSD", Log::DEBUG, "Making egl current out 1%d",syscall(SYS_gettid));
313   eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
314   //Now we will create the Screen
315   initted = 1; // must set this here or create surface won't work
316
317
318   /*if (((VideoOMX*)Video::getInstance())->initUsingOSDObjects()!=1) { //call Video for init  stuff
319           return 0;
320   }*/
321
322
323   threadStart();
324   taskmutex.Unlock();
325   vgmutex.Unlock();
326
327 #ifdef PICTURE_DECODER_OMX
328     imageomx=new ImageOMX(&reader);
329         reader.addDecoder(imageomx);
330 #endif
331
332
333   return 1;
334 }
335
336 void OsdOpenVG::getScreenSize(int &width, int &height)
337 {
338         width=BACKBUFFER_WIDTH;
339         height=BACKBUFFER_HEIGHT;
340 }
341
342 void OsdOpenVG::getRealScreenSize(int &width, int &height)
343 {
344         width=display_width;
345         height=display_height;
346 }
347
348 bool OsdOpenVG::screenShot(void *buffer, int width, int height, bool osd /*include osd*/)
349 {
350         if (!initted) return false;
351         if (!buffer) return false;
352
353         DISPMANX_RESOURCE_HANDLE_T res;
354         DISPMANX_DISPLAY_HANDLE_T display;
355
356         uint32_t image_ptr;
357         VC_RECT_T rect;
358         res=vc_dispmanx_resource_create(VC_IMAGE_RGBA32,width,height,&image_ptr);
359         display=vc_dispmanx_display_open(0);
360         if (!osd) {
361                 vc_dispmanx_snapshot(display, res,
362                                 (DISPMANX_TRANSFORM_T)(DISPMANX_SNAPSHOT_NO_RGB|DISPMANX_SNAPSHOT_FILL/*|DISPMANX_SNAPSHOT_PACK*/));
363         }
364         else
365         {
366                 vc_dispmanx_snapshot(display, res,
367                                 (DISPMANX_TRANSFORM_T)(DISPMANX_SNAPSHOT_FILL));
368         }
369         vc_dispmanx_rect_set(&rect,0,0,width,height);
370         vc_dispmanx_resource_read_data(res, &rect, buffer, width*4);
371         vc_dispmanx_resource_delete(res);
372         vc_dispmanx_display_close(display);
373         return true;
374
375 }
376
377
378 void OsdOpenVG::initPaths()
379 {
380
381
382         VGPath current;
383         current=vgCreatePath(VG_PATH_FORMAT_STANDARD,
384                         VG_PATH_DATATYPE_F,1.f,0.f,
385                         0,0,VG_PATH_CAPABILITY_ALL);
386
387         vguLine(current,0.f,0.f,1.f,0.f);
388         // HorzLine
389         std_paths[PIHorzLine]=current;
390
391         current=vgCreatePath(VG_PATH_FORMAT_STANDARD,
392                                 VG_PATH_DATATYPE_F,1.f,0.f,
393                                 0,0,VG_PATH_CAPABILITY_ALL);
394         vguLine(current,0.f,0.f,0.f,1.f);
395         // VertLine
396         std_paths[PIVertLine]=current;
397
398         current=vgCreatePath(VG_PATH_FORMAT_STANDARD,
399                                 VG_PATH_DATATYPE_F,1.f,0.f,
400                                 0,0,VG_PATH_CAPABILITY_ALL);
401         //vguRect(current,0.f,0.f,1.f,1.f);
402         vguRect(current,0.f,0.f,1.f,1.f);
403         // Rectabgle
404         std_paths[PIRectangle]=current;
405
406         current=vgCreatePath(VG_PATH_FORMAT_STANDARD,
407                                 VG_PATH_DATATYPE_F,1.f,0.f,
408                                 0,0,0);
409         vguEllipse(current,0.f,0.f,1.f,1.f);
410         // Point
411         std_paths[PIPoint]=current;
412
413 }
414
415 void OsdOpenVG::destroyPaths()
416 {
417         vgDestroyPath(std_paths[PIHorzLine]);
418         vgDestroyPath(std_paths[PIVertLine]);
419         vgDestroyPath(std_paths[PIRectangle]);
420         vgDestroyPath(std_paths[PIPoint]);
421
422 }
423
424 int OsdOpenVG::stopUpdate()
425 {
426         threadStop();
427         processTasks();
428         return 1;
429 }
430 /*
431 void OsdOpenVG::purgeAllReferences()
432 {
433         images_ref.clear();
434         styles_ref.clear(); // remove all references
435
436
437         map<void *,ImageIndex>::iterator mitty=monobitmaps.begin();
438         while (mitty!=monobitmaps.end()) {
439                 vgDestroyImage((VGImage)(*mitty).second);
440                 mitty++;
441         }
442         monobitmaps.clear();
443
444         /*map<string,ImageIndex>::iterator jitty=jpegs.begin();
445         while (jitty!=jpegs.end()) {
446                 vgDestroyImage((VGImage)(*jitty).second);
447                 jitty++;
448         }
449         jpegs.clear();*
450
451         map<TVMediaInfo,ImageIndex>::iterator titty=tvmedias.begin();
452         while (titty!=tvmedias.end()) {
453                 vgDestroyImage((VGImage)(*titty).second);
454                 titty++;
455         }
456         tvmedias.clear();
457
458         map<pair<Colour*,unsigned int>,unsigned int>::iterator sitty=styles.begin();
459         while (sitty!=styles.end()) {
460                 vgDestroyPaint((VGPaint)(*sitty).second);
461                 sitty++;
462         }
463         styles.clear();
464
465 }*/
466
467 int OsdOpenVG::shutdown()
468 {
469   reader.shutdown();
470 #ifdef PICTURE_DECODER_OMX
471         if (imageomx) reader.removeDecoder(imageomx);
472         imageomx=NULL;
473 #endif
474
475   if (!initted) return 0;
476
477   initted = 0;
478   Log::getInstance()->log("OSD", Log::DEBUG, "shutdown mark1");
479   threadStop();
480   Log::getInstance()->log("OSD", Log::DEBUG, "shutdown mark1a");
481   //(((VideoOMX*)Video::getInstance())->shutdownUsingOSDObjects());
482   if (eglMakeCurrent(egl_display, egl_surface, egl_surface, egl_context)== EGL_FALSE) {
483           Log::getInstance()->log("OSD", Log::WARN, "Making egl Current failed in shutdown %x",eglGetError());
484   }
485   if (eglBindAPI(EGL_OPENVG_API)==EGL_FALSE) {
486           Log::getInstance()->log("OSD", Log::WARN, "Binding openvg api thread failed! %x",eglGetError());
487   }
488
489   Log::getInstance()->log("OSD", Log::DEBUG, "shutdown mark2");
490   processTasks();
491   Log::getInstance()->log("OSD", Log::DEBUG, "shutdown mark3");
492
493   taskmutex.Lock();
494   vgmutex.Lock();
495
496
497
498   //purgeAllReferences();
499
500   vgDestroyFont(vgfont);
501   vgDestroyFont(vgttfont);
502   vgDestroyPaint(vgttpaint);
503   destroyPaths();
504   float colclear[]={0.8f,0.8f,0.8f,1.f};
505   vgSetfv(VG_CLEAR_COLOR,4,colclear);
506   vgClear(0,0,BACKBUFFER_WIDTH,BACKBUFFER_HEIGHT);
507   eglSwapBuffers(egl_display, egl_surface);
508   Log::getInstance()->log("OSD", Log::DEBUG, "Making egl current out final");
509   eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
510   if (eglDestroySurface(egl_display,egl_surface)==EGL_FALSE) {
511           Log::getInstance()->log("OSD", Log::ERR, "eglDestroySurface failed %x",eglGetError());
512   }
513   if (eglDestroyContext(egl_display,egl_context)==EGL_FALSE) {
514           Log::getInstance()->log("OSD", Log::ERR, "eglDestroyContext failed %x",eglGetError());
515   }
516   if (eglTerminate(egl_display )==EGL_FALSE) {
517           Log::getInstance()->log("OSD", Log::ERR, "eglTerminate failed %x",eglGetError());
518   }
519
520   DISPMANX_UPDATE_HANDLE_T  bcm_update;
521   bcm_update=vc_dispmanx_update_start(0);
522
523   vc_dispmanx_element_remove(bcm_update,bcm_element);
524   vc_dispmanx_element_remove(bcm_update,bcm_background);
525   vc_dispmanx_update_submit_sync(bcm_update);
526   vc_dispmanx_resource_delete(bcm_backres);
527   vc_dispmanx_display_close(bcm_display);
528
529
530
531   return 1;
532 }
533
534
535
536
537 void OsdOpenVG::threadMethod()
538 {
539         // We have to claim the egl context for this thread
540         Log::getInstance()->log("OSD", Log::NOTICE, "Entering drawing thread");
541         if (eglMakeCurrent(egl_display, egl_surface, egl_surface, egl_context)== EGL_FALSE) {
542                 Log::getInstance()->log("OSD", Log::WARN, "Making egl Current failed in thread %x",eglGetError());
543                 return;
544         }
545         if (eglBindAPI(EGL_OPENVG_API)==EGL_FALSE) {
546                 Log::getInstance()->log("OSD", Log::WARN, "Binding openvg api thread failed! %x",eglGetError());
547                 return;
548         }
549         int ts=0;
550         while (true)
551         {
552                 ts=1;
553                 unsigned int waittime=1;
554
555                 if (initted) {
556
557                         long long time1 = getTimeMS();
558                         if ((time1 - lastrendertime) > 200) {//5 fps for OSD updates are enough, avoids tearing
559                                 InternalRendering();
560                                 lastrendertime = getTimeMS();
561
562                         }
563                         if (processTasks()) ts=0;
564                 }
565                 if (!threadIsActive()) {
566                         if (eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT )== EGL_FALSE) {
567                                    Log::getInstance()->log("OSD", Log::WARN, "Making egl Current out thread failed");
568                         }
569                         threadCheckExit();
570                 }
571                 if (ts!=0) {
572                         struct timespec target_time;
573                         clock_gettime(CLOCK_REALTIME,&target_time);
574                         target_time.tv_nsec+=1000000LL*ts;
575                         if (target_time.tv_nsec>999999999) {
576                                 target_time.tv_nsec-=1000000000L;
577                                 target_time.tv_sec+=1;
578                         }
579                         threadLock();
580                         threadWaitForSignalTimed(&target_time);
581                         threadUnlock();
582                 }
583                 //Sleep(1);
584         }
585         eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
586 }
587
588
589 void OsdOpenVG::threadPostStopCleanup()
590 {
591         //Doing nothing
592         //goo;
593         Log::getInstance()->log("OSD", Log::NOTICE, "Exiting drawing thread");
594 }
595
596 void OsdOpenVG::InternalRendering(){
597         vgmutex.Lock();
598         Colour bg=DrawStyle::WALLPAPER;
599     float colclear[]={1.f,1.0f,1.f,1.f};
600     if (bg.alpha==0) colclear[3]=0.f;
601     vgSetfv(VG_CLEAR_COLOR,4,colclear);
602         vgClear(0,0,BACKBUFFER_WIDTH,BACKBUFFER_HEIGHT);
603         vgSeti(VG_BLEND_MODE, VG_BLEND_SRC);
604
605
606         drawSurfaces(); //iterate through and draws all commands
607
608         //Show it to the user!
609         eglSwapBuffers(egl_display, egl_surface);
610         vgmutex.Unlock();
611
612 }
613
614 /*font stuff*/
615
616 float OsdOpenVG::getFontHeight()
617 {
618         return font_height; //dummy
619 }
620 float OsdOpenVG::getCharWidth(wchar_t c)
621 {
622         if (c<256) return byte_char_width[c];
623         unsigned int glyph_index=FT_Get_Char_Index(ft_face,c);
624         return font_exp_x[glyph_index];
625 }
626
627 unsigned int OsdOpenVG::loadTTchar(cTeletextChar c)
628 {
629         unsigned int glyph_index=c.getGlyphIndex();
630         if (tt_font_chars.find(glyph_index)!=tt_font_chars.end())
631         {
632                 return glyph_index;
633         }
634
635         unsigned int buffer[10];
636         const VGfloat glyphOrigin[] = { 0.f, 0.f };
637         const VGfloat escapement[] = { 12.f, 0.f };
638         unsigned int * charmap = GetFontChar(c, buffer);
639         if (!charmap) { //invalid char
640                 return 0;
641         }
642         for (int i=0;i<10;i++) {
643                 buffer[i]=charmap[i]>>4;
644         }
645
646         VGImage handle = vgCreateImage(
647                         VG_A_8,
648                         12,
649                         10,
650                         VG_IMAGE_QUALITY_NONANTIALIASED | VG_IMAGE_QUALITY_FASTER
651                                         | VG_IMAGE_QUALITY_BETTER);
652         vgImageSubData(handle, buffer, 4, VG_A_1, 0, 0, 12, 10);
653         vgSetGlyphToImage(
654                         vgttfont,
655                         glyph_index,
656                         handle, (VGfloat*)glyphOrigin, (VGfloat*)escapement);
657         vgDestroyImage(handle);
658         tt_font_chars[glyph_index]=1;
659
660         return glyph_index;
661 }
662
663 int OsdOpenVG::getFontNames(const char *** names,const char *** names_keys)
664 {
665         *names=(const char**)&(fontnames[0]);
666         *names_keys=(const char**)&(fontnames_keys[0]);
667         return fontnames.size();
668 }
669
670 void OsdOpenVG::setFont(const char * fontname) {
671
672         if (strcmp(fontname,cur_fontname)) {
673                 // new font!
674                 if (cur_fontname) free(cur_fontname);
675                 cur_fontname=(char*)malloc(strlen(fontname)+1);
676                 strcpy(cur_fontname,fontname);
677
678                 struct OpenVGCommand comm;
679                 comm.task=OVGreplacefont;
680                 putOpenVGCommand(comm,false);
681
682
683         }
684 }
685
686
687 int  OsdOpenVG::loadFont(bool newfont)
688 {
689         int error;
690         float font_size=16.f;
691         if (!freetype_inited) {
692                 error=FT_Init_FreeType(&ft_library);
693                 if (error)
694                 {
695                         Log::getInstance()->log("OSD", Log::WARN, "Could not load freetype %x",error);
696                         return 0;
697                 }
698         }
699
700         if (!freetype_inited || newfont) {
701                 //first get the filename algorith extracted from vdr by Klaus Schmidinger
702                 FcInit();
703                 FcPattern *pattern=FcNameParse((FcChar8*)cur_fontname);
704                 FcPatternAddBool(pattern,FC_SCALABLE,FcTrue);
705                 FcConfigSubstitute(NULL,pattern,FcMatchPattern);
706                 FcDefaultSubstitute(pattern);
707                 FcResult fres;
708                 FcFontSet *fonts=FcFontSort(NULL,pattern,FcFalse,NULL,&fres);
709                 FcChar8 *filename=NULL;
710                 if (fonts) {
711                         for (int i=0;i<fonts->nfont;i++) {
712                                 FcBool canscale;
713                                 FcPatternGetBool(fonts->fonts[i],FC_SCALABLE,0,&canscale);
714                                 if (canscale){
715                                         FcPatternGetString(fonts->fonts[i],FC_FILE,0,&filename);
716                                         break;
717                                 }
718                         }
719                         FcFontSetDestroy(fonts);
720                 } else {
721                         Log::getInstance()->log("OSD", Log::CRIT, "Could not locate a font! Abort!");
722                         return 0;
723                 }
724                 FcPatternDestroy(pattern);
725
726                 Log::getInstance()->log("OSD", Log::NOTICE, "Load Font %s: %s", cur_fontname,filename);
727                 // second load the font
728                 FT_Face     new_ft_face;
729                 error=FT_New_Face(ft_library,(const char*)filename,0,&new_ft_face );
730                 if (error) {
731                         Log::getInstance()->log("OSD", Log::WARN, "Could not load font face %x %s",error,filename);
732                         return 0;
733                 }
734                 error=FT_Set_Char_Size(new_ft_face,0,font_size*256,0,0 /*dpi*/);
735                 if (error) {
736                         FT_Done_Face(new_ft_face);
737                         Log::getInstance()->log("OSD", Log::WARN, "Could not set  face size %x",error);
738                         return 0;
739                 }
740                 FT_Face old_ft_face=ft_face; // do it thread safe
741                 ft_face=new_ft_face;
742                 if (freetype_inited) FT_Done_Face(old_ft_face);//
743                 freetype_inited=true;
744         }
745         vgfont=vgCreateFont(0);
746         FT_ULong cur_char;
747         FT_UInt glyph;
748         font_height=ft_face->size->metrics.height/256.f;
749         cur_char = FT_Get_First_Char(ft_face,&glyph);
750         vector<VGubyte> segments;
751         vector<VGfloat> coord;
752         segments.reserve(256);
753         coord.reserve(1024);
754         //Log::getInstance()->log("OSD", Log::DEBUG, "Create Glyph test %d %x %x %d",cur_char,font_data_end,font_data,glyph);
755         while (glyph !=0)
756         {
757                 error=FT_Load_Glyph(ft_face,glyph,FT_LOAD_DEFAULT);
758                 if (error){
759                         FT_Done_Face(ft_face);
760                         Log::getInstance()->log("OSD", Log::WARN, "Could not load glyph %x",error);
761                         return 0;
762                 }
763                 VGPath path;
764                 FT_Outline ot=ft_face->glyph->outline;
765                 segments.clear();
766                 coord.clear();
767
768                 if (ot.n_contours ==0) {
769                         path=VG_INVALID_HANDLE;
770                 } else {
771                         path=vgCreatePath(VG_PATH_FORMAT_STANDARD, VG_PATH_DATATYPE_F,
772                                         1.0f,0.f,0,0,VG_PATH_CAPABILITY_ALL);
773
774                         /* convert glyph */
775                         FT_Vector *pt=ot.points;
776                         const char *tags=ot.tags;
777                         const short* cont=ot.contours;
778                         short n_cont=ot.n_contours;
779                         short n_point=ot.n_points;
780                         short last_cont=0;
781                         for (short point=0;n_cont!=0;cont++,n_cont--) {
782                                 short next_cont=*cont+1;
783                                 bool first=true;
784                                 char last_tag=0;
785                                 short first_point=point;
786                                 //Log::getInstance()->log("OSD", Log::DEBUG, "runs %d",*cont);
787                                 for (;point<next_cont;point++) {
788                                         char tag=tags[point];
789                                         FT_Vector fpoint=pt[point];
790                                 //      Log::getInstance()->log("OSD", Log::DEBUG, "tag %d point %d %d: %d %d",tag,fpoint.x,fpoint.y,point,n_point);
791                                         if (first) {
792                                                 segments.push_back(VG_MOVE_TO);
793                                                 first=false;
794                                         } else if (tag &0x1) { //on curve
795                                                 if (last_tag &0x1) {
796                                                         segments.push_back(VG_LINE_TO);
797                                                 } else if (last_tag &0x2){
798                                                         segments.push_back(VG_CUBIC_TO);
799                                                 } else {
800                                                         segments.push_back(VG_QUAD_TO);
801                                                 }
802
803                                         } else {
804                                                 if (!(tag &0x2)){
805                                                         if (!(last_tag &0x1)) {
806                                                                 segments.push_back(VG_QUAD_TO);
807                                                                 int coord_size=coord.size();
808                                                                 VGfloat x=(coord[coord_size-2]+ ((float)fpoint.x)/256.f)*0.5f*aspect_correction;
809                                                                 VGfloat y=(coord[coord_size-1]+(font_size- ((float)fpoint.y)/256.f))*0.5f;
810                                                                 coord.push_back(x);
811                                                                 coord.push_back(y);
812                                                         }
813                                                 }
814
815
816                                         }
817                                         last_tag=tag;
818                                         coord.push_back(((float)fpoint.x)*aspect_correction/256.);
819                                         coord.push_back(font_size-((float)fpoint.y)/256.);
820                                         //Log::getInstance()->log("OSD", Log::DEBUG, "Create APD Glyph coord %d %d %g %g",fpoint.x,fpoint.y,coord[coord.size()-2],coord[coord.size()-1]);
821                                 }
822                                 if (!(last_tag &0x1)) {
823                                         if (last_tag &0x2) {
824                                                 segments.push_back(VG_CUBIC_TO);
825                                         } else {
826                                                 segments.push_back(VG_QUAD_TO);
827                                         }
828                                         coord.push_back(((float)pt[first_point].x)*aspect_correction/256.);
829                                         coord.push_back(font_size-((float)pt[first_point].y)/256.);
830                                 }
831                                 //segments.push_back(VG_CLOSE_PATH);
832
833
834                         }
835                         vgAppendPathData(path,segments.size(),&segments[0],&coord[0]);
836                         int n=0;
837                 /*      for (int m=0;m<segments.size();m++) {
838                                 switch (segments[m])
839                                 {
840                                 case VG_MOVE_TO:
841                                         Log::getInstance()->log("OSD", Log::DEBUG, "Move To %g %g",coord[n],coord[n+1]);n+=2; break;
842                                 case VG_LINE_TO:
843                                         Log::getInstance()->log("OSD", Log::DEBUG, "Line To %g %g",coord[n],coord[n+1]);n+=2; break;
844                                 case VG_CUBIC_TO:
845                                         Log::getInstance()->log("OSD", Log::DEBUG, "Cubic To %g %g %g %g %g %g",coord[n],coord[n+1],coord[n+2],coord[n+3],coord[n+4],coord[n+5]);n+=6; break;
846                                 case VG_QUAD_TO:
847                                         Log::getInstance()->log("OSD", Log::DEBUG, "Quad To %g %g %g %g",coord[n],coord[n+1],coord[n+2],coord[n+3]);n+=4; break;
848                                 case VG_CLOSE_PATH:
849                                         Log::getInstance()->log("OSD", Log::DEBUG, "Close Path"); break;
850                                 }
851
852                         }*/
853                         //vguRect(path,0.f,0.f,1.f,1.f);
854                         //Log::getInstance()->log("OSD", Log::DEBUG, "Create APD Glyph %d %x",segments.size(),vgGetError());
855                 }
856                 VGfloat ori[]={0.f,0.f};
857                 VGfloat esp[]={ft_face->glyph->advance.x/256.f*aspect_correction,ft_face->glyph->advance.y/256.f};
858                 font_exp_x[glyph]=ft_face->glyph->advance.x/256.f*aspect_correction; //recalculate
859
860                 vgSetGlyphToPath(vgfont,glyph,path,VG_FALSE,ori,esp);
861                 //Log::getInstance()->log("OSD", Log::DEBUG, "Create Glyph %d %d %x",path,glyph,vgGetError());
862                 if (path!=VG_INVALID_HANDLE) {
863                         vgDestroyPath(path);
864                 }
865                 cur_char = FT_Get_Next_Char(ft_face,cur_char,&glyph);
866         }
867         for (int i=0;i<256;i++) {
868                 unsigned int glyph_index=FT_Get_Char_Index(ft_face,i);
869                 byte_char_width[i]=font_exp_x[glyph_index];
870         }
871         return 1;
872 }
873
874
875 void OsdOpenVG::drawSetTrans(SurfaceCommands & sc)
876 {
877         vgSeti(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE);
878         vgLoadIdentity();
879         vgScale(((float)BACKBUFFER_WIDTH)/720.f, -((float)BACKBUFFER_HEIGHT)/576.f);
880         vgTranslate(0.f+sc.x,-576.f+sc.y);
881
882         vgSeti(VG_MATRIX_MODE, VG_MATRIX_GLYPH_USER_TO_SURFACE);
883         vgLoadIdentity();
884     vgScale(((float)BACKBUFFER_WIDTH)/720.f, -((float)BACKBUFFER_HEIGHT)/576.f);
885         vgTranslate(0.f+sc.x,-576.f+sc.y);
886
887         vgSeti(VG_MATRIX_MODE, VG_MATRIX_IMAGE_USER_TO_SURFACE);
888         vgLoadIdentity();
889         vgScale(((float)BACKBUFFER_WIDTH)/720.f, -((float)BACKBUFFER_HEIGHT)/576.f);
890         vgTranslate(0.f+sc.x,-576.f+sc.y);
891     clip_shift_x=sc.x;
892     clip_shift_y=sc.y;
893
894
895
896         //vgTranslate(0.f+sc.x,576.f-sc.y);
897         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Translate %g %g",sc.x,sc.y);
898
899 }
900 void OsdOpenVG::executeDrawCommand(SVGCommand & command)
901 {
902
903         VGfloat  save_matrix[9];
904         VGfloat  save_matrix2[9];
905         switch (command.instr) {
906         case DrawPath: {
907         vgSeti(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE);
908         //      VGuint rgba;
909         //      rgba = vgGetColor((VGPaint) command.reference);
910                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Path %d %x %g %g %g %g",command.reference,command.target.path_index,command.x,command.y,command.w,command.h);
911                 //vgSeti(VG_FILL_RULE,);
912
913                 vgGetMatrix(save_matrix);
914                 vgSetPaint((VGPaint) command.reference,VG_FILL_PATH);
915                 vgSetPaint((VGPaint) command.reference,VG_STROKE_PATH);
916                 vgTranslate(command.x,command.y);
917                 vgScale(command.w,command.h);
918                 vgDrawPath(std_paths[command.target.path_index],VG_FILL_PATH);
919                 vgLoadMatrix(save_matrix);
920         } break;
921         case DrawImage: {
922             vgSeti(VG_MATRIX_MODE, VG_MATRIX_IMAGE_USER_TO_SURFACE);
923                 vgGetMatrix(save_matrix);
924                 VGfloat imagewidth=vgGetParameteri((VGImage) command.target.image, VG_IMAGE_WIDTH);
925                 VGfloat imageheight=vgGetParameteri((VGImage) command.target.image, VG_IMAGE_HEIGHT);
926
927
928                 //vgScale(command.w,command.h);
929
930                 if (command.reference) { //special behaviout for bw images they act as a mask on the current paint
931                         vgTranslate(command.x,command.y);
932                         vgSetPaint((VGPaint) command.reference,VG_FILL_PATH);
933                         vgSetPaint((VGPaint) command.reference,VG_STROKE_PATH);
934                         vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_STENCIL);
935                         vgSeti(VG_BLEND_MODE, VG_BLEND_SRC_OVER);
936                         vgScale(aspect_correction,1.f);
937                         vgSeti(VG_MATRIX_MODE, VG_MATRIX_FILL_PAINT_TO_USER);
938                     vgGetMatrix(save_matrix2);
939                     vgScale(imagewidth,imageheight);
940                 } else {
941
942                         //vgScale(720.f/((float)BACKBUFFER_WIDTH), 576.f/((float)BACKBUFFER_HEIGHT));
943                         float scalex=command.w/imagewidth;
944                         float scaley=command.h/imageheight;
945                         float tx=command.x;
946                         float ty=command.y;
947                         if (command.corner == TopLeftLimited) {
948                                 if (scalex !=0.f && scaley !=0.f) {
949                                         float imageaspect=imagewidth/imageheight;
950                                         float boxaspect=command.w/command.h/aspect_correction;
951                                         if (imageaspect > boxaspect) {
952                                                 scaley=0.f;
953                                                 ty+=(command.h-imageheight * scalex/aspect_correction)*0.5f;
954                                         } else {
955                                                 scalex=0.f;
956                                                 tx+=(command.w-imagewidth * scaley*aspect_correction)*0.5f;
957                                         }
958
959                                 }
960
961                         }
962                         if (scalex==0.f && scaley==0.f) {
963                                 scalex=aspect_correction;
964                                 scaley=1.f;
965                         } else if (scalex==0.f) {
966                                 scalex=scaley*aspect_correction;
967                         } else if (scaley==0.f) {
968                                 scaley=scalex/aspect_correction;
969                         }
970
971
972                         if (command.corner ==  BottomRight || command.corner ==  BottomLeft || command.corner == BottomMiddle)
973                         {
974                                 ty-=imageheight * scaley;
975                         }
976
977                         if (command.corner ==  BottomRight || command.corner ==  TopRight)
978                         {
979                                 tx-=imagewidth * scalex;
980                         }
981
982                         if (command.corner ==  BottomMiddle || command.corner ==  TopMiddle)
983                         {
984                                 tx-=imagewidth * scalex *0.5f;
985                         }
986
987                         vgTranslate(tx,ty);
988                         //vgScale(command.w/imagewidth,command.h/imageheight);
989                         vgScale(scalex,scaley);
990                         vgSeti(VG_BLEND_MODE, VG_BLEND_SRC_OVER);
991                         vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_NORMAL);
992                         //Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia Draw Image Scale  %g %g %g %g %g %g",command.w,imagewidth,command.h,imageheight,scalex,scaley);
993                 }
994
995
996                 //vgLoadIdentity();
997                 //vgTranslate(200.f,500.f);
998                 //vgScale(100.f,100.f);
999
1000                 vgDrawImage((VGImage) command.target.image);
1001                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Image %d %x %g %g %g %g %x",command.reference,command.target.image,command.x,command.y,command.w,command.h,
1002                 //              vgGetError());
1003                 if (command.reference) {
1004                         vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_NORMAL);
1005                         vgSeti(VG_MATRIX_MODE, VG_MATRIX_FILL_PAINT_TO_USER);
1006                         vgLoadMatrix(save_matrix2);
1007                 }
1008                 vgSeti(VG_BLEND_MODE, VG_BLEND_SRC);
1009
1010                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_IMAGE_USER_TO_SURFACE);
1011                 vgLoadMatrix(save_matrix);
1012         } break;
1013         case DrawGlyph: {
1014                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_GLYPH_USER_TO_SURFACE);
1015                 vgGetMatrix(save_matrix);
1016                 vgSetPaint((VGPaint) command.reference,VG_FILL_PATH);
1017                 vgSetPaint((VGPaint) command.reference,VG_STROKE_PATH);
1018                 vgTranslate(command.x,command.y);
1019                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_FILL_PAINT_TO_USER);
1020                 vgGetMatrix(save_matrix2);
1021                 unsigned int glyph_index=FT_Get_Char_Index(ft_face,command.target.textchar);
1022             vgScale(font_exp_x[glyph_index],font_height);
1023
1024
1025                 VGfloat gori[]={0.,0.};
1026                 vgSetfv(VG_GLYPH_ORIGIN,2,gori);
1027
1028
1029                 vgDrawGlyph(vgfont,glyph_index,VG_FILL_PATH,VG_FALSE);
1030                 //vgDrawPath(std_paths[Rectangle],VG_FILL_PATH);
1031         /*      Log::getInstance()->log("OSD", Log::DEBUG, "Draw Glyph %d %c %d %g %g %x",command.reference,command.target.textchar,glyph_index,command.x,command.y,
1032                                                 vgGetError());*/
1033                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_GLYPH_USER_TO_SURFACE);
1034                 vgLoadMatrix(save_matrix);
1035                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_FILL_PAINT_TO_USER);
1036                 vgLoadMatrix(save_matrix2);
1037
1038                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE);
1039         } break;
1040         case DrawTTchar:{
1041                 cTeletextChar tchar;
1042                 tchar.setInternal(command.target.ttchar);
1043                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_GLYPH_USER_TO_SURFACE);
1044                 vgGetMatrix(save_matrix);
1045                 enumTeletextColor ttforegcolour=tchar.GetFGColor();
1046                 enumTeletextColor ttbackgcolour=tchar.GetBGColor();
1047             if (tchar.GetBoxedOut()) {
1048                 ttforegcolour=ttcTransparent;
1049                 ttbackgcolour=ttcTransparent;
1050             }
1051             vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_STENCIL);
1052             vgSeti(VG_BLEND_MODE, VG_BLEND_SRC_OVER);
1053
1054
1055                 vgTranslate(command.x+command.w*11.85f*1.4f,command.y+command.h*19.75f);
1056                 VGfloat gori[]={0.,0.};
1057                 vgSetfv(VG_GLYPH_ORIGIN,2,gori);
1058
1059                 vgScale(-1.4f,2.f);
1060                 unsigned int color=Surface::enumTeletextColorToCoulour(ttbackgcolour).rgba();
1061                 color=color<<8 | (color &0xff000000)>>24;
1062                 vgSetColor(vgttpaint,color);
1063                 vgSetPaint((VGPaint) vgttpaint,VG_FILL_PATH);
1064                 vgSetPaint((VGPaint) vgttpaint,VG_STROKE_PATH);
1065                 cTeletextChar filled;
1066                 filled.setInternal(0x187f);
1067                 unsigned int glyph_index=loadTTchar(filled);
1068                 vgDrawGlyph(vgttfont,glyph_index,VG_FILL_PATH,VG_FALSE);
1069
1070                 color=Surface::enumTeletextColorToCoulour(ttforegcolour).rgba();
1071                 color=color<<8 | (color &0xff000000)>>24;
1072                 vgSetColor(vgttpaint,color);
1073                 vgSetPaint((VGPaint) vgttpaint,VG_FILL_PATH);
1074                 vgSetPaint((VGPaint) vgttpaint,VG_STROKE_PATH);
1075                 glyph_index=loadTTchar(tchar);
1076                 vgDrawGlyph(vgttfont,glyph_index,VG_FILL_PATH,VG_FALSE);
1077
1078                 /*      Log::getInstance()->log("OSD", Log::DEBUG, "Draw TTchar %x %x %x %x",glyph_index,ttforegcolour,Surface::enumTeletextColorToCoulour(ttforegcolour).rgba(),
1079                                         vgGetColor(vgttpaint));*/
1080
1081
1082                 vgLoadMatrix(save_matrix);
1083                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE);
1084                 vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_NORMAL);
1085                 vgSeti(VG_BLEND_MODE, VG_BLEND_SRC);
1086
1087         }break;
1088         case DrawClipping: {
1089                 VGint coords[4]={0,0,0,0};
1090                 coords[0]= ((command.x+clip_shift_x)*((float)BACKBUFFER_WIDTH)/720.f);
1091                 coords[1]= ((576.f-command.y-clip_shift_y-command.h)*((float)BACKBUFFER_HEIGHT)/576.f);
1092                 coords[2]= ((command.w-1.f)*((float)BACKBUFFER_WIDTH)/720.f);
1093                 coords[3]= ((command.h-1.f)*((float)BACKBUFFER_HEIGHT)/576.f);
1094                 vgSetiv(VG_SCISSOR_RECTS, 4,coords);
1095                 if (command.w==0.f && command.h==0.f)
1096                         vgSeti(VG_SCISSORING,VG_FALSE);
1097                 else vgSeti(VG_SCISSORING,VG_TRUE);
1098         } break;
1099         }
1100 }
1101 //int imcount=0;// this is debug code and should not go into release
1102 unsigned int OsdOpenVG::handleTask(OpenVGCommand& command)
1103 {
1104         switch (command.task){
1105         case OVGreplacefont: {
1106                  vgDestroyFont(vgfont);
1107                  loadFont(true);
1108                  return 0;
1109         } break;
1110
1111         case OVGdestroyImageRef: {//imcount--;
1112                 //Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia Draw Image Destroy %x %d",command.param1,imcount);
1113                 vgDestroyImage((VGImage)command.param1);
1114                 return 0;
1115         } break;
1116         case OVGdestroyPaint: {
1117                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Paint Destroy %d ",command.param1);
1118                 vgDestroyPaint((VGPaint)command.param1);
1119                 return 0;
1120         } break;
1121         case OVGcreateImagePalette: {//imcount++;
1122                 VGImage input=vgCreateImage(VG_A_8,command.param1, command.param2,
1123                                 VG_IMAGE_QUALITY_NONANTIALIASED|
1124                                 VG_IMAGE_QUALITY_FASTER|VG_IMAGE_QUALITY_BETTER);
1125                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create palette  %d %d %x %d",command.param1,command.param2,vgGetError(),input);
1126                 vgImageSubData(input,command.data,command.param1,
1127                                                         VG_A_8,0,0,command.param1, command.param2); // upload palettized image data
1128                 VGImage handle=vgCreateImage(VG_sRGBA_8888,command.param1, command.param2,
1129                                                 VG_IMAGE_QUALITY_NONANTIALIASED|
1130                                                 VG_IMAGE_QUALITY_FASTER|VG_IMAGE_QUALITY_BETTER);
1131                 VGuint *palette=(VGuint*)malloc(256*sizeof(VGuint));
1132                 VGuint *in_palette=(VGuint*)command.data2;
1133                 for (int i=0;i<256;i++) {
1134                         VGuint color=in_palette[i];
1135                         palette[i]=color<<8 | (color &0xff000000)>>24;
1136                 }
1137
1138                 vgLookupSingle(handle,input,palette,VG_ALPHA,VG_FALSE,VG_FALSE);
1139                 free(palette);
1140                 vgDestroyImage(input);
1141
1142                 return handle;
1143         } break;
1144         case OVGcreateMonoBitmap: {//imcount++;
1145                 VGImage handle=vgCreateImage(VG_A_1,command.param1, command.param2,
1146                                         VG_IMAGE_QUALITY_FASTER);
1147                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create mono  %d %d %x %d",command.param1,command.param2,vgGetError(),handle);
1148                 unsigned int buffer_len=(command.param1*command.param2)>>3;
1149                 unsigned char * buffer=(unsigned char*)malloc(buffer_len);
1150                 unsigned char * r_buffer1=buffer;
1151                 const unsigned char * r_buffer2=(const unsigned char *)command.data;
1152                 unsigned char *buffer_end=buffer+buffer_len;
1153                 while (r_buffer1!=buffer_end) {
1154                         unsigned char byte=*r_buffer2;
1155                         *r_buffer1=((byte * 0x0802LU & 0x22110LU) | (byte * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
1156                         r_buffer1++;r_buffer2++;
1157                 }
1158
1159
1160                 vgImageSubData(handle,buffer,command.param1>>3,
1161                                         VG_A_1,0,0,command.param1, command.param2);
1162                 free(buffer);
1163         //      Log::getInstance()->log("OSD", Log::DEBUG, "Draw create mono2  %d %d %x %d",command.param1,command.param2,vgGetError(),handle);
1164                 return handle;
1165         } break;
1166         /*case OVGcreateImageFile: {
1167                 VGImage handle;
1168                 try{
1169                         Image *imagefile=(Image*)command.data;
1170                         Blob imageblob;
1171                         imagefile->write(&imageblob,"RGBA");
1172
1173
1174                         handle=vgCreateImage(VG_sXBGR_8888,imagefile->columns(),imagefile->rows(),
1175                                         VG_IMAGE_QUALITY_BETTER);
1176                         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create image details  %d %d %x mark1",imagefile->columns(),imagefile->rows(),(unsigned int*)imageblob.data());
1177                         vgImageSubData(handle,imageblob.data(),imagefile->columns()*4,
1178                                         VG_sXBGR_8888,0,0,imagefile->columns(),imagefile->rows());
1179                         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create image details  %d %d %x mark2",imagefile->columns(),imagefile->rows(),(unsigned int*)imageblob.data());
1180                         delete imagefile;
1181                 }catch( Exception &error_ )
1182                 {
1183                         Log::getInstance()->log("OSD", Log::DEBUG, "Libmagick hT: %s",error_.what());
1184
1185                         return 0;
1186                 }
1187
1188                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create file  %d %d %x %d",command.param1,command.param2,vgGetError(),handle);
1189                 return handle;
1190         } break;*/
1191         case OVGcreateImageMemory: {//imcount++;
1192                 PictureInfo *info = (PictureInfo*) command.data;
1193                 VGImage handle;
1194                 //Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia OVGcreateImageMemory %d",imcount);
1195                 handle=vgCreateImage(VG_sABGR_8888,info->width,info->height,VG_IMAGE_QUALITY_BETTER);
1196                 vgImageSubData(handle,info->image,info->width*4,
1197                                                         VG_sABGR_8888,0,0,info->width,info->height);
1198                 info->decoder->freeReference(info->reference);
1199
1200                 bool static_image=true;
1201                 if (info->lindex & 0xffffffff) static_image=false;
1202
1203                 Message* m = new  Message();
1204                 // We have a pictures! send a message to ourself, to switch to gui thread
1205                 m->from=this;
1206                 m->to=Command::getInstance();
1207                 m->parameter.handle = handle;
1208                 if (!static_image) {
1209                         m->message=Message::NEW_PICTURE;
1210                         m->tag = info->lindex;
1211                 } else {
1212                         m->message=Message::NEW_PICTURE_STATIC;
1213                         m->tag = info->lindex>> 32LL;
1214                 }
1215                 Command::getInstance()->postMessageFromOuterSpace(m); // inform command about new picture
1216
1217                 delete info;
1218
1219         } break;
1220         case OVGcreateEGLImage: {//imcount++;
1221                 PictureInfo *info = (PictureInfo*) command.data;
1222                 VGImage handle;
1223
1224                 handle=vgCreateImage(VG_sABGR_8888,info->width,info->height,VG_IMAGE_QUALITY_BETTER);
1225 //              Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia OVGcreateEGLImage %d %d %x %d",info->width,info->height, handle,imcount);
1226
1227                 info->handle = handle;
1228                 info->reference =  eglCreateImageKHR(egl_display, egl_context, EGL_VG_PARENT_IMAGE_KHR, (EGLClientBuffer)handle, NULL);
1229                 if (info->reference) return true;
1230                 else {
1231                         Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia OVGcreateEGLImage %d %d %x Fail!",info->width,info->height, handle);
1232                         if (handle) vgDestroyImage(handle);
1233                         return false;
1234                 }
1235
1236         } break;
1237
1238         case OVGreadyEGLImage: {
1239                 PictureInfo *info = (PictureInfo*) command.data;
1240                 eglDestroyImageKHR(egl_display,info->reference);
1241                 bool static_image=true;
1242                 if (info->lindex & 0xffffffff) static_image=false;
1243                 Message* m = new  Message();
1244                 m->from=this;
1245                 m->to=Command::getInstance();
1246                 m->parameter.handle = info->handle;
1247                 if (!static_image) {
1248                         m->message=Message::NEW_PICTURE;
1249                         m->tag = info->lindex;
1250                 } else {
1251                         m->message=Message::NEW_PICTURE_STATIC;
1252                         m->tag = info->lindex>> 32LL;
1253                 }
1254                 Command::getInstance()->postMessageFromOuterSpace(m); // inform command about new picture
1255
1256                 delete info;
1257         } break;
1258
1259
1260
1261         case OVGcreateColorRef :{
1262                 VGPaint handle;
1263                 handle=vgCreatePaint();
1264                 DrawStyle *style=(DrawStyle*)command.data;
1265                 switch (style->ft) {
1266                 case DrawStyle::Color: {
1267                         vgSetParameteri(handle, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
1268                         vgSetColor(handle,command.param1);
1269                         VGuint rgba;
1270                         rgba = vgGetColor((VGPaint)handle);
1271                         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Paint %d %x %x",handle,command.param1,rgba);
1272                 } break;
1273                 case DrawStyle::GradientLinear: {
1274                         vgSetParameteri(handle, VG_PAINT_TYPE, VG_PAINT_TYPE_LINEAR_GRADIENT);
1275                         VGfloat params[]={style->x1,style->y1,style->x2,style->y2,style->r};
1276                         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Gradient %d %g %g %g %g",handle,params[0],params[1],params[2],params[3]);
1277                         vgSetParameterfv(handle,VG_PAINT_LINEAR_GRADIENT,4,params);
1278
1279
1280
1281                 } break;
1282                 case DrawStyle::GradientRadial: {
1283                         vgSetParameteri(handle, VG_PAINT_TYPE, VG_PAINT_TYPE_RADIAL_GRADIENT);
1284                         VGfloat params[]={style->x1,style->y1,style->x2,style->y2,style->r};
1285                         vgSetParameterfv(handle,VG_PAINT_RADIAL_GRADIENT,5,params);
1286
1287
1288
1289                 } break;
1290                 };
1291                 if (style->ft==DrawStyle::GradientLinear ||style->ft==DrawStyle::GradientRadial) {
1292                         VGfloat colorramp[5*5];
1293                         colorramp[0+0*5]=0.f;
1294                         colorramp[1+0*5]=((float)style->red)/255.f;
1295                         colorramp[2+0*5]=((float)style->green)/255.f;
1296                         colorramp[3+0*5]=((float)style->blue)/255.f;
1297                         colorramp[4+0*5]=((float)style->alpha)/255.f;
1298                         for (int i=0;i<(style->num_colors-1);i++) {
1299                                 colorramp[0+(i+1)*5]=style->grad_pos[i];
1300                                 colorramp[1+(i+1)*5]=((float)style->grad_col[i].red)/255.f;
1301                                 colorramp[2+(i+1)*5]=((float)style->grad_col[i].green)/255.f;
1302                                 colorramp[3+(i+1)*5]=((float)style->grad_col[i].blue)/255.f;
1303                                 colorramp[4+(i+1)*5]=((float)style->grad_col[i].alpha)/255.f;
1304                         }
1305                         colorramp[0+(style->num_colors)*5]=1.f;
1306                         colorramp[1+(style->num_colors)*5]=((float)style->grad_col[style->num_colors-1].red)/255.f;
1307                         colorramp[2+(style->num_colors)*5]=((float)style->grad_col[style->num_colors-1].green)/255.f;
1308                         colorramp[3+(style->num_colors)*5]=((float)style->grad_col[style->num_colors-1].blue)/255.f;
1309                         colorramp[4+(style->num_colors)*5]=((float)style->grad_col[style->num_colors-1].alpha)/255.f;
1310                         vgSetParameteri(handle, VG_PAINT_COLOR_RAMP_SPREAD_MODE,VG_COLOR_RAMP_SPREAD_REFLECT);
1311                         vgSetParameteri(handle, VG_PAINT_COLOR_RAMP_PREMULTIPLIED,VG_FALSE);
1312                         vgSetParameterfv(handle,VG_PAINT_COLOR_RAMP_STOPS,5+(style->num_colors)*5,colorramp);
1313                 }
1314
1315                 return handle;
1316         } break;
1317
1318
1319         }
1320 }
1321
1322 bool OsdOpenVG::processTasks()
1323 {
1324         bool worked=false;
1325         taskmutex.Lock();
1326         vgmutex.Lock();
1327         while (vgcommands.size()>0)
1328         {
1329                 OpenVGCommand comm=vgcommands.front();
1330                 vgcommands.pop_front();
1331                 taskmutex.Unlock();
1332
1333                 OpenVGResponse resp;
1334                 resp.result=handleTask(comm);
1335                 resp.id=comm.id;
1336                 taskmutex.Lock();
1337                 if (comm.id) {
1338                         vgresponses.push_back(resp);
1339                 }
1340                 taskmutex.Unlock();
1341                 vgmutex.Unlock();
1342                 //threadCheckExit();
1343                 vgtaskSignal.signal();
1344                 taskmutex.Lock();
1345                 vgmutex.Lock();
1346                 worked=true;
1347         }
1348         taskmutex.Unlock();
1349         vgmutex.Unlock();
1350
1351         return worked;
1352 }
1353
1354 bool OsdOpenVG::haveOpenVGResponse(unsigned int id,unsigned int * resp)
1355 {
1356         taskmutex.Lock();
1357         if (vgresponses.size()>0)
1358         {
1359                 deque<OpenVGResponse>::iterator itty=vgresponses.begin();
1360                 while (itty!=vgresponses.end())
1361                 {
1362                         if ((*itty).id==id) {
1363                                 *resp=(*itty).result;
1364                                 taskmutex.Unlock();
1365                                 return true;
1366                         }
1367                         itty++;
1368                 }
1369         }
1370         taskmutex.Unlock();
1371         return false;
1372 }
1373
1374
1375 unsigned int  OsdOpenVG::putOpenVGCommand(OpenVGCommand& comm,bool wait)
1376 {
1377         taskmutex.Lock();
1378         if (wait){
1379                 comm.id=wait_id;
1380                 wait_id++;
1381         } else {
1382                 comm.id=0; // we are not waiting
1383         }
1384         vgcommands.push_back(comm);
1385         taskmutex.Unlock();
1386         threadSignal();
1387         while (wait) {
1388                 unsigned int resp;
1389                 if (!haveOpenVGResponse(comm.id,&resp)) {
1390                         struct timespec target_time;
1391                         clock_gettime(CLOCK_REALTIME,&target_time);
1392                         target_time.tv_nsec+=1000000LL*100;
1393                         if (target_time.tv_nsec>999999999) {
1394                                         target_time.tv_nsec-=1000000000L;
1395                                         target_time.tv_sec+=1;
1396                         }
1397                         vgtaskSignal.waitForSignalTimed(&target_time);
1398                 } else {
1399                         return resp;
1400                 }
1401         }
1402         return 0;
1403 }
1404
1405
1406
1407 void OsdOpenVG::destroyImageRef(ImageIndex index)
1408 {
1409         struct OpenVGCommand comm;
1410         comm.task=OVGdestroyImageRef;
1411         comm.param1=index;
1412         putOpenVGCommand(comm,false);
1413 }
1414
1415
1416 bool OsdOpenVG::getStaticImageData(unsigned int static_id, UCHAR **userdata, ULONG *length)
1417 {
1418         if (sa_MAX>static_id) {
1419                 *userdata = static_artwork_begin[static_id];
1420                 *length = static_artwork_end[static_id] - static_artwork_begin[static_id];
1421                 return true;
1422         }
1423
1424         *userdata = NULL;
1425         *length = 0;
1426         return false;
1427
1428 }
1429
1430 void  OsdOpenVG::createPicture(struct PictureInfo& pict_inf)
1431 {
1432         struct OpenVGCommand comm;
1433         Log::getInstance()->log("OsdOpenVG", Log::DEBUG, "TVMedia Create Picture %d",pict_inf.type);
1434         if (pict_inf.type == PictureInfo::RGBAMemBlock) {
1435                 comm.task = OVGcreateImageMemory;
1436                 comm.data =  new PictureInfo(pict_inf);
1437                 putOpenVGCommand(comm,false);
1438         } else if (pict_inf.type == PictureInfo::EGLImage) {
1439                 comm.task = OVGreadyEGLImage;
1440                 comm.data =  new PictureInfo(pict_inf);
1441                 putOpenVGCommand(comm,false);
1442         } else {
1443                 // unsupported
1444                 pict_inf.decoder->freeReference(pict_inf.reference);
1445
1446
1447         }
1448 }
1449
1450 bool OsdOpenVG::getEGLPicture(struct OsdVector::PictureInfo & info , EGLDisplay * display)
1451 {
1452         struct OpenVGCommand comm;
1453         info.type = PictureInfo::EGLImage;
1454         comm.task = OVGcreateEGLImage;
1455         comm.data = &info;
1456         *display = egl_display;
1457         return  putOpenVGCommand(comm,true);
1458 }
1459
1460
1461
1462 ImageIndex OsdOpenVG::createMonoBitmap(void *base,int width,int height)
1463 {
1464         struct OpenVGCommand comm;
1465         comm.task=OVGcreateMonoBitmap;
1466         comm.param1=width;
1467         comm.param2=height;
1468         comm.data=base;
1469         return putOpenVGCommand(comm,true);
1470 }
1471
1472 ImageIndex OsdOpenVG::createImagePalette(int width,int height,const unsigned char *image_data,const unsigned int*palette_data)
1473 {
1474     struct OpenVGCommand comm;
1475     comm.task=OVGcreateImagePalette;
1476     comm.param1=width;
1477     comm.param2=height;
1478     comm.data=image_data;
1479     comm.data2=palette_data;
1480     return putOpenVGCommand(comm,true);
1481 }
1482
1483 void OsdOpenVG::destroyStyleRef(VectorHandle index)
1484 {
1485         struct OpenVGCommand comm;
1486         comm.task=OVGdestroyPaint;
1487         comm.param1=index;
1488         putOpenVGCommand(comm,false);
1489 }
1490
1491 VectorHandle OsdOpenVG::createStyleRef(const DrawStyle &c)
1492 {
1493         unsigned int col=c.rgba();
1494         struct OpenVGCommand comm;
1495         comm.task=OVGcreateColorRef;
1496         comm.param1=col<<8 | (col &0xff000000)>>24;
1497         comm.data=&c;
1498         return putOpenVGCommand(comm,true);
1499 }
1500
1501
1502
1503