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