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