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