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