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