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