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