]> git.vomp.tv Git - vompclient.git/blob - osdopenvg.cc
Rework master loop
[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
610 void OsdOpenVG::threadPostStopCleanup()
611 {
612         //Doing nothing
613         //goo;
614         Log::getInstance()->log("OSD", Log::NOTICE, "Exiting drawing thread");
615 }
616
617 void OsdOpenVG::InternalRendering(){
618         vgmutex.Lock();
619         Colour bg=DrawStyle::WALLPAPER;
620     float colclear[]={1.f,1.0f,1.f,1.f};
621     if (bg.alpha==0) colclear[3]=0.f;
622     vgSetfv(VG_CLEAR_COLOR,4,colclear);
623         vgClear(0,0,BACKBUFFER_WIDTH,BACKBUFFER_HEIGHT);
624         vgSeti(VG_BLEND_MODE, VG_BLEND_SRC);
625
626
627         drawSurfaces(); //iterate through and draws all commands
628
629         //Show it to the user!
630         eglSwapBuffers(egl_display, egl_surface);
631         vgmutex.Unlock();
632
633 }
634
635 /*font stuff*/
636
637 float OsdOpenVG::getFontHeight()
638 {
639         return font_height; //dummy
640 }
641 float OsdOpenVG::getCharWidth(wchar_t c)
642 {
643         if (c<256) return byte_char_width[c];
644         unsigned int glyph_index=FT_Get_Char_Index(ft_face,c);
645         return font_exp_x[glyph_index];
646 }
647
648 unsigned int OsdOpenVG::loadTTchar(cTeletextChar c)
649 {
650         unsigned int glyph_index=c.getGlyphIndex();
651         if (tt_font_chars.find(glyph_index)!=tt_font_chars.end())
652         {
653                 return glyph_index;
654         }
655
656         unsigned int buffer[10];
657         const VGfloat glyphOrigin[] = { 0.f, 0.f };
658         const VGfloat escapement[] = { 12.f, 0.f };
659         unsigned int * charmap = GetFontChar(c, buffer);
660         if (!charmap) { //invalid char
661                 return 0;
662         }
663         for (int i=0;i<10;i++) {
664                 buffer[i]=charmap[i]>>4;
665         }
666
667         VGImage handle = vgCreateImage(
668                         VG_A_8,
669                         12,
670                         10,
671                         VG_IMAGE_QUALITY_NONANTIALIASED | VG_IMAGE_QUALITY_FASTER
672                                         | VG_IMAGE_QUALITY_BETTER);
673         vgImageSubData(handle, buffer, 4, VG_A_1, 0, 0, 12, 10);
674         vgSetGlyphToImage(
675                         vgttfont,
676                         glyph_index,
677                         handle, (VGfloat*)glyphOrigin, (VGfloat*)escapement);
678         vgDestroyImage(handle);
679         tt_font_chars[glyph_index]=1;
680
681         return glyph_index;
682 }
683
684 int OsdOpenVG::getFontNames(const char *** names,const char *** names_keys)
685 {
686         *names=(const char**)&(fontnames[0]);
687         *names_keys=(const char**)&(fontnames_keys[0]);
688         return fontnames.size();
689 }
690
691 void OsdOpenVG::setFont(const char * fontname) {
692
693         if (strcmp(fontname,cur_fontname)) {
694                 // new font!
695                 if (cur_fontname) free(cur_fontname);
696                 cur_fontname=(char*)malloc(strlen(fontname)+1);
697                 strcpy(cur_fontname,fontname);
698
699                 struct OpenVGCommand comm;
700                 comm.task=OVGreplacefont;
701                 putOpenVGCommand(comm,false);
702
703
704         }
705 }
706
707
708 int  OsdOpenVG::loadFont(bool newfont)
709 {
710         int error;
711         float font_size=16.f;
712         if (!freetype_inited) {
713                 error=FT_Init_FreeType(&ft_library);
714                 if (error)
715                 {
716                         Log::getInstance()->log("OSD", Log::WARN, "Could not load freetype %x",error);
717                         return 0;
718                 }
719         }
720
721         if (!freetype_inited || newfont) {
722                 //first get the filename algorith extracted from vdr by Klaus Schmidinger
723                 FcInit();
724                 FcPattern *pattern=FcNameParse((FcChar8*)cur_fontname);
725                 FcPatternAddBool(pattern,FC_SCALABLE,FcTrue);
726                 FcConfigSubstitute(NULL,pattern,FcMatchPattern);
727                 FcDefaultSubstitute(pattern);
728                 FcResult fres;
729                 FcFontSet *fonts=FcFontSort(NULL,pattern,FcFalse,NULL,&fres);
730                 FcChar8 *filename=NULL;
731                 if (fonts) {
732                         for (int i=0;i<fonts->nfont;i++) {
733                                 FcBool canscale;
734                                 FcPatternGetBool(fonts->fonts[i],FC_SCALABLE,0,&canscale);
735                                 if (canscale){
736                                         FcPatternGetString(fonts->fonts[i],FC_FILE,0,&filename);
737                                         break;
738                                 }
739                         }
740                         FcFontSetDestroy(fonts);
741                 } else {
742                         Log::getInstance()->log("OSD", Log::CRIT, "Could not locate a font! Abort!");
743                         return 0;
744                 }
745                 FcPatternDestroy(pattern);
746
747                 Log::getInstance()->log("OSD", Log::NOTICE, "Load Font %s: %s", cur_fontname,filename);
748                 // second load the font
749                 FT_Face     new_ft_face;
750                 error=FT_New_Face(ft_library,(const char*)filename,0,&new_ft_face );
751                 if (error) {
752                         Log::getInstance()->log("OSD", Log::WARN, "Could not load font face %x %s",error,filename);
753                         return 0;
754                 }
755                 error=FT_Set_Char_Size(new_ft_face,0,font_size*256,0,0 /*dpi*/);
756                 if (error) {
757                         FT_Done_Face(new_ft_face);
758                         Log::getInstance()->log("OSD", Log::WARN, "Could not set  face size %x",error);
759                         return 0;
760                 }
761                 FT_Face old_ft_face=ft_face; // do it thread safe
762                 ft_face=new_ft_face;
763                 if (freetype_inited) FT_Done_Face(old_ft_face);//
764                 freetype_inited=true;
765         }
766         vgfont=vgCreateFont(0);
767         FT_ULong cur_char;
768         FT_UInt glyph;
769         font_height=ft_face->size->metrics.height/256.f;
770         cur_char = FT_Get_First_Char(ft_face,&glyph);
771         std::vector<VGubyte> segments;
772         std::vector<VGfloat> coord;
773         segments.reserve(256);
774         coord.reserve(1024);
775         //Log::getInstance()->log("OSD", Log::DEBUG, "Create Glyph test %d %x %x %d",cur_char,font_data_end,font_data,glyph);
776         while (glyph !=0)
777         {
778                 error=FT_Load_Glyph(ft_face,glyph,FT_LOAD_DEFAULT);
779                 if (error){
780                         cur_char = FT_Get_Next_Char(ft_face,cur_char,&glyph);
781                         Log::getInstance()->log("OSD", Log::WARN, "Could not load glyph %x %c",error);
782                         continue;
783                 }
784                 VGPath path;
785                 FT_Outline ot=ft_face->glyph->outline;
786                 segments.clear();
787                 coord.clear();
788
789                 if (ot.n_contours ==0) {
790                         path=VG_INVALID_HANDLE;
791                 } else {
792                         path=vgCreatePath(VG_PATH_FORMAT_STANDARD, VG_PATH_DATATYPE_F,
793                                         1.0f,0.f,0,0,VG_PATH_CAPABILITY_ALL);
794
795                         /* convert glyph */
796                         FT_Vector *pt=ot.points;
797                         const char *tags=ot.tags;
798                         const short* cont=ot.contours;
799                         short n_cont=ot.n_contours;
800                         //short n_point=ot.n_points;
801                         //short last_cont=0;
802                         for (short point=0;n_cont!=0;cont++,n_cont--) {
803                                 short next_cont=*cont+1;
804                                 bool first=true;
805                                 char last_tag=0;
806                                 short first_point=point;
807                                 //Log::getInstance()->log("OSD", Log::DEBUG, "runs %d",*cont);
808                                 for (;point<next_cont;point++) {
809                                         char tag=tags[point];
810                                         FT_Vector fpoint=pt[point];
811                                 //      Log::getInstance()->log("OSD", Log::DEBUG, "tag %d point %d %d: %d %d",tag,fpoint.x,fpoint.y,point,n_point);
812                                         if (first) {
813                                                 segments.push_back(VG_MOVE_TO);
814                                                 first=false;
815                                         } else if (tag &0x1) { //on curve
816                                                 if (last_tag &0x1) {
817                                                         segments.push_back(VG_LINE_TO);
818                                                 } else if (last_tag &0x2){
819                                                         segments.push_back(VG_CUBIC_TO);
820                                                 } else {
821                                                         segments.push_back(VG_QUAD_TO);
822                                                 }
823
824                                         } else {
825                                                 if (!(tag &0x2)){
826                                                         if (!(last_tag &0x1)) {
827                                                                 segments.push_back(VG_QUAD_TO);
828                                                                 int coord_size=coord.size();
829                                                                 VGfloat x=(coord[coord_size-2]+ ((float)fpoint.x)/256.f)*0.5f*aspect_correction;
830                                                                 VGfloat y=(coord[coord_size-1]+(font_size- ((float)fpoint.y)/256.f))*0.5f;
831                                                                 coord.push_back(x);
832                                                                 coord.push_back(y);
833                                                         }
834                                                 }
835
836
837                                         }
838                                         last_tag=tag;
839                                         coord.push_back(((float)fpoint.x)*aspect_correction/256.);
840                                         coord.push_back(font_size-((float)fpoint.y)/256.);
841                                         //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]);
842                                 }
843                                 if (!(last_tag &0x1)) {
844                                         if (last_tag &0x2) {
845                                                 segments.push_back(VG_CUBIC_TO);
846                                         } else {
847                                                 segments.push_back(VG_QUAD_TO);
848                                         }
849                                         coord.push_back(((float)pt[first_point].x)*aspect_correction/256.);
850                                         coord.push_back(font_size-((float)pt[first_point].y)/256.);
851                                 }
852                                 //segments.push_back(VG_CLOSE_PATH);
853
854
855                         }
856                         vgAppendPathData(path,segments.size(),&segments[0],&coord[0]);
857                 /*      for (int m=0;m<segments.size();m++) {
858                                 int n=0;
859                                 switch (segments[m])
860                                 {
861                                 case VG_MOVE_TO:
862                                         Log::getInstance()->log("OSD", Log::DEBUG, "Move To %g %g",coord[n],coord[n+1]);n+=2; break;
863                                 case VG_LINE_TO:
864                                         Log::getInstance()->log("OSD", Log::DEBUG, "Line To %g %g",coord[n],coord[n+1]);n+=2; break;
865                                 case VG_CUBIC_TO:
866                                         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;
867                                 case VG_QUAD_TO:
868                                         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;
869                                 case VG_CLOSE_PATH:
870                                         Log::getInstance()->log("OSD", Log::DEBUG, "Close Path"); break;
871                                 }
872
873                         }*/
874                         //vguRect(path,0.f,0.f,1.f,1.f);
875                         //Log::getInstance()->log("OSD", Log::DEBUG, "Create APD Glyph %d %x",segments.size(),vgGetError());
876                 }
877                 VGfloat ori[]={0.f,0.f};
878                 VGfloat esp[]={ft_face->glyph->advance.x/256.f*aspect_correction,ft_face->glyph->advance.y/256.f};
879                 font_exp_x[glyph]=ft_face->glyph->advance.x/256.f*aspect_correction; //recalculate
880
881                 vgSetGlyphToPath(vgfont,glyph,path,VG_FALSE,ori,esp);
882                 //Log::getInstance()->log("OSD", Log::DEBUG, "Create Glyph %d %d %x",path,glyph,vgGetError());
883                 if (path!=VG_INVALID_HANDLE) {
884                         vgDestroyPath(path);
885                 }
886                 cur_char = FT_Get_Next_Char(ft_face,cur_char,&glyph);
887         }
888         for (int i=0;i<256;i++) {
889                 unsigned int glyph_index=FT_Get_Char_Index(ft_face,i);
890                 byte_char_width[i]=font_exp_x[glyph_index];
891         }
892         return 1;
893 }
894
895
896 void OsdOpenVG::drawSetTrans(SurfaceCommands & sc)
897 {
898         vgSeti(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE);
899         vgLoadIdentity();
900         vgScale(((float)BACKBUFFER_WIDTH)/720.f, -((float)BACKBUFFER_HEIGHT)/576.f);
901         vgTranslate(0.f+sc.x,-576.f+sc.y);
902
903         vgSeti(VG_MATRIX_MODE, VG_MATRIX_GLYPH_USER_TO_SURFACE);
904         vgLoadIdentity();
905     vgScale(((float)BACKBUFFER_WIDTH)/720.f, -((float)BACKBUFFER_HEIGHT)/576.f);
906         vgTranslate(0.f+sc.x,-576.f+sc.y);
907
908         vgSeti(VG_MATRIX_MODE, VG_MATRIX_IMAGE_USER_TO_SURFACE);
909         vgLoadIdentity();
910         vgScale(((float)BACKBUFFER_WIDTH)/720.f, -((float)BACKBUFFER_HEIGHT)/576.f);
911         vgTranslate(0.f+sc.x,-576.f+sc.y);
912     clip_shift_x=sc.x;
913     clip_shift_y=sc.y;
914
915
916
917         //vgTranslate(0.f+sc.x,576.f-sc.y);
918         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Translate %g %g",sc.x,sc.y);
919
920 }
921 void OsdOpenVG::executeDrawCommand(SVGCommand & command)
922 {
923
924         VGfloat  save_matrix[9];
925         VGfloat  save_matrix2[9];
926         switch (command.instr) {
927         case DrawPath: {
928         vgSeti(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE);
929         //      VGuint rgba;
930         //      rgba = vgGetColor((VGPaint) command.reference);
931                 //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);
932                 //vgSeti(VG_FILL_RULE,);
933
934                 vgGetMatrix(save_matrix);
935                 vgSetPaint((VGPaint) command.reference,VG_FILL_PATH);
936                 vgSetPaint((VGPaint) command.reference,VG_STROKE_PATH);
937                 vgTranslate(command.x,command.y);
938                 vgScale(command.w,command.h);
939                 vgDrawPath(std_paths[command.target.path_index],VG_FILL_PATH);
940                 vgLoadMatrix(save_matrix);
941         } break;
942         case DrawImage: {
943             vgSeti(VG_MATRIX_MODE, VG_MATRIX_IMAGE_USER_TO_SURFACE);
944                 vgGetMatrix(save_matrix);
945                 VGfloat imagewidth=vgGetParameteri((VGImage) command.target.image, VG_IMAGE_WIDTH);
946                 VGfloat imageheight=vgGetParameteri((VGImage) command.target.image, VG_IMAGE_HEIGHT);
947
948
949                 //vgScale(command.w,command.h);
950
951                 if (command.reference) { //special behaviout for bw images they act as a mask on the current paint
952                         vgTranslate(command.x,command.y);
953                         vgSetPaint((VGPaint) command.reference,VG_FILL_PATH);
954                         vgSetPaint((VGPaint) command.reference,VG_STROKE_PATH);
955                         vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_STENCIL);
956                         vgSeti(VG_BLEND_MODE, VG_BLEND_SRC_OVER);
957                         vgScale(aspect_correction,1.f);
958                         vgSeti(VG_MATRIX_MODE, VG_MATRIX_FILL_PAINT_TO_USER);
959                     vgGetMatrix(save_matrix2);
960                     vgScale(imagewidth,imageheight);
961                 } else {
962
963                         //vgScale(720.f/((float)BACKBUFFER_WIDTH), 576.f/((float)BACKBUFFER_HEIGHT));
964                         float scalex=command.w/imagewidth;
965                         float scaley=command.h/imageheight;
966                         float tx=command.x;
967                         float ty=command.y;
968                         if (command.corner == TopLeftLimited) {
969                                 if (scalex !=0.f && scaley !=0.f) {
970                                         float imageaspect=imagewidth/imageheight;
971                                         float boxaspect=command.w/command.h/aspect_correction;
972                                         if (imageaspect > boxaspect) {
973                                                 scaley=0.f;
974                                                 ty+=(command.h-imageheight * scalex/aspect_correction)*0.5f;
975                                         } else {
976                                                 scalex=0.f;
977                                                 tx+=(command.w-imagewidth * scaley*aspect_correction)*0.5f;
978                                         }
979
980                                 }
981
982                         }
983                         if (scalex==0.f && scaley==0.f) {
984                                 scalex=aspect_correction;
985                                 scaley=1.f;
986                         } else if (scalex==0.f) {
987                                 scalex=scaley*aspect_correction;
988                         } else if (scaley==0.f) {
989                                 scaley=scalex/aspect_correction;
990                         }
991
992
993                         if (command.corner ==  BottomRight || command.corner ==  BottomLeft || command.corner == BottomMiddle)
994                         {
995                                 ty-=imageheight * scaley;
996                         }
997
998                         if (command.corner ==  BottomRight || command.corner ==  TopRight)
999                         {
1000                                 tx-=imagewidth * scalex;
1001                         }
1002
1003                         if (command.corner ==  BottomMiddle || command.corner ==  TopMiddle)
1004                         {
1005                                 tx-=imagewidth * scalex *0.5f;
1006                         }
1007
1008                         vgTranslate(tx,ty);
1009                         //vgScale(command.w/imagewidth,command.h/imageheight);
1010                         vgScale(scalex,scaley);
1011                         vgSeti(VG_BLEND_MODE, VG_BLEND_SRC_OVER);
1012                         vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_NORMAL);
1013                         //Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia Draw Image Scale  %g %g %g %g %g %g",command.w,imagewidth,command.h,imageheight,scalex,scaley);
1014                 }
1015
1016
1017                 //vgLoadIdentity();
1018                 //vgTranslate(200.f,500.f);
1019                 //vgScale(100.f,100.f);
1020
1021                 vgDrawImage((VGImage) command.target.image);
1022                 //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,
1023                 //              vgGetError());
1024                 if (command.reference) {
1025                         vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_NORMAL);
1026                         vgSeti(VG_MATRIX_MODE, VG_MATRIX_FILL_PAINT_TO_USER);
1027                         vgLoadMatrix(save_matrix2);
1028                 }
1029                 vgSeti(VG_BLEND_MODE, VG_BLEND_SRC);
1030
1031                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_IMAGE_USER_TO_SURFACE);
1032                 vgLoadMatrix(save_matrix);
1033         } break;
1034         case DrawGlyph: {
1035                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_GLYPH_USER_TO_SURFACE);
1036                 vgGetMatrix(save_matrix);
1037                 vgSetPaint((VGPaint) command.reference,VG_FILL_PATH);
1038                 vgSetPaint((VGPaint) command.reference,VG_STROKE_PATH);
1039                 vgTranslate(command.x,command.y);
1040                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_FILL_PAINT_TO_USER);
1041                 vgGetMatrix(save_matrix2);
1042                 unsigned int glyph_index=FT_Get_Char_Index(ft_face,command.target.textchar);
1043             vgScale(font_exp_x[glyph_index],font_height);
1044
1045
1046                 VGfloat gori[]={0.,0.};
1047                 vgSetfv(VG_GLYPH_ORIGIN,2,gori);
1048
1049
1050                 vgDrawGlyph(vgfont,glyph_index,VG_FILL_PATH,VG_FALSE);
1051                 //vgDrawPath(std_paths[Rectangle],VG_FILL_PATH);
1052         /*      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,
1053                                                 vgGetError());*/
1054                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_GLYPH_USER_TO_SURFACE);
1055                 vgLoadMatrix(save_matrix);
1056                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_FILL_PAINT_TO_USER);
1057                 vgLoadMatrix(save_matrix2);
1058
1059                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE);
1060         } break;
1061         case DrawTTchar:{
1062                 cTeletextChar tchar;
1063                 tchar.setInternal(command.target.ttchar);
1064                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_GLYPH_USER_TO_SURFACE);
1065                 vgGetMatrix(save_matrix);
1066                 enumTeletextColor ttforegcolour=tchar.GetFGColor();
1067                 enumTeletextColor ttbackgcolour=tchar.GetBGColor();
1068             if (tchar.GetBoxedOut()) {
1069                 ttforegcolour=ttcTransparent;
1070                 ttbackgcolour=ttcTransparent;
1071             }
1072             vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_STENCIL);
1073             vgSeti(VG_BLEND_MODE, VG_BLEND_SRC_OVER);
1074
1075
1076                 vgTranslate(command.x+command.w*11.85f*1.4f,command.y+command.h*19.75f);
1077                 VGfloat gori[]={0.,0.};
1078                 vgSetfv(VG_GLYPH_ORIGIN,2,gori);
1079
1080                 vgScale(-1.4f,2.f);
1081                 unsigned int color=Surface::enumTeletextColorToCoulour(ttbackgcolour).rgba();
1082                 color=color<<8 | (color &0xff000000)>>24;
1083                 vgSetColor(vgttpaint,color);
1084                 vgSetPaint((VGPaint) vgttpaint,VG_FILL_PATH);
1085                 vgSetPaint((VGPaint) vgttpaint,VG_STROKE_PATH);
1086                 cTeletextChar filled;
1087                 filled.setInternal(0x187f);
1088                 unsigned int glyph_index=loadTTchar(filled);
1089                 vgDrawGlyph(vgttfont,glyph_index,VG_FILL_PATH,VG_FALSE);
1090
1091                 color=Surface::enumTeletextColorToCoulour(ttforegcolour).rgba();
1092                 color=color<<8 | (color &0xff000000)>>24;
1093                 vgSetColor(vgttpaint,color);
1094                 vgSetPaint((VGPaint) vgttpaint,VG_FILL_PATH);
1095                 vgSetPaint((VGPaint) vgttpaint,VG_STROKE_PATH);
1096                 glyph_index=loadTTchar(tchar);
1097                 vgDrawGlyph(vgttfont,glyph_index,VG_FILL_PATH,VG_FALSE);
1098
1099                 /*      Log::getInstance()->log("OSD", Log::DEBUG, "Draw TTchar %x %x %x %x",glyph_index,ttforegcolour,Surface::enumTeletextColorToCoulour(ttforegcolour).rgba(),
1100                                         vgGetColor(vgttpaint));*/
1101
1102
1103                 vgLoadMatrix(save_matrix);
1104                 vgSeti(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE);
1105                 vgSeti(VG_IMAGE_MODE,VG_DRAW_IMAGE_NORMAL);
1106                 vgSeti(VG_BLEND_MODE, VG_BLEND_SRC);
1107
1108         }break;
1109         case DrawClipping: {
1110                 VGint coords[4]={0,0,0,0};
1111                 coords[0]= ((command.x+clip_shift_x)*((float)BACKBUFFER_WIDTH)/720.f);
1112                 coords[1]= ((576.f-command.y-clip_shift_y-command.h)*((float)BACKBUFFER_HEIGHT)/576.f);
1113                 coords[2]= ((command.w-1.f)*((float)BACKBUFFER_WIDTH)/720.f);
1114                 coords[3]= ((command.h-1.f)*((float)BACKBUFFER_HEIGHT)/576.f);
1115                 vgSetiv(VG_SCISSOR_RECTS, 4,coords);
1116                 if (command.w==0.f && command.h==0.f)
1117                         vgSeti(VG_SCISSORING,VG_FALSE);
1118                 else vgSeti(VG_SCISSORING,VG_TRUE);
1119         } break;
1120
1121         case DrawImageLoading:
1122         case DrawNoop:
1123                 {}
1124         }
1125 }
1126 //int imcount=0;// this is debug code and should not go into release
1127 unsigned int OsdOpenVG::handleTask(OpenVGCommand& command)
1128 {
1129         switch (command.task){
1130         case OVGreplacefont: {
1131                  vgDestroyFont(vgfont);
1132                  loadFont(true);
1133                  return 0;
1134         } break;
1135
1136         case OVGdestroyImageRef: {//imcount--;
1137                 //Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia Draw Image Destroy %x %d",command.param1,imcount);
1138                 vgDestroyImage((VGImage)command.param1);
1139                 return 0;
1140         } break;
1141         case OVGdestroyPaint: {
1142                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Paint Destroy %d ",command.param1);
1143                 vgDestroyPaint((VGPaint)command.param1);
1144                 return 0;
1145         } break;
1146         case OVGcreateImagePalette: {//imcount++;
1147                 VGImage input=vgCreateImage(VG_A_8,command.param1, command.param2,
1148                                 VG_IMAGE_QUALITY_NONANTIALIASED|
1149                                 VG_IMAGE_QUALITY_FASTER|VG_IMAGE_QUALITY_BETTER);
1150                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create palette  %d %d %x %d",command.param1,command.param2,vgGetError(),input);
1151                 vgImageSubData(input,command.data,command.param1,
1152                                                         VG_A_8,0,0,command.param1, command.param2); // upload palettized image data
1153                 VGImage handle=vgCreateImage(VG_sRGBA_8888,command.param1, command.param2,
1154                                                 VG_IMAGE_QUALITY_NONANTIALIASED|
1155                                                 VG_IMAGE_QUALITY_FASTER|VG_IMAGE_QUALITY_BETTER);
1156                 VGuint *palette=(VGuint*)malloc(256*sizeof(VGuint));
1157                 VGuint *in_palette=(VGuint*)command.data2;
1158                 for (int i=0;i<256;i++) {
1159                         VGuint color=in_palette[i];
1160                         palette[i]=color<<8 | (color &0xff000000)>>24;
1161                 }
1162
1163                 vgLookupSingle(handle,input,palette,VG_ALPHA,VG_FALSE,VG_FALSE);
1164                 free(palette);
1165                 vgDestroyImage(input);
1166
1167                 return handle;
1168         } break;
1169         case OVGcreateMonoBitmap: {//imcount++;
1170                 VGImage handle=vgCreateImage(VG_A_1,command.param1, command.param2,
1171                                         VG_IMAGE_QUALITY_FASTER);
1172                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create mono  %d %d %x %d",command.param1,command.param2,vgGetError(),handle);
1173                 unsigned int buffer_len=(command.param1*command.param2)>>3;
1174                 unsigned char * buffer=(unsigned char*)malloc(buffer_len);
1175                 unsigned char * r_buffer1=buffer;
1176                 const unsigned char * r_buffer2=(const unsigned char *)command.data;
1177                 unsigned char *buffer_end=buffer+buffer_len;
1178                 while (r_buffer1!=buffer_end) {
1179                         unsigned char byte=*r_buffer2;
1180                         *r_buffer1=((byte * 0x0802LU & 0x22110LU) | (byte * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
1181                         r_buffer1++;r_buffer2++;
1182                 }
1183
1184
1185                 vgImageSubData(handle,buffer,command.param1>>3,
1186                                         VG_A_1,0,0,command.param1, command.param2);
1187                 free(buffer);
1188         //      Log::getInstance()->log("OSD", Log::DEBUG, "Draw create mono2  %d %d %x %d",command.param1,command.param2,vgGetError(),handle);
1189                 return handle;
1190         } break;
1191         /*case OVGcreateImageFile: {
1192                 VGImage handle;
1193                 try{
1194                         Image *imagefile=(Image*)command.data;
1195                         Blob imageblob;
1196                         imagefile->write(&imageblob,"RGBA");
1197
1198
1199                         handle=vgCreateImage(VG_sXBGR_8888,imagefile->columns(),imagefile->rows(),
1200                                         VG_IMAGE_QUALITY_BETTER);
1201                         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create image details  %d %d %x mark1",imagefile->columns(),imagefile->rows(),(unsigned int*)imageblob.data());
1202                         vgImageSubData(handle,imageblob.data(),imagefile->columns()*4,
1203                                         VG_sXBGR_8888,0,0,imagefile->columns(),imagefile->rows());
1204                         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create image details  %d %d %x mark2",imagefile->columns(),imagefile->rows(),(unsigned int*)imageblob.data());
1205                         delete imagefile;
1206                 }catch( Exception &error_ )
1207                 {
1208                         Log::getInstance()->log("OSD", Log::DEBUG, "Libmagick hT: %s",error_.what());
1209
1210                         return 0;
1211                 }
1212
1213                 //Log::getInstance()->log("OSD", Log::DEBUG, "Draw create file  %d %d %x %d",command.param1,command.param2,vgGetError(),handle);
1214                 return handle;
1215         } break;*/
1216         case OVGcreateImageMemory: {//imcount++;
1217                 PictureInfo *info = (PictureInfo*) command.data;
1218                 VGImage handle;
1219                 //Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia OVGcreateImageMemory %d",imcount);
1220                 handle=vgCreateImage(VG_sABGR_8888,info->width,info->height,VG_IMAGE_QUALITY_BETTER);
1221                 vgImageSubData(handle,info->image,info->width*4,
1222                                                         VG_sABGR_8888,0,0,info->width,info->height);
1223                 info->decoder->freeReference(info->reference);
1224
1225                 bool static_image=true;
1226                 if (info->lindex & 0xffffffff) static_image=false;
1227
1228                 Message* m = new  Message();
1229                 // We have a pictures! send a message to ourself, to switch to gui thread
1230                 m->from=this;
1231                 m->to=Command::getInstance();
1232                 m->data = reinterpret_cast<void*>(handle);
1233                 if (!static_image) {
1234                         m->message=Message::NEW_PICTURE;
1235                         m->tag = info->lindex;
1236                 } else {
1237                         m->message=Message::NEW_PICTURE_STATIC;
1238                         m->tag = info->lindex>> 32LL;
1239                 }
1240                 MessageQueue::getInstance()->postMessage(m); // inform command about new picture
1241
1242                 delete info;
1243
1244         } break;
1245         case OVGcreateEGLImage: {//imcount++;
1246                 PictureInfo *info = (PictureInfo*) command.data;
1247                 VGImage handle;
1248
1249                 handle=vgCreateImage(VG_sABGR_8888,info->width,info->height,VG_IMAGE_QUALITY_BETTER);
1250 //              Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia OVGcreateEGLImage %d %d %x %d",info->width,info->height, handle,imcount);
1251
1252                 info->handle = handle;
1253                 info->reference =  eglCreateImageKHR(egl_display, egl_context, EGL_VG_PARENT_IMAGE_KHR, (EGLClientBuffer)handle, NULL);
1254                 if (info->reference) return true;
1255                 else {
1256                         Log::getInstance()->log("OSD", Log::DEBUG, "TVMedia OVGcreateEGLImage %d %d %x Fail!",info->width,info->height, handle);
1257                         if (handle) vgDestroyImage(handle);
1258                         return false;
1259                 }
1260
1261         } break;
1262
1263         case OVGreadyEGLImage: {
1264                 PictureInfo *info = (PictureInfo*) command.data;
1265                 eglDestroyImageKHR(egl_display,info->reference);
1266                 bool static_image=true;
1267                 if (info->lindex & 0xffffffff) static_image=false;
1268                 Message* m = new  Message();
1269                 m->from=this;
1270                 m->to=Command::getInstance();
1271                 m->data = reinterpret_cast<void*>(info->handle);
1272                 if (!static_image) {
1273                         m->message=Message::NEW_PICTURE;
1274                         m->tag = info->lindex;
1275                 } else {
1276                         m->message=Message::NEW_PICTURE_STATIC;
1277                         m->tag = info->lindex>> 32LL;
1278                 }
1279                 MessageQueue::getInstance()->postMessage(m); // inform command about new picture
1280
1281                 delete info;
1282         } break;
1283
1284
1285
1286         case OVGcreateColorRef :{
1287                 VGPaint handle;
1288                 handle=vgCreatePaint();
1289                 DrawStyle *style=(DrawStyle*)command.data;
1290                 switch (style->ft) {
1291                 case DrawStyle::Color: {
1292                         vgSetParameteri(handle, VG_PAINT_TYPE, VG_PAINT_TYPE_COLOR);
1293                         vgSetColor(handle,command.param1);
1294                         //VGuint rgba;
1295                         //rgba = vgGetColor((VGPaint)handle);
1296                         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Paint %d %x %x",handle,command.param1,rgba);
1297                 } break;
1298                 case DrawStyle::GradientLinear: {
1299                         vgSetParameteri(handle, VG_PAINT_TYPE, VG_PAINT_TYPE_LINEAR_GRADIENT);
1300                         VGfloat params[]={style->x1,style->y1,style->x2,style->y2,style->r};
1301                         //Log::getInstance()->log("OSD", Log::DEBUG, "Draw Gradient %d %g %g %g %g",handle,params[0],params[1],params[2],params[3]);
1302                         vgSetParameterfv(handle,VG_PAINT_LINEAR_GRADIENT,4,params);
1303
1304
1305
1306                 } break;
1307                 case DrawStyle::GradientRadial: {
1308                         vgSetParameteri(handle, VG_PAINT_TYPE, VG_PAINT_TYPE_RADIAL_GRADIENT);
1309                         VGfloat params[]={style->x1,style->y1,style->x2,style->y2,style->r};
1310                         vgSetParameterfv(handle,VG_PAINT_RADIAL_GRADIENT,5,params);
1311
1312
1313
1314                 } break;
1315                 };
1316                 if (style->ft==DrawStyle::GradientLinear ||style->ft==DrawStyle::GradientRadial) {
1317                         VGfloat colorramp[5*5];
1318                         colorramp[0+0*5]=0.f;
1319                         colorramp[1+0*5]=((float)style->red)/255.f;
1320                         colorramp[2+0*5]=((float)style->green)/255.f;
1321                         colorramp[3+0*5]=((float)style->blue)/255.f;
1322                         colorramp[4+0*5]=((float)style->alpha)/255.f;
1323                         for (int i=0;i<(style->num_colors-1);i++) {
1324                                 colorramp[0+(i+1)*5]=style->grad_pos[i];
1325                                 colorramp[1+(i+1)*5]=((float)style->grad_col[i].red)/255.f;
1326                                 colorramp[2+(i+1)*5]=((float)style->grad_col[i].green)/255.f;
1327                                 colorramp[3+(i+1)*5]=((float)style->grad_col[i].blue)/255.f;
1328                                 colorramp[4+(i+1)*5]=((float)style->grad_col[i].alpha)/255.f;
1329                         }
1330                         colorramp[0+(style->num_colors)*5]=1.f;
1331                         colorramp[1+(style->num_colors)*5]=((float)style->grad_col[style->num_colors-1].red)/255.f;
1332                         colorramp[2+(style->num_colors)*5]=((float)style->grad_col[style->num_colors-1].green)/255.f;
1333                         colorramp[3+(style->num_colors)*5]=((float)style->grad_col[style->num_colors-1].blue)/255.f;
1334                         colorramp[4+(style->num_colors)*5]=((float)style->grad_col[style->num_colors-1].alpha)/255.f;
1335                         vgSetParameteri(handle, VG_PAINT_COLOR_RAMP_SPREAD_MODE,VG_COLOR_RAMP_SPREAD_REFLECT);
1336                         vgSetParameteri(handle, VG_PAINT_COLOR_RAMP_PREMULTIPLIED,VG_FALSE);
1337                         vgSetParameterfv(handle,VG_PAINT_COLOR_RAMP_STOPS,5+(style->num_colors)*5,colorramp);
1338                 }
1339
1340                 return handle;
1341         } break;
1342
1343
1344                 case OVGimageUploadLine:
1345                         {}
1346
1347         }
1348
1349         return 0;
1350 }
1351
1352 bool OsdOpenVG::processTasks()
1353 {
1354         bool worked=false;
1355         taskmutex.Lock();
1356         vgmutex.Lock();
1357         while (vgcommands.size()>0)
1358         {
1359                 OpenVGCommand comm=vgcommands.front();
1360                 vgcommands.pop_front();
1361                 taskmutex.Unlock();
1362
1363                 OpenVGResponse resp;
1364                 resp.result=handleTask(comm);
1365                 resp.id=comm.id;
1366                 taskmutex.Lock();
1367                 if (comm.id) {
1368                         vgresponses.push_back(resp);
1369                 }
1370                 taskmutex.Unlock();
1371                 vgmutex.Unlock();
1372                 //threadCheckExit();
1373                 vgtaskSignal.signal();
1374                 taskmutex.Lock();
1375                 vgmutex.Lock();
1376                 worked=true;
1377         }
1378         taskmutex.Unlock();
1379         vgmutex.Unlock();
1380
1381         return worked;
1382 }
1383
1384 bool OsdOpenVG::haveOpenVGResponse(unsigned int id,unsigned int * resp)
1385 {
1386         taskmutex.Lock();
1387         if (vgresponses.size()>0)
1388         {
1389                 std::deque<OpenVGResponse>::iterator itty=vgresponses.begin();
1390                 while (itty!=vgresponses.end())
1391                 {
1392                         if ((*itty).id==id) {
1393                                 *resp=(*itty).result;
1394                                 taskmutex.Unlock();
1395                                 return true;
1396                         }
1397                         itty++;
1398                 }
1399         }
1400         taskmutex.Unlock();
1401         return false;
1402 }
1403
1404
1405 unsigned int  OsdOpenVG::putOpenVGCommand(OpenVGCommand& comm,bool wait)
1406 {
1407         taskmutex.Lock();
1408         if (wait){
1409                 comm.id=wait_id;
1410                 wait_id++;
1411         } else {
1412                 comm.id=0; // we are not waiting
1413         }
1414         vgcommands.push_back(comm);
1415         taskmutex.Unlock();
1416         threadSignal();
1417         while (wait) {
1418                 unsigned int resp;
1419                 if (!haveOpenVGResponse(comm.id,&resp)) {
1420                         struct timespec target_time;
1421                         clock_gettime(CLOCK_REALTIME,&target_time);
1422                         target_time.tv_nsec+=1000000LL*100;
1423                         if (target_time.tv_nsec>999999999) {
1424                                         target_time.tv_nsec-=1000000000L;
1425                                         target_time.tv_sec+=1;
1426                         }
1427                         vgtaskSignal.waitForSignalTimed(&target_time);
1428                 } else {
1429                         return resp;
1430                 }
1431         }
1432         return 0;
1433 }
1434
1435
1436
1437 void OsdOpenVG::destroyImageRef(ImageIndex index)
1438 {
1439         struct OpenVGCommand comm;
1440         comm.task=OVGdestroyImageRef;
1441         comm.param1=index;
1442         putOpenVGCommand(comm,false);
1443 }
1444
1445
1446 bool OsdOpenVG::getStaticImageData(unsigned int static_id, UCHAR **userdata, ULONG *length)
1447 {
1448         if (sa_MAX>static_id) {
1449                 *userdata = static_artwork_begin[static_id];
1450                 *length = static_artwork_end[static_id] - static_artwork_begin[static_id];
1451                 return true;
1452         }
1453
1454         *userdata = NULL;
1455         *length = 0;
1456         return false;
1457
1458 }
1459
1460 void  OsdOpenVG::createPicture(struct PictureInfo& pict_inf)
1461 {
1462         struct OpenVGCommand comm;
1463         Log::getInstance()->log("OsdOpenVG", Log::DEBUG, "TVMedia Create Picture %d",pict_inf.type);
1464         if (pict_inf.type == PictureInfo::RGBAMemBlock) {
1465                 comm.task = OVGcreateImageMemory;
1466                 comm.data =  new PictureInfo(pict_inf);
1467                 putOpenVGCommand(comm,false);
1468         } else if (pict_inf.type == PictureInfo::EGLImage) {
1469                 comm.task = OVGreadyEGLImage;
1470                 comm.data =  new PictureInfo(pict_inf);
1471                 putOpenVGCommand(comm,false);
1472         } else {
1473                 // unsupported
1474                 pict_inf.decoder->freeReference(pict_inf.reference);
1475
1476
1477         }
1478 }
1479
1480 bool OsdOpenVG::getEGLPicture(struct OsdVector::PictureInfo & info , EGLDisplay * display)
1481 {
1482         struct OpenVGCommand comm;
1483         info.type = PictureInfo::EGLImage;
1484         comm.task = OVGcreateEGLImage;
1485         comm.data = &info;
1486         *display = egl_display;
1487         return  putOpenVGCommand(comm,true);
1488 }
1489
1490
1491
1492 ImageIndex OsdOpenVG::createMonoBitmap(void *base,int width,int height)
1493 {
1494         struct OpenVGCommand comm;
1495         comm.task=OVGcreateMonoBitmap;
1496         comm.param1=width;
1497         comm.param2=height;
1498         comm.data=base;
1499         return putOpenVGCommand(comm,true);
1500 }
1501
1502 ImageIndex OsdOpenVG::createImagePalette(int width,int height,const unsigned char *image_data,const unsigned int*palette_data)
1503 {
1504     struct OpenVGCommand comm;
1505     comm.task=OVGcreateImagePalette;
1506     comm.param1=width;
1507     comm.param2=height;
1508     comm.data=image_data;
1509     comm.data2=palette_data;
1510     return putOpenVGCommand(comm,true);
1511 }
1512
1513 void OsdOpenVG::destroyStyleRef(VectorHandle index)
1514 {
1515         struct OpenVGCommand comm;
1516         comm.task=OVGdestroyPaint;
1517         comm.param1=index;
1518         putOpenVGCommand(comm,false);
1519 }
1520
1521 VectorHandle OsdOpenVG::createStyleRef(const DrawStyle &c)
1522 {
1523         unsigned int col=c.rgba();
1524         struct OpenVGCommand comm;
1525         comm.task=OVGcreateColorRef;
1526         comm.param1=col<<8 | (col &0xff000000)>>24;
1527         comm.data=&c;
1528         return putOpenVGCommand(comm,true);
1529 }
1530
1531
1532
1533