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