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