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