]> git.vomp.tv Git - vompclient.git/blob - videoomx.cc
Rewrite timers class using std::thread/mutex/cond/chrono
[vompclient.git] / videoomx.cc
1 /*
2     Copyright 2004-2005 Chris Tallon, 2009-12 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 #include "videoomx.h"
22 #include "audioomx.h"
23 #include "demuxer.h"
24 #include "vdr.h"
25 #include "woptionpane.h"
26 #include "osdopenvg.h"
27 #include "boxstack.h"
28 #include "inputman.h"
29
30 #include <bcm_host.h>
31
32 #include <linux/fb.h>
33
34 // temp
35 #include "log.h"
36
37 //A lot of parts of this file are heavily inspired by xbmc omx implementations
38
39 VideoOMX::VideoOMX() {
40
41         omx_running = false;
42
43         omx_vid_dec = 0;
44         cur_input_buf_omx = NULL;
45         omx_h264 = omx_mpeg2 = true;
46         clock_references = 0;
47
48         omx_vid_stalled = false;
49
50         offsetnotset = true;
51         offsetvideonotset = true;
52         offsetaudionotset = true;
53         startoffset = 0;
54         lastrefaudiotime = 0;
55         lastrefvideotime = 0;
56         lastreftimeOMX = 0;
57         lastreftimePTS = 0;
58         firstsynched = false;
59         cur_clock_time=0;
60         mpeg2_supported=false;
61         //cur_pts=0;
62
63         mode=NORMAL;
64         xpos=ypos=0.f;
65         deinterlace=2; //advanced
66
67         signalon=false;
68         outputinterlaced=0;
69
70         strcpy(L_VPE_OMX_CLOCK, VPE_OMX_CLOCK);
71         strcpy(L_VPE_OMX_H264_DECODER, VPE_OMX_H264_DECODER);
72         strcpy(L_VPE_OMX_MPEG2_DECODER, VPE_OMX_MPEG2_DECODER);
73         strcpy(L_VPE_OMX_VIDEO_SCHED, VPE_OMX_VIDEO_SCHED);
74         strcpy(L_VPE_OMX_VIDEO_REND, VPE_OMX_VIDEO_REND);
75         strcpy(L_VPE_OMX_VIDEO_DEINTERLACE, VPE_OMX_VIDEO_DEINTERLACE);
76 }
77
78 VideoOMX::~VideoOMX()
79 {
80   instance = NULL;
81 }
82
83 int VideoOMX::init(UCHAR tformat)
84 {
85   if (initted) return 0;
86   initted = 1;
87
88   // libcec calls bcm_host_init() - but in case CEC is disabled call it here as well.
89   // Seems safe to call it more than once.
90   bcm_host_init();
91
92   int ret=vc_gencmd_send("codec_enabled MPG2");
93   if (ret!=0) {
94           Log::getInstance()->log("Video", Log::DEBUG, "vc_gencmd_send failed %x",ret);
95   } else {
96           char buffer[1024];
97           ret=vc_gencmd_read_response(buffer,sizeof(buffer));
98           if (ret!=0) {
99                   Log::getInstance()->log("Video", Log::DEBUG, "vc_gencmd_read_response failed %x",ret);
100           } else {
101                   if (STRCASECMP(buffer,"MPG2=enabled")==0) {
102                           mpeg2_supported=true;
103                   } else if (STRCASECMP(buffer,"MPG2=disabled")==0) {
104                           mpeg2_supported=false;
105                   } else {
106                           Log::getInstance()->log("Video", Log::DEBUG, "Undefined mpg codec answer %s",buffer);
107                   }
108           }
109   }
110
111   if (!setFormat(tformat))           { shutdown(); return 0; }
112   if (!setConnection(HDMI))  { shutdown(); return 0; }
113   if (!setAspectRatio(ASPECT4X3,12,11))    { shutdown(); return 0; }
114   if (!setMode(NORMAL))              { shutdown(); return 0; }
115   if (!setSource())                  { shutdown(); return 0; }
116   if (!attachFrameBuffer())          { shutdown(); return 0; }
117
118   setTVsize(ASPECT16X9);
119   selectVideoMode(0);
120
121
122   OMX_ERRORTYPE error;
123         error = OMX_Init();
124         if (error != OMX_ErrorNone) {
125                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX failed %x",
126                                 error);
127                 return 0;
128         }
129
130
131
132
133
134   //stop();
135
136
137
138   return 1;
139 }
140
141
142
143
144 OMX_ERRORTYPE VideoOMX::EventHandler_OMX(OMX_IN OMX_HANDLETYPE handle,OMX_IN OMX_PTR appdata,
145            OMX_IN OMX_EVENTTYPE event_type,OMX_IN OMX_U32 data1,
146            OMX_IN OMX_U32 data2,OMX_IN OMX_PTR event_data) {
147
148         //Log::getInstance()->log("Video", Log::NOTICE, "eventHandler %x %x %x %x %x",handle,event_type,data1,data2,event_data);
149
150         struct VPE_OMX_EVENT  new_event;
151         new_event.handle=handle;
152         new_event.appdata=appdata;
153         new_event.event_type=event_type;
154         new_event.data1=data1;
155         new_event.data2=data2;
156         new_event.event_data=event_data;
157
158         VideoOMX *video=(VideoOMX *)getInstance();
159         video->AddOmxEvent(new_event);
160
161 /*      switch (event_type) {
162         case OMX_EventCmdComplete: {
163
164         } break;
165         }*/
166
167         return OMX_ErrorNone;
168
169 }
170
171 void VideoOMX::AddOmxEvent(VPE_OMX_EVENT  new_event)
172 {
173         omx_event_mutex.Lock();
174     omx_events.push_back(new_event);
175         omx_event_mutex.Unlock();
176         omx_event_ready_signal.signal();
177 }
178
179
180 OMX_ERRORTYPE VideoOMX::EmptyBufferDone_OMX(OMX_IN OMX_HANDLETYPE hcomp,OMX_IN OMX_PTR appdata,OMX_IN OMX_BUFFERHEADERTYPE* buffer){
181
182 //      Log::getInstance()->log("Video", Log::NOTICE, "EmptyBufferDone");
183         VideoOMX *video=(VideoOMX *)getInstance();
184 /*      long long temp =buffer->nTimeStamp.nLowPart
185                                                                 | ((long long) buffer->nTimeStamp.nHighPart << 32);
186         Log::getInstance()->log("Video", Log::NOTICE, "EBD Video %lld  %x",temp,buffer->nFlags);*/
187         video->ReturnEmptyOMXBuffer(buffer);
188         return OMX_ErrorNone;
189
190 }
191
192 void VideoOMX::ReturnEmptyOMXBuffer(OMX_BUFFERHEADERTYPE* buffer){
193         input_bufs_omx_mutex.Lock();
194         //Log::getInstance()->log("Video", Log::NOTICE, "ReturnEmptyOMXBuffer %d %d",input_bufs_omx_free.size(),input_bufs_omx_all.size());
195         input_bufs_omx_free.push_back(buffer);
196         //Log::getInstance()->log("Video", Log::NOTICE, "ReturnEmptyOMXBuffer %d",input_bufs_omx_free.size());
197         input_bufs_omx_mutex.Unlock();
198         omx_event_ready_signal.signal();
199 }
200
201  OMX_ERRORTYPE VideoOMX::FillBufferDone_OMX(OMX_IN OMX_HANDLETYPE hcomp, OMX_IN OMX_PTR appdata,OMX_IN OMX_BUFFERHEADERTYPE* buffer) {
202          //Log::getInstance()->log("Video", Log::NOTICE, "FillBufferDone");
203         return OMX_ErrorNone;
204 }
205
206
207
208 int VideoOMX::shutdown()
209 {
210   if (!initted) return 0;
211   initted = 0;
212   Log::getInstance()->log("Video", Log::NOTICE, "Shutdown video module");
213
214   DeAllocateCodecsOMX();
215   OMX_Deinit();
216   //vc_tv_show_info(0); // back to console
217   // Restore console
218   int fd_fbset=0;
219   struct fb_var_screeninfo screeninfo;
220   fd_fbset=open("/dev/fb0",O_RDONLY);
221   if (fd_fbset<0) {
222           Log::getInstance()->log("Video", Log::CRIT, "Could not open frame buffer device %d", fd_fbset);
223           return 0;
224   }
225   if (ioctl(fd_fbset, FBIOGET_VSCREENINFO, &screeninfo)){
226           close(fd_fbset);
227           Log::getInstance()->log("Video", Log::CRIT, "Could not FBIOGET_VSCREENINFO frame buffer device");
228           return 0;
229   }
230   screeninfo.bits_per_pixel=8;
231   if (ioctl(fd_fbset, FBIOPUT_VSCREENINFO, &screeninfo)){
232           Log::getInstance()->log("Video", Log::CRIT, "Could not FBIOPUT_VSCREENINFO frame buffer device");
233   }
234   screeninfo.bits_per_pixel=16;
235   if (ioctl(fd_fbset, FBIOPUT_VSCREENINFO, &screeninfo)){
236           Log::getInstance()->log("Video", Log::CRIT, "Could not FBIOPUT_VSCREENINFO frame buffer device");
237   }
238   close(fd_fbset);
239   return 1;
240 }
241
242
243
244 bool VideoOMX::loadOptionsFromServer(VDR* vdr)
245 {
246         Log::getInstance()->log("Video", Log::DEBUG, "VideoOMX config load");
247     char *name=vdr->configLoad("VideoOMX","SDDeinterlacing");
248
249     if (name != NULL) {
250                 if (STRCASECMP(name, "None") == 0) {
251                         deinterlace = 0;
252                 }/* else if (STRCASECMP(name, "LineDouble") == 0) {
253                         deinterlace = 1;
254                 }*/ else if (STRCASECMP(name, "Advanced") == 0) {
255                         deinterlace = 2;
256                 } /*else if (STRCASECMP(name, "Crazy") == 0) {
257                         deinterlace = 3; // this does not activate deinterlacing but a image filter, just for fun
258                 }*/ else if (STRCASECMP(name, "Fast") == 0) {
259                         deinterlace = 4;
260                 }
261                 Log::getInstance()->log("Video", Log::DEBUG, "Set deinterlacing to %s %d",name,deinterlace);
262                 delete[] name;
263         }
264
265    return true;
266
267 }
268
269 bool VideoOMX::handleOptionChanges(Option* option)
270 {
271     if (Video::handleOptionChanges(option))
272                 return true;
273         switch (option->id) {
274         case 1: {
275                 if (STRCASECMP(option->options[option->userSetChoice], "None") == 0) {
276                         deinterlace = 0;
277                 } /*else if (STRCASECMP(option->options[option->userSetChoice], "LineDouble")
278                                 == 0) {
279                         deinterlace = 1;
280                 }*/ else if (STRCASECMP(option->options[option->userSetChoice], "Advanced")
281                                 == 0) {
282                         deinterlace = 2;
283                 } /*else if (STRCASECMP(option->options[option->userSetChoice], "Crazy")
284                                 == 0) {
285                         deinterlace = 3;
286                 }*/ else if (STRCASECMP(option->options[option->userSetChoice], "Fast")
287                         == 0) {
288                         deinterlace = 4;
289                 }
290                 Log::getInstance()->log("Video", Log::DEBUG, "Set deinterlacing to %s %d",option->options[option->userSetChoice],deinterlace);
291                 return true;
292         }
293         break;
294         };
295         return false;
296
297 }
298
299 bool VideoOMX::saveOptionstoServer()
300 {
301
302     switch (deinterlace) {
303         case 0:
304                 VDR::getInstance()->configSave("VideoOMX","SDDeinterlacing", "None");
305                 break;
306         /*case 1:
307                 VDR::getInstance()->configSave("VideoOMX","SDDeinterlacing", "LineDouble");
308                 break;*/
309         case 2:
310                 VDR::getInstance()->configSave("VideoOMX","SDDeinterlacing", "Advanced");
311                 break;
312         /*case 3:
313                 VDR::getInstance()->configSave("VideoOMX","SDDeinterlacing", "Crazy");
314                 break;*/
315         case 4:
316                 VDR::getInstance()->configSave("VideoOMX", "SDDeinterlacing", "Fast");
317                 break;
318         };
319
320     return true;
321 }
322
323 /*Option(UINT id, const char* displayText, const char* configSection, const char* configKey, UINT optionType,
324            UINT numChoices, UINT defaultChoice, UINT startInt,
325            const char * const * options, const char * const * optionkeys = NULL, AbstractOption* handler=NULL);*/
326
327 bool VideoOMX::addOptionsToPanes(int panenumber,Options *options,WOptionPane* pane)
328 {
329     if (!Video::addOptionsToPanes(panenumber,options,pane)) return false;
330
331
332     Option* option;
333     if (panenumber == 2)
334     {
335                 static const char* deinterlaceopts[] = { "None", "Fast",/*"LineDouble",*/"Advanced"/*,"Crazy"*/ };
336         option = new Option(1,tr("SD Deinterlacing"), "VideoOMX","SDDeinterlacing",Option::TYPE_TEXT,/*4,2*/3,2,0,deinterlaceopts,NULL,false,this);
337         options->push_back(option);
338         pane->addOptionLine(option);
339     }
340
341     return true;
342 }
343
344
345
346 int VideoOMX::setTVsize(UCHAR ttvsize)
347 {
348   if (tvsize!=ttvsize) pendingmodechange=true;
349   tvsize=ttvsize;
350   return 1;
351 }
352
353 UCHAR VideoOMX::getTVsize()       {
354         /*if (hdmi)*/
355         return ASPECT16X9; // in order that aspect ratio changes are reported
356         //return tvsize;
357 }
358
359 void VideoOMX::executePendingModeChanges()
360 {
361         if (pendingmodechange) {
362                 Log::getInstance()->log("Video", Log::NOTICE, "Execute pending mode change");
363                 Osd::getInstance()->shutdown();
364                 selectVideoMode(0);
365                 Osd::getInstance()->restore();
366                 Osd::getInstance()->init();
367                 BoxStack::getInstance()->redrawAllBoxes();
368                 initted = 1;
369         }
370 }
371
372 int VideoOMX::setDefaultAspect()
373 {
374   return setAspectRatio(tvsize,parx,pary);
375 }
376
377
378
379 int VideoOMX::setFormat(UCHAR tformat)
380 {
381   if (!initted) return 0;
382   if ((tformat != PAL) && (tformat != NTSC)
383                   && (tformat != PAL_M) && (tformat != NTSC_J)) return 0;
384   format = PAL;
385   tvsystem = tformat;
386
387   if (format == PAL)
388   {
389     screenWidth = 720;
390     screenHeight = 576;
391   }
392
393 //  selectVideoMode(0);
394
395   return 1;
396 }
397
398 void VideoOMX::selectVideoMode(int interlaced)
399 {
400         TV_GET_STATE_RESP_T tvstate;
401         vc_tv_get_state(&tvstate);
402
403         if ((tvstate.state & VC_HDMI_UNPLUGGED)) {
404                 hdmi = false;
405                 Log::getInstance()->log("Video", Log::NOTICE, "HDMI unplugged");
406         } else {
407                 hdmi = true;
408                 Log::getInstance()->log("Video", Log::NOTICE, "HDMI plugged");
409                 if (connection==COMPOSITERGB) {
410                         hdmi=false;
411                         Log::getInstance()->log("Video", Log::NOTICE, "SDTV set");
412                 } else {
413                         hdmi=true;
414                         Log::getInstance()->log("Video", Log::NOTICE, "HDMI set");
415                 }
416         }
417
418
419         if (hdmi) {
420                 TV_SUPPORTED_MODE_T all_supp_modes[200];
421                 HDMI_RES_GROUP_T pref_group;
422                 TV_SUPPORTED_MODE_T  *mymode=NULL;
423                 TV_SUPPORTED_MODE_T  *mymode_second_best=NULL;
424                 // bool got_optimum=false;
425                 uint32_t pref_mode;
426                 HDMI_RES_GROUP_T group=HDMI_RES_GROUP_CEA;
427                 int all_my_modes=vc_tv_hdmi_get_supported_modes(HDMI_RES_GROUP_CEA,
428                                 all_supp_modes,200,
429                                 &pref_group,&pref_mode);
430                 if (all_my_modes<=0) {
431                         group=HDMI_RES_GROUP_DMT;
432                         all_my_modes=vc_tv_hdmi_get_supported_modes(HDMI_RES_GROUP_DMT,
433                                         all_supp_modes,200,
434                                         &pref_group,&pref_mode);
435                         Log::getInstance()->log("Video", Log::NOTICE, "No CEA fall back to DMT modes ");
436                 }
437
438
439
440
441                 int target_fps=50;
442                 if (format==PAL)target_fps=50;
443                 else if (format==NTSC) target_fps=60;
444
445                 //Now first determine native resolution
446                 int native_width=1920;
447                 int native_height=1080;
448                 for (int i=0;i<all_my_modes;i++) {
449                         if (all_supp_modes[i].native) {
450                                 mymode=all_supp_modes+i;
451                                 Log::getInstance()->log("Video", Log::NOTICE, "Found native mode %dx%d %d Hz i: %d",
452                                                 mymode->width,mymode->height,mymode->frame_rate,mymode->scan_mode);
453                                 native_width=mymode->width;
454                                 native_height=mymode->height;
455                         }
456
457                 }
458                 //Now find the mode which matches best
459                 for (int i=0;i<all_my_modes;i++) {
460                         TV_SUPPORTED_MODE_T  *curmode=all_supp_modes+i;
461                         if (curmode->width==native_width &&
462                                         curmode->height==native_height &&
463                                         curmode->frame_rate==target_fps) {
464                                 if(curmode->scan_mode==interlaced) {
465                                         //got_optimum=true;
466                                         mymode=curmode;
467                                         Log::getInstance()->log("Video", Log::NOTICE, "Found optimum mode %dx%d %d Hz i: %d",
468                                                         mymode->width,mymode->height,mymode->frame_rate,mymode->scan_mode);
469                                 } else {
470                                         mymode_second_best=curmode;
471                                         Log::getInstance()->log("Video", Log::NOTICE, "Found close to optimum mode %dx%d %d Hz i: %d",
472                                                         mymode_second_best->width,mymode_second_best->height,
473                                                         mymode_second_best->frame_rate,mymode_second_best->scan_mode);
474                                 }
475
476                         }
477                 }
478                 // InputMan::getInstance()->shutdown(); FIXME FIXME FIXME - disabling this temp, why does this have to run?
479                 vc_tv_power_off();
480                 if (mymode) {
481                         Log::getInstance()->log("Video", Log::NOTICE, "Switch to optimum mode");
482                         vc_tv_hdmi_power_on_explicit(HDMI_MODE_HDMI,group,mymode->code);
483                 } else if (mymode_second_best) {
484                         Log::getInstance()->log("Video", Log::NOTICE, "Switch to close to optimum mode");
485                         vc_tv_hdmi_power_on_explicit(HDMI_MODE_HDMI,group,mymode_second_best->code);
486                 } else {
487                         Log::getInstance()->log("Video", Log::NOTICE, "Switch to prefered mode");
488                         vc_tv_hdmi_power_on_best(1920,1080,target_fps,interlaced?HDMI_INTERLACED:HDMI_NONINTERLACED,
489                                         (EDID_MODE_MATCH_FLAG_T)(HDMI_MODE_MATCH_FRAMERATE|HDMI_MODE_MATCH_RESOLUTION|HDMI_MODE_MATCH_SCANMODE));
490                 }
491                 hdmi=true;
492                 outputinterlaced=interlaced;
493         } else {
494                 /* analog tv case */
495                 Log::getInstance()->log("Video", Log::NOTICE, "Analog tv case");
496                 // InputMan::getInstance()->shutdown(); FIXME FIXME FIXME - disabling this temp, why does this have to run?             vc_tv_power_off();
497                 SDTV_MODE_T setmode=SDTV_MODE_PAL;
498                 SDTV_OPTIONS_T options;
499
500                 switch (tvsize) {
501                 default:
502                 case ASPECT16X9:
503                         Log::getInstance()->log("Video", Log::NOTICE, "SDTV aspect 16:9");
504                         options.aspect=SDTV_ASPECT_16_9; break;
505                 case ASPECT4X3:
506                         Log::getInstance()->log("Video", Log::NOTICE, "SDTV aspect 4:3");
507                         options.aspect=SDTV_ASPECT_4_3; break;
508                 case ASPECT14X9:
509                         Log::getInstance()->log("Video", Log::NOTICE, "SDTV aspect 14:9");
510                         options.aspect=SDTV_ASPECT_14_9; break;
511                 };
512
513                 if (format==PAL) setmode=SDTV_MODE_PAL;
514                 else if (format==NTSC) setmode=SDTV_MODE_NTSC;
515                 else if (format==PAL_M)setmode=SDTV_MODE_PAL_M;
516                 else if (format==NTSC_J) setmode=SDTV_MODE_NTSC_J;
517                 vc_tv_sdtv_power_on(setmode,&options);
518                 hdmi=false;
519         }
520
521 //      InputMan::getInstance()->init(); // FIXME complete shutdown and reinit maybe heavy handed. FIXME FIXME FIXME - disabled temp
522     // If this was just to reinit CEC then funcitons should be made to do that
523
524
525         signalon=true;
526         pendingmodechange=false;
527
528 }
529
530
531 int VideoOMX::setConnection(UCHAR tconnection)
532 {
533   if (!initted) return 0;
534   if ((tconnection != COMPOSITERGB)  && (tconnection != HDMI)) return 0;
535   if (connection!=tconnection) pendingmodechange=true;
536   connection = tconnection;
537
538 //  if (ioctl(fdVideo, AV_SET_VID_OUTPUT, connection) != 0) return 0;
539   return 1;
540 }
541
542 int VideoOMX::setAspectRatio(UCHAR taspectRatio, int tparx,int tpary)
543 {
544   if (!initted) return 0;
545   //if ((taspectRatio != ASPECT4X3) && (taspectRatio != ASPECT16X9)) return 0;
546   aspectRatio = taspectRatio;
547   parx=tparx;
548   pary=tpary;
549
550   Log::getInstance()->log("Video", Log::DEBUG, "Setting aspect to %i: PAR %d %d", aspectRatio,parx,pary);
551
552   updateMode();
553 //  if (ioctl(fdVideo, AV_SET_VID_RATIO, aspectRatio) != 0) return 0;
554   return 1;
555 }
556
557 int VideoOMX::setMode(UCHAR tmode)
558 {
559   if (!initted) return 0;
560   if (tmode==LETTERBOX || tmode==NORMAL) mode=tmode;
561   updateMode();
562   return 1;
563 }
564
565 bool VideoOMX::setVideoDisplay(VideoDisplay display)
566 {
567         if (!initted) return false;
568         switch (display.mode)
569         {
570         case None: return true; //??
571         case Fullscreen: {
572                 windowed = false;
573
574         } break;
575         case Quarter: {
576                 windowed =true;
577                 xpos = ((float) display.x) / ((float) screenWidth);
578                 ypos = ((float) display.y) / ((float) screenHeight);
579                 width = 0.5f;
580                 height = 0.5f;
581         } break;
582
583         case Eighth: {
584                 windowed =true;
585                 xpos = ((float) display.x) / ((float) screenWidth);
586                 ypos = ((float) display.y) / ((float) screenHeight);
587                 width = 0.25f;
588                 height = 0.25f;
589         } break;
590
591         case Window: {
592                 windowed =true;
593                 xpos = ((float) display.x) / ((float) screenWidth);
594                 ypos = ((float) display.y) / ((float) screenHeight);
595                 width = ((float) display.width) / ((float) screenWidth);
596                 height = ((float) display.height) / ((float) screenHeight);
597         }break;
598         }
599         updateMode();
600         return true;
601 }
602
603
604 void VideoOMX::updateMode()
605 {
606         clock_mutex.Lock();
607         if (omx_running) {
608                 int oldcancelstate;
609                 int oldcanceltype;
610                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
611                 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
612                 OMX_ERRORTYPE error;
613                 OMX_CONFIG_DISPLAYREGIONTYPE dispconf;
614                 memset(&dispconf, 0, sizeof(dispconf));
615                 dispconf.nSize = sizeof(dispconf);
616                 dispconf.nVersion.nVersion = OMX_VERSION;
617                 dispconf.nPortIndex = omx_rend_input_port;
618                 dispconf.layer = 1;
619                 dispconf.set = OMX_DISPLAY_SET_LAYER;
620                 error = OMX_SetParameter(omx_vid_rend, OMX_IndexConfigDisplayRegion,
621                                 &dispconf);
622                 if (error != OMX_ErrorNone) {
623                         Log::getInstance()->log("Video", Log::DEBUG,
624                                         "Set OMX_IndexConfigDisplayRegion1 failed %x", error);
625                         pthread_setcancelstate(oldcancelstate, NULL);
626                         pthread_setcanceltype(oldcanceltype, NULL);
627                         clock_mutex.Unlock();
628                         return;
629                 }
630
631
632                 dispconf.pixel_x =parx;
633                 dispconf.pixel_y=pary;
634                 dispconf.set = OMX_DISPLAY_SET_PIXEL;
635                 error = OMX_SetParameter(omx_vid_rend, OMX_IndexConfigDisplayRegion,
636                                 &dispconf);
637                 if (error != OMX_ErrorNone) {
638                         Log::getInstance()->log("Video", Log::DEBUG,
639                                         "Set OMX_IndexConfigDisplayRegion5 failed %x", error);
640                         pthread_setcancelstate(oldcancelstate, NULL);
641                         pthread_setcanceltype(oldcanceltype, NULL);
642                         clock_mutex.Unlock();
643                         return;
644                 }
645
646
647
648                 dispconf.set = OMX_DISPLAY_SET_FULLSCREEN;
649                 if (!windowed) {
650                         //Set Fullscreen
651                         dispconf.fullscreen = OMX_TRUE;
652                 } else {
653                         dispconf.fullscreen = OMX_FALSE;
654                 }
655                 error = OMX_SetParameter(omx_vid_rend, OMX_IndexConfigDisplayRegion,
656                                 &dispconf);
657                 if (error != OMX_ErrorNone) {
658                         Log::getInstance()->log("Video", Log::DEBUG,
659                                         "Set OMX_IndexConfigDisplayRegion2 failed %x", error);
660                         pthread_setcancelstate(oldcancelstate, NULL);
661                         pthread_setcanceltype(oldcanceltype, NULL);
662                         clock_mutex.Unlock();
663                         return;
664                 }
665
666                 dispconf.set = OMX_DISPLAY_SET_MODE;
667                 if (!windowed) {
668                         dispconf.mode = (mode == NORMAL) ? OMX_DISPLAY_MODE_FILL
669                                         : OMX_DISPLAY_MODE_LETTERBOX;
670                 } else {
671                         dispconf.mode = OMX_DISPLAY_MODE_LETTERBOX;
672                 }
673                 error = OMX_SetParameter(omx_vid_rend, OMX_IndexConfigDisplayRegion,
674                                 &dispconf);
675                 if (error != OMX_ErrorNone) {
676                         Log::getInstance()->log("Video", Log::DEBUG,
677                                         "Set OMX_IndexConfigDisplayRegion3 failed %x", error);
678                         pthread_setcancelstate(oldcancelstate, NULL);
679                         pthread_setcanceltype(oldcanceltype, NULL);
680                         clock_mutex.Unlock();
681                         return;
682                 }
683
684                 if (windowed) {
685                         unsigned int display_width, display_height;
686                         display_width = display_height = 0;
687                         if (graphics_get_display_size(0, &display_width, &display_height)
688                                         < 0) {
689                                 Log::getInstance()->log("OSD", Log::WARN,
690                                                 "Getting display size failed! (BCM API) ");
691                                 pthread_setcancelstate(oldcancelstate, NULL);
692                                 pthread_setcanceltype(oldcanceltype, NULL);
693                                 clock_mutex.Unlock();
694                                 return;
695                         }
696                         //UnSetFullscreen with window
697                         dispconf.set = OMX_DISPLAY_SET_DEST_RECT;
698                         dispconf.dest_rect.x_offset
699                                         = (int) (xpos * ((float) display_width));
700                         dispconf.dest_rect.y_offset = (int) (ypos
701                                         * ((float) display_height));
702                         dispconf.dest_rect.width = (int) (width * ((float) display_width));
703                         dispconf.dest_rect.height = (int) (height * ((float) display_height));
704                         Log::getInstance()->log("Video", Log::DEBUG,
705                                                                         "Set dest_rect as %d %d %d %d", dispconf.dest_rect.x_offset,dispconf.dest_rect.y_offset,
706                                                                         dispconf.dest_rect.width , dispconf.dest_rect.height);
707
708                         error = OMX_SetParameter(omx_vid_rend,
709                                         OMX_IndexConfigDisplayRegion, &dispconf);
710                         if (error != OMX_ErrorNone) {
711                                 Log::getInstance()->log("Video", Log::DEBUG,
712                                                 "Set OMX_IndexConfigDisplayRegion failed %x", error);
713                                 pthread_setcancelstate(oldcancelstate, NULL);
714                                 pthread_setcanceltype(oldcanceltype, NULL);
715                                 clock_mutex.Unlock();
716                                 return;
717                         }
718                 }
719                 pthread_setcancelstate(oldcancelstate, NULL);
720                 pthread_setcanceltype(oldcanceltype, NULL);
721
722         }
723         clock_mutex.Unlock();
724 }
725
726 int VideoOMX::signalOff()
727 {
728         //TODO reinit osd
729         Log::getInstance()->log("Video", Log::NOTICE, "signalOff");
730         Osd::getInstance()->stopUpdate(); // turn off drawing thread
731         InputMan::getInstance()->shutdown();
732         vc_tv_power_off();
733         InputMan::getInstance()->init(); // FIXME
734         signalon=false;
735     return 1;
736 }
737
738 int VideoOMX::signalOn()
739 {
740   if (!signalon)  {
741           Osd::getInstance()->shutdown();
742           Log::getInstance()->log("Video", Log::NOTICE, "signalOn");
743           selectVideoMode(0);
744           Osd::getInstance()->restore();
745           Osd::getInstance()->init();
746           BoxStack::getInstance()->redrawAllBoxes();
747           initted=1;
748
749   }
750   return 1;
751 }
752
753 int VideoOMX::setSource()
754 {
755   if (!initted) return 0;
756
757   // What does this do...
758 //  if (ioctl(fdVideo, AV_SET_VID_SRC, 1) != 0) return 0;
759   return 1;
760 }
761
762 int VideoOMX::setPosition(int x, int y) {
763         if (!initted)
764                 return 0;
765         xpos = ((float) x*2.f) / ((float) screenWidth);
766         ypos = ((float) y*2.f) / ((float) screenHeight);
767
768         updateMode();
769         return 1;
770 }
771
772 int VideoOMX::sync()
773 {
774   if (!initted) return 0;
775
776 //  if (ioctl(fdVideo, AV_SET_VID_SYNC, 2) != 0) return 0;
777   return 1;
778 }
779
780 void VideoOMX::interlaceSwitch4Demux() {
781         return;
782         Demuxer *demux=Demuxer::getInstance();
783
784         if (hdmi) { // only switch if hdmi and HD or interlaced SD material
785
786
787                 //OMX_Deinit();
788                 int set_interlaced=0;
789                 if (demux->getHorizontalSize()>720  && demux->getInterlaced()) {
790                         set_interlaced=1;
791                 }
792                 Log::getInstance()->log("Video", Log::NOTICE, "switch interlacing %d %d %d",demux->getInterlaced(),outputinterlaced,set_interlaced);
793                 if (outputinterlaced!=set_interlaced) {
794                         selectVideoMode(set_interlaced);
795                         Osd::getInstance()->shutdown();
796                         Osd::getInstance()->restore();
797                         Osd::getInstance()->init();
798                         BoxStack::getInstance()->redrawAllBoxes();
799                         initted=1;
800                 }
801                 //OMX_Init();
802
803
804         }
805
806
807 }
808
809
810 int VideoOMX::play() {
811         if (!initted)
812                 return 0;
813         iframemode = false;
814         Log::getInstance()->log("Video", Log::DEBUG, "enter play");
815
816         interlaceSwitch4Demux();
817
818         if (AllocateCodecsOMX()) {
819                 return 1;
820                 // Otherwise fall back to libav
821         } else {
822                 if (h264) {
823                         omx_h264 = false;
824                         Log::getInstance()->log("Video", Log::NOTICE,
825                                         "Allocate Codecs OMX failed assume h264 unsupported");
826                 } else {
827                         omx_mpeg2 = false;
828                         Log::getInstance()->log("Video", Log::NOTICE,
829                                         "Allocate Codecs OMX failed assume mpeg2 unsupported");
830                 }
831         }
832
833         return 0;
834
835 }
836
837
838 int VideoOMX::initClock()
839 {
840         OMX_ERRORTYPE error;
841         clock_mutex.Lock();
842         if (clock_references==0)
843         {
844
845                 static OMX_CALLBACKTYPE callbacks= {&EventHandler_OMX,&EmptyBufferDone_OMX,&FillBufferDone_OMX};
846                 omx_event_mutex.Lock();
847                 omx_events.clear();
848                 omx_event_mutex.Unlock();
849
850                 error=OMX_GetHandle(&omx_clock,L_VPE_OMX_CLOCK,NULL,&callbacks);
851
852                 if (error!=OMX_ErrorNone) {
853                         Log::getInstance()->log("Video", Log::DEBUG, "Init OMX clock failed %x", error);
854                         clock_mutex.Unlock();
855                         DeAllocateCodecsOMX();
856                         return 0;
857                 }
858
859                 /* TODO Clock config to separate method */
860                 OMX_PORT_PARAM_TYPE p_param;
861                 memset(&p_param,0,sizeof(p_param));
862                 p_param.nSize=sizeof(p_param);
863                 p_param.nVersion.nVersion=OMX_VERSION;
864                 error=OMX_GetParameter(omx_clock,OMX_IndexParamOtherInit,&p_param);
865                 if (error!=OMX_ErrorNone) {
866                         Log::getInstance()->log("Video", Log::DEBUG, "Init clock OMX_GetParameter failed %x", error);
867                         clock_mutex.Unlock();
868                         DeAllocateCodecsOMX();
869                         return 0;
870                 }
871                 omx_clock_output_port=p_param.nStartPortNumber;
872
873                 for (unsigned int i=0;i<p_param.nPorts;i++) {
874                         if (!DisablePort(omx_clock,p_param.nStartPortNumber+i,true) ) {
875                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX clock failed %d",i);
876                                 clock_mutex.Unlock();
877                                 DeAllocateCodecsOMX();
878                                 return 0;
879                         }
880                 }
881
882
883
884
885         }
886         Log::getInstance()->log("Video", Log::DEBUG, "init omx clock %x %x",this,omx_clock);
887         clock_references++;
888         clock_mutex.Unlock();
889         return 1;
890 }
891
892 int VideoOMX::getClockAudioandInit(OMX_HANDLETYPE *p_omx_clock,OMX_U32 *p_omx_clock_output_port)
893 {
894         OMX_ERRORTYPE error;
895         *p_omx_clock=NULL;
896         *p_omx_clock_output_port=0;
897
898         if (!initClock()) {
899                 return 0;
900         }
901         clock_mutex.Lock();
902
903         OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE refclock;
904         memset(&refclock,0,sizeof(refclock));
905         refclock.nSize=sizeof(refclock);
906         refclock.nVersion.nVersion=OMX_VERSION;
907
908         refclock.eClock=OMX_TIME_RefClockAudio;
909
910         //refclock.eClock=OMX_TIME_RefClockVideo;
911         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeActiveRefClock,&refclock);
912         if (error!=OMX_ErrorNone){
913                 Log::getInstance()->log("Video", Log::DEBUG, "Clock OMX_IndexConfigTimeActiveRefClock failed %x", error);
914                 clock_mutex.Unlock();
915                 DeAllocateCodecsOMX();
916                 return 0;
917         }
918
919         OMX_PORT_PARAM_TYPE p_param;
920         memset(&p_param,0,sizeof(p_param));
921         p_param.nSize=sizeof(p_param);
922         p_param.nVersion.nVersion=OMX_VERSION;
923         error=OMX_GetParameter(omx_clock,OMX_IndexParamOtherInit,&p_param);
924         if (error!=OMX_ErrorNone){
925                 Log::getInstance()->log("Video", Log::DEBUG, "Init clock OMX_GetParameter failed %x", error);
926                 clock_mutex.Unlock();
927                 DeAllocateCodecsOMX();
928                 return 0;
929         }
930
931         OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
932         memset(&clock_conf,0,sizeof(clock_conf));
933         clock_conf.nSize=sizeof(clock_conf);
934         clock_conf.nVersion.nVersion=OMX_VERSION;
935         clock_conf.eState=OMX_TIME_ClockStateWaitingForStartTime;
936         clock_conf.nStartTime=intToOMXTicks(0);
937         clock_conf.nOffset=intToOMXTicks(0);
938         if (clock_references==1) clock_conf.nWaitMask=OMX_CLOCKPORT1;
939         else clock_conf.nWaitMask=OMX_CLOCKPORT0|OMX_CLOCKPORT1;
940         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
941         if (error!=OMX_ErrorNone) {
942                 Log::getInstance()->log("Video", Log::DEBUG, "AuI Clock IndexConfigTimeClockState failed %x", error);
943         }
944
945
946         *p_omx_clock_output_port=p_param.nStartPortNumber+1;
947         *p_omx_clock=omx_clock;
948         clock_mutex.Unlock();
949         return 1;
950 }
951
952 int VideoOMX::getClockVideoandInit()
953 {
954         OMX_ERRORTYPE error;
955
956         if (!initClock()) {
957                 return 0;
958         }
959         clock_mutex.Lock();
960
961         if (clock_references==1) { // only if no audio is attached to this clock!
962                 OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE refclock;
963                 memset(&refclock,0,sizeof(refclock));
964                 refclock.nSize=sizeof(refclock);
965                 refclock.nVersion.nVersion=OMX_VERSION;
966
967                 //refclock.eClock=OMX_TIME_RefClockAudio;
968
969                 refclock.eClock=OMX_TIME_RefClockVideo;
970                 error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeActiveRefClock,&refclock);
971                 if (error!=OMX_ErrorNone) {
972                         Log::getInstance()->log("Video", Log::DEBUG, "Clock OMX_IndexConfigTimeActiveRefClock failed %x", error);
973                         clock_mutex.Unlock();
974                         DeAllocateCodecsOMX();
975                         return 0;
976                 }
977         }
978
979         OMX_PORT_PARAM_TYPE p_param;
980         memset(&p_param,0,sizeof(p_param));
981         p_param.nSize=sizeof(p_param);
982         p_param.nVersion.nVersion=OMX_VERSION;
983         error=OMX_GetParameter(omx_clock,OMX_IndexParamOtherInit,&p_param);
984         if (error!=OMX_ErrorNone){
985                 Log::getInstance()->log("Video", Log::DEBUG, "Init clock OMX_GetParameter failed %x", error);
986                 clock_mutex.Unlock();
987                 DeAllocateCodecsOMX();
988                 return 0;
989         }
990
991
992         OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
993         memset(&clock_conf,0,sizeof(clock_conf));
994         clock_conf.nSize=sizeof(clock_conf);
995         clock_conf.nVersion.nVersion=OMX_VERSION;
996         clock_conf.eState=OMX_TIME_ClockStateStopped;
997         clock_conf.nStartTime=intToOMXTicks(0);
998         clock_conf.nOffset=intToOMXTicks(0);
999         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
1000         if (error!=OMX_ErrorNone) {
1001                 Log::getInstance()->log("Video", Log::DEBUG, "VuI Clock IndexConfigTimeClockState failed %x", error);
1002         }
1003
1004
1005         memset(&clock_conf,0,sizeof(clock_conf));
1006         clock_conf.nSize=sizeof(clock_conf);
1007         clock_conf.nVersion.nVersion=OMX_VERSION;
1008         clock_conf.eState=OMX_TIME_ClockStateWaitingForStartTime;
1009         clock_conf.nStartTime=intToOMXTicks(0);
1010         clock_conf.nOffset=intToOMXTicks(0);
1011         if (clock_references==1) clock_conf.nWaitMask=OMX_CLOCKPORT0;
1012         else clock_conf.nWaitMask=OMX_CLOCKPORT0|OMX_CLOCKPORT1;
1013         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
1014         if (error!=OMX_ErrorNone) {
1015                 Log::getInstance()->log("Video", Log::DEBUG, "VuI Clock IndexConfigTimeClockState failed %x", error);
1016         }
1017
1018         omx_clock_output_port=p_param.nStartPortNumber;
1019         clock_mutex.Unlock();
1020
1021         return 1;
1022 }
1023
1024 void VideoOMX::clockUnpause()
1025 {
1026         OMX_ERRORTYPE error;
1027         Log::getInstance()->log("Video", Log::NOTICE, "enter Clockunpause");
1028         clock_mutex.Lock();
1029         if (clock_references>0 && clockpaused) {
1030                 OMX_TIME_CONFIG_SCALETYPE scale_type;
1031                 memset(&scale_type,0,sizeof(scale_type));
1032                 scale_type.nSize=sizeof(scale_type);
1033                 scale_type.nVersion.nVersion=OMX_VERSION;
1034                 scale_type.xScale=1<<16;
1035                 error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeScale,&scale_type);
1036                 if (error!=OMX_ErrorNone) {
1037                         Log::getInstance()->log("Video", Log::DEBUG, "ClockUnpause OMX_IndexConfigTimeScale failed %x", error);
1038                 }
1039                 Log::getInstance()->log("Video", Log::NOTICE, "set playback speed ClockUnpause");
1040                 clockpaused=false;
1041         }
1042         clock_mutex.Unlock();
1043 }
1044
1045
1046 void VideoOMX::clockPause()
1047 {
1048         OMX_ERRORTYPE error;
1049         Log::getInstance()->log("Video", Log::NOTICE, "enter ClockPause");
1050         clock_mutex.Lock();
1051         if (clock_references>0 && !clockpaused) {
1052                 OMX_TIME_CONFIG_SCALETYPE scale_type;
1053                 memset(&scale_type,0,sizeof(scale_type));
1054                 scale_type.nSize=sizeof(scale_type);
1055                 scale_type.nVersion.nVersion=OMX_VERSION;
1056                 scale_type.xScale=0;
1057                 error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeScale,&scale_type);
1058                 if (error!=OMX_ErrorNone) {
1059                         Log::getInstance()->log("Video", Log::DEBUG, "ClockPause OMX_IndexConfigTimeScale failed %x", error);
1060                 }
1061                 Log::getInstance()->log("Video", Log::NOTICE, "set playback speed ClockPause");
1062                 clockpaused=true;
1063         }
1064         clock_mutex.Unlock();
1065 }
1066
1067
1068
1069 int VideoOMX::AllocateCodecsOMX()
1070 {
1071         OMX_ERRORTYPE error;
1072         static OMX_CALLBACKTYPE callbacks= {&EventHandler_OMX,&EmptyBufferDone_OMX,&FillBufferDone_OMX};
1073
1074         Demuxer* demux=Demuxer::getInstance();
1075
1076         dodeint=false;
1077         first_frame=true;
1078
1079         Log::getInstance()->log("Video", Log::NOTICE, "Allocate Codecs OMX");
1080         //Clock, move later to audio including events
1081
1082         Log::getInstance()->log("Video", Log::NOTICE, "Deinter VideoType %d x %d i: %d", demux->getHorizontalSize(),demux->getVerticalSize(),demux->getInterlaced());
1083         if (deinterlace!=0 && /*(demux->getHorizontalSize()<=720 ) &&*/ demux->getInterlaced()) { 
1084                 dodeint=true;
1085
1086
1087                 Log::getInstance()->log("Video", Log::NOTICE, "Deinterlacing activated %d",deinterlace);
1088
1089         }
1090
1091
1092         if (!getClockVideoandInit()){
1093                 return 0;// get the clock and init it if necessary
1094         }
1095
1096
1097         if (!idleClock()) {
1098                 Log::getInstance()->log("Video", Log::DEBUG, "idleClock failed");
1099                 return 0;
1100         }
1101         /* TODO end */
1102
1103         clock_mutex.Lock();
1104         if (h264) {
1105                 error=OMX_GetHandle(&omx_vid_dec,L_VPE_OMX_H264_DECODER,NULL,&callbacks);
1106         } else {
1107                 error=OMX_GetHandle(&omx_vid_dec,L_VPE_OMX_MPEG2_DECODER,NULL,&callbacks);
1108         }
1109
1110         if (error!=OMX_ErrorNone){
1111                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video decoder failed %x", error);
1112                 clock_mutex.Unlock();
1113                 DeAllocateCodecsOMX();
1114                 return 0;
1115         }
1116
1117
1118         Log::getInstance()->log("Video", Log::DEBUG, "Nmark3 ");
1119         OMX_PORT_PARAM_TYPE p_param;
1120         memset(&p_param,0,sizeof(p_param));
1121         p_param.nSize=sizeof(p_param);
1122         p_param.nVersion.nVersion=OMX_VERSION;
1123         error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamVideoInit,&p_param);
1124         if (error!=OMX_ErrorNone){
1125                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX h264 decoder OMX_GetParameter failed %x", error);
1126                 clock_mutex.Unlock();
1127                 DeAllocateCodecsOMX();
1128             return 0;
1129         }
1130         omx_codec_input_port=p_param.nStartPortNumber;
1131         omx_codec_output_port=p_param.nStartPortNumber+1;
1132
1133         if (!DisablePort(omx_vid_dec,omx_codec_input_port) || !DisablePort(omx_vid_dec,omx_codec_output_port)) {
1134                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX video decoder failed");
1135                 clock_mutex.Unlock();
1136                 DeAllocateCodecsOMX();
1137                 return 0;
1138         }
1139
1140         Log::getInstance()->log("Video", Log::DEBUG, "Nmark4 ");
1141
1142         OMX_PARAM_BRCMVIDEODECODEERRORCONCEALMENTTYPE conceal;
1143         memset(&conceal,0,sizeof(conceal));
1144         conceal.nSize=sizeof(conceal);
1145         conceal.nVersion.nVersion=OMX_VERSION;
1146         conceal.bStartWithValidFrame=OMX_FALSE;
1147
1148         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamBrcmVideoDecodeErrorConcealment,&conceal);
1149         if (error!=OMX_ErrorNone){
1150                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_IndexParamBrcmVideoDecodeErrorConcealment failed %x", error);
1151                 clock_mutex.Unlock();
1152                 DeAllocateCodecsOMX();
1153                 return 0;
1154         }
1155
1156         if (dodeint) {
1157                 error = OMX_GetHandle(&omx_vid_deint, L_VPE_OMX_VIDEO_DEINTERLACE, NULL,
1158                                 &callbacks);
1159                 if (error != OMX_ErrorNone) {
1160                         Log::getInstance()->log("Video", Log::DEBUG,
1161                                         "Init OMX video deinterlacer failed %x", error);
1162                         clock_mutex.Unlock();
1163                         DeAllocateCodecsOMX();
1164                         return 0;
1165                 }
1166
1167                 error = OMX_GetParameter(omx_vid_deint, OMX_IndexParamImageInit,
1168                                 &p_param);
1169                 if (error != OMX_ErrorNone) {
1170                         Log::getInstance()->log("Video", Log::DEBUG,
1171                                         "Init OMX video deinterlacer OMX_GetParameter failed %x",
1172                                         error);
1173                         clock_mutex.Unlock();
1174                         DeAllocateCodecsOMX();
1175                         return 0;
1176                 }
1177                 omx_deint_input_port = p_param.nStartPortNumber;
1178                 omx_deint_output_port = p_param.nStartPortNumber + 1;
1179
1180                 if (!DisablePort(omx_vid_deint, omx_deint_input_port, true)
1181                                 || !DisablePort(omx_vid_deint, omx_deint_output_port, true)) {
1182                         Log::getInstance()->log("Video", Log::DEBUG,
1183                                         "Disable Ports OMX video deint failed");
1184                         clock_mutex.Unlock();
1185                         DeAllocateCodecsOMX();
1186                         return 0;
1187                 }
1188
1189         }
1190
1191
1192         error=OMX_GetHandle(&omx_vid_sched,L_VPE_OMX_VIDEO_SCHED,NULL,&callbacks);
1193         if (error!=OMX_ErrorNone){
1194                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video scheduler failed %x", error);
1195                 clock_mutex.Unlock();
1196                 DeAllocateCodecsOMX();
1197                 return 0;
1198         }
1199
1200
1201
1202         error=OMX_GetParameter(omx_vid_sched,OMX_IndexParamVideoInit,&p_param);
1203         if (error!=OMX_ErrorNone){
1204                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video scheduler OMX_GetParameter failed %x", error);
1205                 clock_mutex.Unlock();
1206                 DeAllocateCodecsOMX();
1207                 return 0;
1208         }
1209         omx_shed_input_port=p_param.nStartPortNumber;
1210         omx_shed_output_port=p_param.nStartPortNumber+1;
1211
1212
1213         error=OMX_GetParameter(omx_vid_sched,OMX_IndexParamOtherInit,&p_param);
1214         if (error!=OMX_ErrorNone){
1215                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video scheduler OMX_GetParameter failed %x", error);
1216                 clock_mutex.Unlock();
1217                 DeAllocateCodecsOMX();
1218                 return 0;
1219         }
1220         omx_shed_clock_port=p_param.nStartPortNumber;
1221         Log::getInstance()->log("Video", Log::DEBUG, "scheduler ports %d %d %d ",omx_shed_input_port,omx_shed_output_port,omx_shed_clock_port);
1222
1223
1224         if (!DisablePort(omx_vid_sched,omx_shed_input_port,true) || !DisablePort(omx_vid_sched,omx_shed_output_port,true)
1225                         || !DisablePort(omx_vid_sched,omx_shed_clock_port,true)) {
1226                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX video shed failed");
1227                 clock_mutex.Unlock();
1228                 DeAllocateCodecsOMX();
1229                 return 0;
1230         }
1231
1232
1233         error=OMX_GetHandle(&omx_vid_rend,L_VPE_OMX_VIDEO_REND,NULL,&callbacks);
1234         if (error!=OMX_ErrorNone){
1235                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video rend failed %x", error);
1236                 clock_mutex.Unlock();
1237                 DeAllocateCodecsOMX();
1238                 return 0;
1239         }
1240
1241         error=OMX_GetParameter(omx_vid_rend,OMX_IndexParamVideoInit,&p_param);
1242         if (error!=OMX_ErrorNone){
1243                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video rend OMX_GetParameter failed %x", error);
1244                 clock_mutex.Unlock();
1245                 DeAllocateCodecsOMX();
1246                 return 0;
1247         }
1248         omx_rend_input_port=p_param.nStartPortNumber;
1249         //omx_rend_output_port=p_param.nStartPortNumber+1;
1250
1251
1252         if (!DisablePort(omx_vid_rend,omx_rend_input_port,true) /*|| !DisablePort(omx_vid_rend,omx_rend_output_port)*/
1253                                 ) {
1254                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX video rend failed");
1255                 clock_mutex.Unlock();
1256                 DeAllocateCodecsOMX();
1257                 return 0;
1258         }
1259
1260         //Setuo chain
1261
1262
1263
1264         error=OMX_SetupTunnel(omx_clock,omx_clock_output_port,omx_vid_sched,omx_shed_clock_port);
1265         if (error!=OMX_ErrorNone){
1266                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel clock to sched failed %x %d %d", error,omx_clock_output_port,omx_shed_clock_port);
1267                 clock_mutex.Unlock();
1268                 DeAllocateCodecsOMX();
1269                 return 0;
1270         }
1271
1272         if (!EnablePort(omx_clock,omx_clock_output_port,false) || !EnablePort(omx_vid_sched,omx_shed_clock_port,false)
1273                                         ) {
1274                 Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX clock shed failed");
1275                 clock_mutex.Unlock();
1276                 DeAllocateCodecsOMX();
1277                 return 0;
1278         }
1279
1280
1281
1282         if (!ChangeComponentState(omx_vid_sched,OMX_StateIdle)) {
1283                 Log::getInstance()->log("Video", Log::DEBUG, "vid_sched idle ChangeComponentState");
1284                 clock_mutex.Unlock();
1285                 DeAllocateCodecsOMX();
1286                 return 0;
1287         }
1288
1289
1290
1291
1292         if ( !CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_clock_port)) {
1293                 clock_mutex.Unlock();
1294                 DeAllocateCodecsOMX();
1295                 return 0;
1296         }
1297
1298
1299
1300
1301
1302         if ( !CommandFinished(omx_clock,OMX_CommandPortEnable,omx_clock_output_port)) {
1303                 clock_mutex.Unlock();
1304                 DeAllocateCodecsOMX();
1305                 return 0;
1306         }
1307
1308
1309
1310 /*      error=OMX_SendCommand(omx_vid_dec,OMX_CommandStateSet,OMX_StateIdle,0);
1311         if (error!=OMX_ErrorNone){
1312                 Log::getInstance()->log("Video", Log::DEBUG, "vid_dec Send Command to OMX State Idle %x", error);
1313                 return 0;
1314         }*/
1315
1316         OMX_VIDEO_PARAM_PORTFORMATTYPE ft_type;
1317         memset(&ft_type,0,sizeof(ft_type));
1318         ft_type.nSize=sizeof(ft_type);
1319         ft_type.nVersion.nVersion=OMX_VERSION;
1320
1321         ft_type.nPortIndex=omx_codec_input_port;
1322         if (h264) {
1323                 ft_type.eCompressionFormat=OMX_VIDEO_CodingAVC;
1324         } else {
1325                 ft_type.eCompressionFormat=OMX_VIDEO_CodingMPEG2;
1326         }
1327
1328
1329
1330     ft_type.xFramerate=0*(1<<16);//25*(1<<16);//demux->getFrameRate()*(1<<16);
1331     Log::getInstance()->log("Video", Log::DEBUG, "Framerate: %d",demux->getFrameRate());
1332         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamVideoPortFormat,&ft_type);
1333         if (error!=OMX_ErrorNone){
1334                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexParamVideoPortFormat failed %x", error);
1335                 clock_mutex.Unlock();
1336                 DeAllocateCodecsOMX();
1337                 return 0;
1338         }
1339
1340
1341         if (!ChangeComponentState(omx_vid_dec,OMX_StateIdle)) {
1342                 Log::getInstance()->log("Video", Log::DEBUG, "vid_dec ChangeComponentState");
1343                 clock_mutex.Unlock();
1344                 DeAllocateCodecsOMX();
1345                 return 0;
1346         }
1347
1348         OMX_CONFIG_BUFFERSTALLTYPE stall_conf;
1349         memset(&stall_conf,0,sizeof(stall_conf));
1350         stall_conf.nSize=sizeof(stall_conf);
1351         stall_conf.nVersion.nVersion=OMX_VERSION;
1352         stall_conf.nPortIndex=omx_codec_output_port;
1353         stall_conf.nDelay=1500*1000;
1354         error=OMX_SetConfig(omx_vid_dec,OMX_IndexConfigBufferStall,&stall_conf);
1355         if (error!=OMX_ErrorNone){
1356                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigBufferStall failed %x", error);
1357                 clock_mutex.Unlock();
1358                 DeAllocateCodecsOMX();
1359                 return 0;
1360         }
1361         omx_vid_stalled = false;
1362
1363         OMX_CONFIG_REQUESTCALLBACKTYPE req_callback;
1364         memset(&req_callback,0,sizeof(req_callback));
1365         req_callback.nSize=sizeof(req_callback);
1366         req_callback.nVersion.nVersion=OMX_VERSION;
1367         req_callback.nPortIndex=omx_codec_output_port;
1368         req_callback.nIndex=OMX_IndexConfigBufferStall;
1369         req_callback.bEnable=OMX_TRUE;
1370         error=OMX_SetConfig(omx_vid_dec,OMX_IndexConfigRequestCallback,&req_callback);
1371         if (error!=OMX_ErrorNone){
1372                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigRequestCallback  failed %x", error);
1373                 clock_mutex.Unlock();
1374                 DeAllocateCodecsOMX();
1375                 return 0;
1376         }
1377
1378
1379
1380         if (!PrepareInputBufsOMX()) {
1381                 clock_mutex.Unlock();
1382                 DeAllocateCodecsOMX();
1383                 return 0;
1384         }
1385
1386         if (!dodeint) {
1387                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,omx_vid_sched,omx_shed_input_port);
1388                 if (error!=OMX_ErrorNone){
1389                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel dec to sched failed %x", error);
1390                         clock_mutex.Unlock();
1391                         DeAllocateCodecsOMX();
1392                         return 0;
1393                 }
1394
1395
1396
1397                 if (!EnablePort(omx_vid_dec,omx_codec_output_port,false) || !EnablePort(omx_vid_sched,omx_shed_input_port,false)
1398                 ) {
1399                         Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX codec shed failed");
1400                         clock_mutex.Unlock();
1401                         DeAllocateCodecsOMX();
1402                         return 0;
1403                 }
1404
1405                 if ( !CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_output_port) || !CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_input_port)) {
1406                         clock_mutex.Unlock();
1407                         DeAllocateCodecsOMX();
1408                         return 0;
1409                 }
1410
1411         } else {
1412
1413                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,omx_vid_deint,omx_deint_input_port);
1414                 if (error!=OMX_ErrorNone){
1415                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel dec to deint failed %x", error);
1416                         clock_mutex.Unlock();
1417                         DeAllocateCodecsOMX();
1418                         return 0;
1419                 }
1420
1421
1422
1423                 if (!EnablePort(omx_vid_dec,omx_codec_output_port,false) || !EnablePort(omx_vid_deint,omx_deint_input_port,false)
1424                 ) {
1425                         Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX codec deint failed");
1426                         clock_mutex.Unlock();
1427                         DeAllocateCodecsOMX();
1428                         return 0;
1429                 }
1430
1431                 if ( !CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_output_port) || !CommandFinished(omx_vid_deint,OMX_CommandPortEnable,omx_deint_input_port)) {
1432                         clock_mutex.Unlock();
1433                         DeAllocateCodecsOMX();
1434                         return 0;
1435                 }
1436
1437                 if (!ChangeComponentState(omx_vid_deint,OMX_StateIdle)) {
1438                         Log::getInstance()->log("Video", Log::DEBUG, "vid_deint ChangeComponentState");
1439                         clock_mutex.Unlock();
1440                         DeAllocateCodecsOMX();
1441                         return 0;
1442                 }
1443
1444                 OMX_CONFIG_IMAGEFILTERPARAMSTYPE imagefilter;
1445                 memset(&imagefilter,0,sizeof(imagefilter));
1446                 imagefilter.nSize=sizeof(imagefilter);
1447                 imagefilter.nVersion.nVersion=OMX_VERSION;
1448
1449                 imagefilter.nPortIndex=omx_deint_output_port;
1450                 imagefilter.nNumParams=4;
1451                 imagefilter.nParams[0]=3;//???
1452                 imagefilter.nParams[1]=0;//default frame interval
1453                 imagefilter.nParams[2]=0;// frame rate
1454                 if (demux->getHorizontalSize() <= 720){
1455                         imagefilter.nParams[3] = 1;//use qpus
1456                 }
1457                 else 
1458                 {
1459                         imagefilter.nParams[3] = 0;//use qpus
1460                 }
1461
1462                 switch (deinterlace) {
1463                 case 1:
1464                         imagefilter.eImageFilter=OMX_ImageFilterDeInterlaceLineDouble; break;
1465                 case 2:
1466                         imagefilter.eImageFilter=OMX_ImageFilterDeInterlaceAdvanced; break;
1467                 case 3:
1468                         imagefilter.eImageFilter=OMX_ImageFilterFilm; break;
1469                 case 4:
1470                         imagefilter.eImageFilter = OMX_ImageFilterDeInterlaceFast; break;
1471                 }
1472
1473
1474                 error=OMX_SetConfig(omx_vid_deint,OMX_IndexConfigCommonImageFilterParameters,&imagefilter);
1475                 if (error!=OMX_ErrorNone){
1476                         Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigCommonImageFilterParameters failed %x", error);
1477                         clock_mutex.Unlock();
1478                         DeAllocateCodecsOMX();
1479                         return 0;
1480                 }
1481
1482
1483                 error=OMX_SetupTunnel(omx_vid_deint,omx_deint_output_port,omx_vid_sched,omx_shed_input_port);
1484                 if (error!=OMX_ErrorNone){
1485                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel deint to sched failed %x", error);
1486                         clock_mutex.Unlock();
1487                         DeAllocateCodecsOMX();
1488                         return 0;
1489                 }
1490
1491                 if (!EnablePort(omx_vid_deint,omx_deint_output_port,false) || !EnablePort(omx_vid_sched,omx_shed_input_port,false)
1492                 ) {
1493                         Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX deint shed failed");
1494                         clock_mutex.Unlock();
1495                         DeAllocateCodecsOMX();
1496                         return 0;
1497                 }
1498
1499                 if ( !CommandFinished(omx_vid_deint,OMX_CommandPortEnable,omx_deint_output_port) || !CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_input_port)) {
1500                         clock_mutex.Unlock();
1501                         DeAllocateCodecsOMX();
1502                         return 0;
1503                 }
1504
1505         }
1506
1507         if (!ChangeComponentState(omx_vid_dec,OMX_StateExecuting)) {
1508                 Log::getInstance()->log("Video", Log::DEBUG, "omx_vid_dec ChangeComponentState Execute");
1509                 clock_mutex.Unlock();
1510                 DeAllocateCodecsOMX();
1511                 return 0;
1512         }
1513
1514         error=OMX_SetupTunnel(omx_vid_sched,omx_shed_output_port,omx_vid_rend,omx_rend_input_port);
1515         if (error!=OMX_ErrorNone){
1516                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel  sched to rend failed %x", error);
1517                 clock_mutex.Unlock();
1518                 DeAllocateCodecsOMX();
1519                 return 0;
1520         }
1521
1522         if (!EnablePort(omx_vid_sched,omx_shed_output_port,false) || !EnablePort(omx_vid_rend,omx_rend_input_port,false)
1523                                                         ) {
1524                 Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX  shed rend failed");
1525                 clock_mutex.Unlock();
1526                 DeAllocateCodecsOMX();
1527                 return 0;
1528         }
1529
1530         if (!CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_output_port)
1531                                         || !CommandFinished(omx_vid_rend,OMX_CommandPortEnable,omx_rend_input_port)) {
1532                 clock_mutex.Unlock();
1533                 DeAllocateCodecsOMX();
1534                 return 0;
1535         }
1536
1537         if (!ChangeComponentState(omx_vid_rend,OMX_StateIdle)) {
1538                 Log::getInstance()->log("Video", Log::DEBUG, "vid_rend ChangeComponentState");
1539                 clock_mutex.Unlock();
1540                 DeAllocateCodecsOMX();
1541                 return 0;
1542         }
1543
1544         if (dodeint) {
1545                 if (!ChangeComponentState(omx_vid_deint,OMX_StateExecuting)) {
1546                         Log::getInstance()->log("Video", Log::DEBUG, "vid_vid_deint ChangeComponentState");
1547                         clock_mutex.Unlock();
1548                         DeAllocateCodecsOMX();
1549                         return 0;
1550                 }
1551                 DisablePort(omx_vid_deint,omx_deint_output_port,false);
1552                 DisablePort(omx_vid_deint,omx_deint_input_port,false);
1553         }
1554
1555         if (!ChangeComponentState(omx_vid_sched,OMX_StateExecuting)) {
1556                 Log::getInstance()->log("Video", Log::DEBUG, "omx_vid_sched ChangeComponentState Execute");
1557                 clock_mutex.Unlock();
1558                 DeAllocateCodecsOMX();
1559                 return 0;
1560         }
1561
1562         if (!ChangeComponentState(omx_vid_rend,OMX_StateExecuting)) {
1563                 Log::getInstance()->log("Video", Log::DEBUG, "omx_vid_rend ChangeComponentState Execute");
1564                 clock_mutex.Unlock();
1565                 DeAllocateCodecsOMX();
1566                 return 0;
1567         }
1568
1569         //raspbi specifif
1570         /*OMX_CONFIG_DISPLAYREGIONTYPE dispconf;
1571         memset(&dispconf,0,sizeof(dispconf));
1572         dispconf.nSize=sizeof(dispconf);
1573         dispconf.nVersion.nVersion=OMX_VERSION;
1574
1575         dispconf.nPortIndex=omx_rend_input_port;
1576
1577         dispconf.set=OMX_DISPLAY_SET_LAYER ;
1578         dispconf.layer=1;
1579         error=OMX_SetConfig(omx_vid_rend,OMX_IndexConfigDisplayRegion,&dispconf);
1580         if (error!=OMX_ErrorNone){
1581                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigDisplayRegion failed %x", error);
1582                 clock_mutex.Unlock();
1583                 DeAllocateCodecsOMX();
1584                 return 0;
1585         }*/
1586
1587 /*      dispconf.set=OMX_DISPLAY_SET_FULLSCREEN ;
1588         dispconf.fullscreen=OMX_FALSE;
1589         error=OMX_SetParameter(omx_vid_rend,OMX_IndexConfigDisplayRegion,&dispconf);
1590         if (error!=OMX_ErrorNone){
1591                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigDisplayRegion failed %x", error);
1592                 clock_mutex.Unlock();
1593                 DeAllocateCodecsOMX();
1594                 return 0;
1595         }
1596
1597         dispconf.set=OMX_DISPLAY_SET_DEST_RECT;
1598         dispconf.dest_rect.x_offset=100;
1599         dispconf.dest_rect.y_offset=100;
1600         dispconf.dest_rect.width=640;
1601         dispconf.dest_rect.height=480;
1602         error=OMX_SetParameter(omx_vid_rend,OMX_IndexConfigDisplayRegion,&dispconf);
1603         if (error!=OMX_ErrorNone){
1604                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigDisplayRegion failed %x", error);
1605                 clock_mutex.Unlock();
1606                 DeAllocateCodecsOMX();
1607                 return 0;
1608         }*/
1609
1610
1611         //playbacktimeoffset=-GetCurrentSystemTime();
1612
1613         iframemode=false;
1614         omx_running=true;
1615         clock_mutex.Unlock();
1616         clockUnpause();
1617         updateMode();
1618
1619         setClockExecutingandRunning();
1620
1621
1622
1623
1624
1625         return 1;
1626 }
1627
1628 int VideoOMX::idleClock()
1629 {
1630         //OMX_ERRORTYPE error;
1631         OMX_STATETYPE temp_state;
1632         clock_mutex.Lock();
1633         OMX_GetState(omx_clock,&temp_state);
1634
1635         if (temp_state!=OMX_StateIdle) {
1636                 if (!ChangeComponentState(omx_clock,OMX_StateIdle)) {
1637                         Log::getInstance()->log("Video", Log::DEBUG, "omx_clock ChangeComponentState Idle failed");
1638                         clock_mutex.Unlock();
1639                         return 0;
1640                 }
1641         }
1642         clock_mutex.Unlock();
1643         return 1;
1644 }
1645
1646 int VideoOMX::setClockExecutingandRunning()
1647 {
1648         OMX_ERRORTYPE error;
1649         OMX_STATETYPE temp_state;
1650         clock_mutex.Lock();
1651         OMX_GetState(omx_clock,&temp_state);
1652
1653         if (temp_state!=OMX_StateExecuting) {
1654                 if (!ChangeComponentState(omx_clock,OMX_StateExecuting)) {
1655                         Log::getInstance()->log("Video", Log::DEBUG, "omx_clock ChangeComponentState Execute failed");
1656                         clock_mutex.Unlock();
1657                         DeAllocateCodecsOMX();
1658                         return 0;
1659                 }
1660         }
1661
1662         OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
1663         memset(&clock_conf,0,sizeof(clock_conf));
1664         clock_conf.nSize=sizeof(clock_conf);
1665         clock_conf.nVersion.nVersion=OMX_VERSION;
1666         clock_conf.eState=OMX_TIME_ClockStateRunning;
1667         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
1668         if (error!=OMX_ErrorNone) {
1669                 Log::getInstance()->log("Video", Log::DEBUG, "Clock IndexConfigTimeClockState failed %x", error);
1670                 clock_mutex.Unlock();
1671                 DeAllocateCodecsOMX();
1672                 return 0;
1673         }
1674         clock_mutex.Unlock();
1675         return 1;
1676
1677 }
1678
1679
1680 int VideoOMX::ChangeComponentState(OMX_HANDLETYPE handle,OMX_STATETYPE type,bool wait) //needs to be called with locked mutex
1681 {
1682         OMX_ERRORTYPE error;
1683         error=OMX_SendCommand(handle,OMX_CommandStateSet,type,0);
1684         if (error!=OMX_ErrorNone){
1685                 Log::getInstance()->log("Video", Log::DEBUG, "handle %x Send Command to OMX State %x %x",handle,type, error);
1686                 return 0;
1687         }
1688
1689         if (wait) {
1690                 if (!CommandFinished(handle,OMX_CommandStateSet,type)) {
1691                         return 0;
1692                 }
1693         }
1694
1695         return 1;
1696 }
1697
1698
1699 int VideoOMX::EnablePort(OMX_HANDLETYPE handle,OMX_U32 port,bool wait) //needs to be called with locked mutex
1700 {
1701         OMX_ERRORTYPE error;
1702         bool skip=false;
1703
1704         OMX_PARAM_PORTDEFINITIONTYPE pdt;
1705         memset(&pdt,0,sizeof(pdt));
1706         pdt.nSize=sizeof(pdt);
1707         pdt.nVersion.nVersion=OMX_VERSION;
1708         pdt.nPortIndex=port;
1709         error=OMX_GetParameter(handle,OMX_IndexParamPortDefinition, &pdt);
1710         if (error==OMX_ErrorNone) {
1711                 if(pdt.bEnabled==OMX_TRUE) {
1712                         skip=true; //already disabled;
1713                 }
1714
1715         }
1716
1717         if (!skip) {
1718                 error=OMX_SendCommand(handle,OMX_CommandPortEnable,port,0);
1719                 if (error!=OMX_ErrorNone){
1720                         Log::getInstance()->log("Video", Log::DEBUG, "handle %x Send Command to enable port %x %x",handle,port, error);
1721                         return 0;
1722                 }
1723
1724                 if (!wait) return 1;
1725                 if (!CommandFinished(handle,OMX_CommandPortEnable,port)) {
1726                         return 0;
1727                 }
1728
1729         }
1730         return 1;
1731 }
1732
1733
1734 int VideoOMX::DisablePort(OMX_HANDLETYPE handle,OMX_U32 port,bool wait) //needs to be called with locked mutex
1735 {
1736         OMX_ERRORTYPE error;
1737         bool skip=false;
1738
1739         OMX_PARAM_PORTDEFINITIONTYPE pdt;
1740         memset(&pdt,0,sizeof(pdt));
1741         pdt.nSize=sizeof(pdt);
1742         pdt.nVersion.nVersion=OMX_VERSION;
1743         pdt.nPortIndex=port;
1744         error=OMX_GetParameter(handle,OMX_IndexParamPortDefinition, &pdt);
1745         if (error==OMX_ErrorNone) {
1746                 if(pdt.bEnabled==OMX_FALSE) {
1747                         skip=true; //already disabled;
1748                 }
1749
1750         }
1751
1752
1753         if (!skip) {
1754                 error=OMX_SendCommand(handle,OMX_CommandPortDisable,port,0);
1755                 if (error!=OMX_ErrorNone){
1756                         Log::getInstance()->log("Video", Log::DEBUG, "handle %x Send Command to disable port %x %x",handle,port, error);
1757                         return 0;
1758                 }
1759
1760                 if (!wait) return 1;
1761                 if (!CommandFinished(handle,OMX_CommandPortDisable,port)) {
1762                         return 0;
1763                 }
1764         }
1765
1766         return 1;
1767 }
1768
1769 int VideoOMX::WaitForEvent(OMX_HANDLETYPE handle,OMX_U32 event, int wait) //needs to be called with locked mutex
1770 {
1771         int i=0;
1772         int iend=(wait/5+1);
1773         while (i<iend) {
1774                 omx_event_mutex.Lock();
1775                 std::list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1776                 while (itty!=omx_events.end()) {
1777
1778                         VPE_OMX_EVENT current=*itty;
1779                         if (current.handle==handle) { //this is ours
1780                                 if (current.event_type==OMX_EventError) {
1781                                         omx_events.erase(itty);
1782                                         omx_event_mutex.Unlock();
1783                                         Log::getInstance()->log("Video", Log::DEBUG, "WaitForEvent Finished on Error");
1784                                         return 0;
1785
1786                                 } else if (current.event_type==event) {
1787                                         omx_events.erase(itty);
1788                                         omx_event_mutex.Unlock();
1789                                         Log::getInstance()->log("Video", Log::DEBUG, "WaitForEvent Finished Completed");
1790                                         return 1;
1791                                 }
1792                         }
1793                         itty++;
1794
1795                 }
1796                 omx_event_mutex.Unlock();
1797                 omx_event_ready_signal.waitForSignalTimed(10);
1798                 //MILLISLEEP(2);
1799                 i++;
1800
1801         }
1802         Log::getInstance()->log("Video", Log::DEBUG, "WaitForEvent waited too long %x %x",handle,event);
1803         return 0;
1804
1805 }
1806
1807 int VideoOMX::clearEvents()
1808 {
1809         omx_event_mutex.Lock();
1810         omx_events.clear();
1811         omx_event_mutex.Unlock();
1812
1813         return 1;
1814 }
1815
1816 int VideoOMX::clearEventsForComponent(OMX_HANDLETYPE handle)
1817 {
1818         omx_event_mutex.Lock();
1819         std::list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1820         while (itty!=omx_events.end()) {
1821                 VPE_OMX_EVENT current=*itty;
1822                 if (current.handle==handle) { //this is ours
1823                         itty=omx_events.erase(itty);
1824                         continue;
1825                 }
1826                 itty++;
1827
1828         }
1829         omx_event_mutex.Unlock();
1830         return 1;
1831 }
1832
1833 void VideoOMX::checkForStalledBuffers()
1834 {
1835         //Log::getInstance()->log("Video", Log::DEBUG, "Check stalled");
1836         clock_mutex.Lock();
1837         omx_event_mutex.Lock();
1838         std::list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1839         while (itty!=omx_events.end()) {
1840                 VPE_OMX_EVENT current=*itty;
1841                 if (current.event_type==OMX_EventParamOrConfigChanged && current.data1==omx_codec_output_port
1842                                 && current.handle==omx_vid_dec && current.data2==OMX_IndexConfigBufferStall) {
1843                         OMX_ERRORTYPE error;
1844                         OMX_CONFIG_BUFFERSTALLTYPE stall_conf;
1845                         memset(&stall_conf,0,sizeof(stall_conf));
1846                         stall_conf.nSize=sizeof(stall_conf);
1847                         stall_conf.nVersion.nVersion=OMX_VERSION;
1848                         stall_conf.nPortIndex=omx_codec_output_port;
1849                         stall_conf.nDelay=200000;
1850
1851                         error=OMX_GetConfig(omx_vid_dec,OMX_IndexConfigBufferStall,&stall_conf);
1852                         if (error!=OMX_ErrorNone){
1853                                         Log::getInstance()->log("Video", Log::DEBUG, "Get OMX_IndexConfigBufferStall failed %x", error);
1854                                         clock_mutex.Unlock();
1855                                         omx_event_mutex.Unlock();
1856                                         return ;
1857                                 }
1858                         if (stall_conf.bStalled==OMX_TRUE) {
1859                                 omx_vid_stalled=true;
1860                                 Log::getInstance()->log("Video", Log::DEBUG, "Video decoder stalled! %d", stall_conf.nDelay);
1861                         } else {
1862                                 omx_vid_stalled=false;
1863                                 Log::getInstance()->log("Video", Log::DEBUG, "Video decoder unstalled! %d",stall_conf.nDelay);
1864                         }
1865                         omx_events.erase(itty);
1866                         break;
1867                 }
1868                 itty++;
1869         }
1870         omx_event_mutex.Unlock();
1871         clock_mutex.Unlock();
1872 }
1873
1874
1875
1876
1877 int VideoOMX::CommandFinished(OMX_HANDLETYPE handle,OMX_U32 command,OMX_U32 data2) //needs to be called with locked mutex
1878 {
1879         int i=0;
1880         while (i<200/*1000*/) {
1881                 omx_event_mutex.Lock();
1882                 std::list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1883                 while (itty!=omx_events.end()) {
1884
1885                         VPE_OMX_EVENT current=*itty;
1886                         if (current.handle==handle) { //this is ours
1887                                 if (current.event_type==OMX_EventError) {
1888                                         omx_events.erase(itty);
1889                                         omx_event_mutex.Unlock();
1890                                         Log::getInstance()->log("Video", Log::DEBUG, "Command Finished on Error %x",current.data1);
1891                                         return 0;
1892
1893                                 } else if (current.event_type==OMX_EventCmdComplete && current.data1==command && current.data2==data2) {
1894                                         omx_events.erase(itty);
1895                                         omx_event_mutex.Unlock();
1896                                         //Log::getInstance()->log("Video", Log::DEBUG, "Command Finished Completed");
1897                                         return 1;
1898                                 }
1899                         }
1900                         itty++;
1901
1902                 }
1903                 omx_event_mutex.Unlock();
1904                 omx_event_ready_signal.waitForSignalTimed(10);
1905                 //MILLISLEEP(2);
1906                 i++;
1907
1908         }
1909         Log::getInstance()->log("Video", Log::DEBUG, "CommandFinished waited too long %x %x %x",handle,command, data2);
1910         return 0;
1911
1912 }
1913
1914
1915
1916 int VideoOMX::PrepareInputBufsOMX() //needs to be called with locked mutex
1917 {
1918         OMX_ERRORTYPE error;
1919         OMX_PARAM_PORTDEFINITIONTYPE port_def_type;
1920         memset(&port_def_type,0,sizeof(port_def_type));
1921         port_def_type.nSize=sizeof(port_def_type);
1922         port_def_type.nVersion.nVersion=OMX_VERSION;
1923         port_def_type.nPortIndex=omx_codec_input_port;
1924
1925         error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
1926
1927         if (error!=OMX_ErrorNone){
1928                         Log::getInstance()->log("Video", Log::DEBUG, "Get OMX OMX_IndexParamPortDefinition failed %x", error);
1929         }
1930 /*      Log::getInstance()->log("Video", Log::DEBUG, "Port para %d %d %d %d %d %d %d", port_def_type.nBufferCountActual,
1931                         port_def_type.nBufferCountMin,port_def_type.nBufferSize,port_def_type.bEnabled,port_def_type.bPopulated,
1932                         port_def_type.bBuffersContiguous,port_def_type.nBufferAlignment);*/
1933
1934         port_def_type.nBufferCountActual=100;
1935         port_def_type.nBufferSize=max(port_def_type.nBufferSize,150000); // for transcoder important
1936
1937         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
1938
1939         if (error!=OMX_ErrorNone){
1940                         Log::getInstance()->log("Video", Log::DEBUG, "Set OMX OMX_IndexParamPortDefinition failed %x", error);
1941         }
1942
1943
1944         error=OMX_SendCommand(omx_vid_dec,OMX_CommandPortEnable,omx_codec_input_port,0);
1945         if (error!=OMX_ErrorNone){
1946                 Log::getInstance()->log("Video", Log::DEBUG, "Prepare Input bufs Send Command to enable port %x", error);
1947                 return 0;
1948         }
1949
1950         input_bufs_omx_mutex.Lock();
1951         for (unsigned int i=0; i< port_def_type.nBufferCountActual;i++) {
1952
1953         //      unsigned char* new_buffer_data=(unsigned char*)malloc(port_def_type.nbufferSize);
1954                 OMX_BUFFERHEADERTYPE *buf_head=NULL;
1955         /*      error=OMX_Usebuffer(omx_vid_dec,&buf_head,omx_codec_input_port,NULL,port_def_type.nbufferSize,new_buffer_data);
1956                 if (error!=OMX_ErrorNone){
1957                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_Usebuffer failed %x", error);
1958                         input_bufs_omx_mutex.Unlock();
1959                         return 0;
1960                 }*/
1961                 error=OMX_AllocateBuffer(omx_vid_dec,&buf_head,omx_codec_input_port,NULL,port_def_type.nBufferSize);
1962                 if (error!=OMX_ErrorNone){
1963                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_AllocateBuffer failed %x", error);
1964                                 input_bufs_omx_mutex.Unlock();
1965                         return 0;
1966                 }
1967                 input_bufs_omx_all.push_back(buf_head);
1968                 input_bufs_omx_free.push_back(buf_head);
1969         }
1970         omx_first_frame=true;
1971
1972         firstsynched=false;
1973         cur_input_buf_omx=NULL;
1974         input_bufs_omx_mutex.Unlock();
1975
1976
1977         Log::getInstance()->log("Video", Log::DEBUG, "PrepareInputBufsOMX mark3");
1978         if (!CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_input_port)) {
1979                 return 0;
1980         }
1981         Log::getInstance()->log("Video", Log::DEBUG, "PrepareInputBufsOMX mark4");
1982
1983         return 1;
1984 }
1985
1986 int VideoOMX::DestroyInputBufsOMX() //need s to be called with locked mutex
1987 {
1988         OMX_ERRORTYPE error;
1989
1990         cur_input_buf_omx=NULL;
1991         input_bufs_omx_mutex.Lock();
1992         for (UINT i=0; i< input_bufs_omx_all.size();i++) {
1993         //      free(input_bufs_omx_all[i]->pBuffer);
1994         //      input_bufs_omx_all[i]->pBuffer=NULL;
1995                 error=OMX_FreeBuffer(omx_vid_dec,omx_codec_input_port,input_bufs_omx_all[i]);
1996                 if (error!=OMX_ErrorNone){
1997                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_FreeBuffer failed %x", error);
1998                         input_bufs_omx_mutex.Unlock();
1999                         return 0;
2000                 }
2001
2002         }
2003         input_bufs_omx_all.clear();
2004         input_bufs_omx_free.clear();
2005         input_bufs_omx_mutex.Unlock();
2006
2007         return 1;
2008 }
2009
2010
2011
2012 int VideoOMX::FlushRenderingPipe()
2013 {
2014         OMX_ERRORTYPE error;
2015
2016         if (!dodeint) {
2017
2018                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
2019                                 omx_codec_output_port, NULL);
2020                 if (error != OMX_ErrorNone) {
2021                         Log::getInstance()->log("Video", Log::DEBUG,
2022                                         "OMX_Flush codec out 1 failed %x", error);
2023
2024                 }
2025
2026                 error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
2027                                 omx_shed_input_port, NULL);
2028                 if (error != OMX_ErrorNone) {
2029                         Log::getInstance()->log("Video", Log::DEBUG,
2030                                         "OMX_Flush shed in 2 failed %x", error);
2031
2032                 }
2033
2034                 if (!CommandFinished(omx_vid_dec, OMX_CommandFlush,
2035                                 omx_codec_output_port)) {
2036                         Log::getInstance()->log("Video", Log::DEBUG,
2037                                         "flush cmd codec  3 failed");
2038                 }
2039
2040                 if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
2041                                 omx_shed_input_port)) {
2042                         Log::getInstance()->log("Video", Log::DEBUG,
2043                                         "flush cmd  shed 4 failed");
2044                 }
2045         } else {
2046                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
2047                                 omx_codec_output_port, NULL);
2048                 if (error != OMX_ErrorNone) {
2049                         Log::getInstance()->log("Video", Log::DEBUG,
2050                                         "OMX_Flush codec out 5 failed %x", error);
2051
2052                 }
2053
2054                 error = OMX_SendCommand(omx_vid_deint, OMX_CommandFlush,
2055                                 omx_deint_input_port, NULL);
2056                 if (error != OMX_ErrorNone) {
2057                         Log::getInstance()->log("Video", Log::DEBUG,
2058                                         "OMX_Flush deint in 6 failed %x", error);
2059
2060                 }
2061
2062                 if (!CommandFinished(omx_vid_dec, OMX_CommandFlush,
2063                                 omx_codec_output_port)) {
2064                         Log::getInstance()->log("Video", Log::DEBUG,
2065                                         "flush cmd codec  7 failed");
2066                 }
2067
2068                 if (!CommandFinished(omx_vid_deint, OMX_CommandFlush,
2069                                 omx_deint_input_port)) {
2070                         Log::getInstance()->log("Video", Log::DEBUG,
2071                                         "flush cmd  deint 8 failed");
2072                 }
2073
2074                 //m
2075                 error = OMX_SendCommand(omx_vid_deint, OMX_CommandFlush,
2076                                 omx_deint_output_port, NULL);
2077                 if (error != OMX_ErrorNone) {
2078                         Log::getInstance()->log("Video", Log::DEBUG,
2079                                         "OMX_Flush deint out 9 failed %x", error);
2080
2081                 }
2082
2083                 error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
2084                                 omx_shed_input_port, NULL);
2085                 if (error != OMX_ErrorNone) {
2086                         Log::getInstance()->log("Video", Log::DEBUG,
2087                                         "OMX_Flush shed in 10 failed %x", error);
2088
2089                 }
2090
2091                 if (!CommandFinished(omx_vid_deint, OMX_CommandFlush,
2092                                 omx_deint_output_port)) {
2093                         Log::getInstance()->log("Video", Log::DEBUG,
2094                                         "flush cmd deint 11 failed");
2095                 }
2096
2097                 if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
2098                                 omx_shed_input_port)) {
2099                         Log::getInstance()->log("Video", Log::DEBUG,
2100                                         "flush cmd  shed 12 failed");
2101                 }
2102
2103         }
2104
2105
2106
2107
2108         error = OMX_SendCommand(omx_vid_rend, OMX_CommandFlush,
2109                         omx_rend_input_port, NULL);
2110         if (error != OMX_ErrorNone) {
2111                 Log::getInstance()->log("Video", Log::DEBUG,
2112                                 "OMX_Flush rend in failed %x", error);
2113
2114         }
2115
2116         error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
2117                         omx_shed_output_port, NULL);
2118         if (error != OMX_ErrorNone) {
2119                 Log::getInstance()->log("Video", Log::DEBUG,
2120                                 "OMX_Flush shed out failed %x", error);
2121
2122         }
2123
2124
2125
2126         if (!CommandFinished(omx_vid_rend, OMX_CommandFlush,
2127                         omx_rend_input_port)) {
2128                 Log::getInstance()->log("Video", Log::DEBUG,
2129                                 "flush cmd shed rend failed");
2130         }
2131
2132         if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
2133                         omx_shed_output_port)) {
2134                 Log::getInstance()->log("Video", Log::DEBUG,
2135                                 "flush cmd shed rend failed");
2136         }
2137
2138         return 1;
2139 }
2140
2141
2142 int VideoOMX::DeAllocateCodecsOMX()
2143 {
2144         OMX_ERRORTYPE error;
2145         omx_running=false;
2146           Log::getInstance()->log("Video", Log::DEBUG, "enter deallocatecodecsomx");
2147
2148    if (cur_input_buf_omx) {
2149                 cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_EOS;
2150                 error=ProtOMXEmptyThisBuffer(omx_vid_dec,cur_input_buf_omx);
2151                 if (error!=OMX_ErrorNone) {
2152                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_EmptyThisBuffer failed %x", error);
2153                 }
2154
2155                 cur_input_buf_omx=NULL;//write out old data
2156         }
2157    clock_mutex.Lock();
2158    clearEvents();
2159         if (omx_vid_dec) {
2160                 // first stop the omx elements
2161                 if (!ChangeComponentState(omx_vid_dec,OMX_StateIdle)) {
2162                         Log::getInstance()->log("Video", Log::DEBUG, "vid_dec ChangeComponentState");
2163
2164                 }
2165                 clock_mutex.Unlock();
2166
2167                 idleClock();
2168                 clock_mutex.Lock();
2169
2170                 if (dodeint) {
2171                         if (!ChangeComponentState(omx_vid_deint, OMX_StateIdle)) {
2172                                 Log::getInstance()->log("Video", Log::DEBUG,
2173                                                 "vid_deint ChangeComponentState");
2174
2175                         }
2176                 }
2177
2178
2179                 if (!ChangeComponentState(omx_vid_sched,OMX_StateIdle)) {
2180                         Log::getInstance()->log("Video", Log::DEBUG, "vid_shed ChangeComponentState");
2181
2182                 }
2183
2184                 if (!ChangeComponentState(omx_vid_rend,OMX_StateIdle)) {
2185                         Log::getInstance()->log("Video", Log::DEBUG, "vid_rend ChangeComponentState");
2186
2187                 }
2188
2189
2190
2191         // TODO proper deinit sequence
2192                 // first flush all buffers
2193                 FlushRenderingPipe();
2194
2195
2196
2197
2198
2199                 error=OMX_SendCommand(omx_clock,OMX_CommandFlush, omx_clock_output_port, NULL);
2200                 if (error!=OMX_ErrorNone){
2201                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Flush clock out failed %x", error);
2202
2203                 }
2204
2205                 error=OMX_SendCommand(omx_vid_sched,OMX_CommandFlush, omx_shed_clock_port, NULL);
2206                 if (error!=OMX_ErrorNone){
2207                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Flush shed clock failed %x", error);
2208
2209                 }
2210
2211                 if (!CommandFinished(omx_clock,OMX_CommandFlush,omx_clock_output_port) ||
2212                         !CommandFinished(omx_vid_sched,OMX_CommandFlush,omx_shed_clock_port)) {
2213                                 Log::getInstance()->log("Video", Log::DEBUG, "flush cmd clock shed failed");
2214                 }
2215
2216
2217
2218
2219                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
2220                                 omx_codec_input_port, NULL);
2221                 if (error != OMX_ErrorNone) {
2222                         Log::getInstance()->log("Video", Log::DEBUG,
2223                                         "OMX_Flush codec out failed %x", error);
2224
2225                 }
2226
2227
2228
2229
2230                 DestroyInputBufsOMX();
2231
2232                 //todo flushing
2233                 if (!DisablePort(omx_vid_sched,omx_shed_output_port,true)) {
2234                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 2 ");
2235                 }
2236                 if (!DisablePort(omx_vid_rend,omx_rend_input_port,true)) {
2237                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 1");
2238                 }
2239
2240
2241
2242
2243                 if (!DisablePort(omx_vid_dec,omx_codec_output_port,true)) {
2244                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 6");
2245                 }
2246
2247
2248
2249                 if (!DisablePort(omx_vid_dec,omx_codec_input_port,true)) {
2250                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 7");
2251                 }
2252
2253                 if (dodeint) {
2254                         if (!DisablePort(omx_vid_deint,omx_deint_output_port,true)) {
2255                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 6a");
2256                         }
2257
2258
2259
2260                         if (!DisablePort(omx_vid_deint,omx_deint_input_port,true)) {
2261                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 7a");
2262                         }
2263                 }
2264
2265
2266
2267                 if (!DisablePort(omx_vid_sched,omx_shed_input_port,true)) {
2268                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 3");
2269                 }
2270
2271                 if (!DisablePort(omx_vid_sched,omx_shed_clock_port,true)) {
2272                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 4");
2273                 }
2274
2275                 if (!DisablePort(omx_clock,omx_clock_output_port,true)) {
2276                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 5");
2277                 }
2278
2279
2280
2281
2282                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,NULL,0);
2283                 if (error!=OMX_ErrorNone) {
2284                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2285
2286                 }
2287
2288                 if (dodeint) {
2289                         error=OMX_SetupTunnel(omx_vid_deint,omx_deint_input_port,NULL,0);
2290                         if (error!=OMX_ErrorNone) {
2291                                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2292                         }
2293
2294
2295                         error=OMX_SetupTunnel(omx_vid_deint,omx_deint_output_port,NULL,0);
2296                         if (error!=OMX_ErrorNone) {
2297                                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2298                         }
2299                 }
2300
2301                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_input_port,NULL,0);
2302                 if (error!=OMX_ErrorNone) {
2303                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2304
2305                 }
2306
2307
2308                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_output_port,NULL,0);
2309                 if (error!=OMX_ErrorNone) {
2310                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2311
2312                 }
2313
2314                 error=OMX_SetupTunnel(omx_vid_rend,omx_rend_input_port,NULL,0);
2315                 if (error!=OMX_ErrorNone) {
2316                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2317
2318                 }
2319
2320
2321                 error=OMX_SetupTunnel(omx_clock,omx_clock_output_port,NULL,0);
2322                 if (error!=OMX_ErrorNone) {
2323                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2324
2325                 }
2326
2327                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_clock_port,NULL,0);
2328                 if (error!=OMX_ErrorNone) {
2329                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2330
2331                 }
2332
2333
2334
2335
2336                 error=OMX_FreeHandle(omx_vid_dec);
2337                 error=OMX_FreeHandle(omx_vid_sched);
2338                 error=OMX_FreeHandle(omx_vid_rend);
2339                 if (dodeint) error=OMX_FreeHandle(omx_vid_deint);
2340                 omx_vid_dec=NULL;
2341                 clock_mutex.Unlock();
2342                 destroyClock();
2343                 if (error!=OMX_ErrorNone) {
2344                         Log::getInstance()->log("Video", Log::DEBUG, "FreeHandle failed %d", error);
2345                 }
2346         } else  clock_mutex.Unlock();
2347           Log::getInstance()->log("Video", Log::DEBUG, "leave deallocate codecs OMX");
2348
2349         return 1;
2350 }
2351
2352
2353 void VideoOMX::destroyClock()
2354 {
2355         clock_mutex.Lock();
2356         if (clock_references>0) {
2357                 clock_references--;
2358                 if (clock_references==0) {
2359                         OMX_ERRORTYPE error;
2360                         Log::getInstance()->log("Video", Log::DEBUG, "destroy omx clock");
2361                         error=OMX_FreeHandle(omx_clock);
2362                         if (error!=OMX_ErrorNone) {
2363                                 Log::getInstance()->log("Video", Log::DEBUG, "FreeHandle failed %d", error);
2364                         }
2365
2366                 }
2367         }
2368         clock_mutex.Unlock();
2369
2370 }
2371
2372 int VideoOMX::stop()
2373 {
2374   if (!initted) return 0;
2375   iframemode=false;
2376
2377   //Check if libav mode
2378   DeAllocateCodecsOMX();
2379
2380
2381
2382
2383 //  if (ioctl(fdVideo, AV_SET_VID_STOP, 0) != 0) return 0;
2384   return 1;
2385 }
2386
2387 int VideoOMX::reset()
2388 {
2389   if (!initted) return 0;
2390
2391   iframemode=false;
2392   DeAllocateCodecsOMX();
2393 //  if (ioctl(fdVideo, AV_SET_VID_RESET, 0x11) != 0) return 0;
2394   return 1;
2395 }
2396
2397 int VideoOMX::pause()
2398 {
2399   if (!initted) return 0;
2400   Log::getInstance()->log("Video", Log::DEBUG, "enter pause");
2401  // clockPause();
2402   // ignore it audio handles this
2403   return 1;
2404 }
2405
2406 int VideoOMX::unPause() // FIXME get rid - same as play!! Not here!
2407 {
2408   if (!initted) return 0;
2409   Log::getInstance()->log("Video", Log::DEBUG, "enter unpause");
2410
2411   //clockUnpause();
2412   //ignore it audio handles this
2413
2414   return 1;
2415 }
2416
2417 int VideoOMX::fastForward()
2418 {
2419   if (!initted) return 0;
2420
2421 //  if (ioctl(fdVideo, AV_SET_VID_libavWD, 1) != 0) return 0;
2422   return 1;
2423 }
2424
2425 int VideoOMX::unFastForward()
2426 {
2427   if (!initted) return 0;
2428
2429 //  if (ioctl(fdVideo, AV_SET_VID_RESET, 0x11) != 0) return 0; // don't need this.
2430
2431  //// if (ioctl(fdVideo, AV_SET_VID_PLAY, 0) != 0) return 0;
2432   return 1;
2433 }
2434
2435 int VideoOMX::attachFrameBuffer()
2436 {
2437   if (!initted) return 0;
2438
2439 //  if (ioctl(fdVideo, AV_SET_VID_FB, 0) != 0) return 0;
2440   return 1;
2441 }
2442
2443 int VideoOMX::blank(void)
2444 {
2445 //  if (ioctl(fdVideo, AV_SET_VID_FB, 1) != 0) return 0;
2446 //  if (ioctl(fdVideo, AV_SET_VID_FB, 0) != 0) return 0;
2447   return 1;
2448 }
2449
2450 ULLONG VideoOMX::getCurrentTimestamp() {
2451         if (iframemode)
2452                 return 0;
2453         long long ncur_clock_time = cur_clock_time;
2454         if (omx_running) {
2455                 int oldcancelstate;
2456                 int oldcanceltype;
2457                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2458                 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2459                 clock_mutex.Lock();
2460                 OMX_ERRORTYPE error;
2461                 OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
2462                 memset(&clock_conf, 0, sizeof(clock_conf));
2463                 clock_conf.nSize = sizeof(clock_conf);
2464                 clock_conf.nVersion.nVersion = OMX_VERSION;
2465                 error= OMX_GetConfig(omx_clock, OMX_IndexConfigTimeClockState,
2466                                 &clock_conf);
2467                 if (error != OMX_ErrorNone) {
2468                         Log::getInstance()->log("Video", Log::DEBUG,"getCurrentTimestamp IndexConfigTimeClockState failed %x",error);
2469                 }
2470
2471                 if (clock_conf.eState == OMX_TIME_ClockStateRunning) {
2472
2473                         OMX_TIME_CONFIG_TIMESTAMPTYPE cur_time_stamp;
2474                         memset(&cur_time_stamp, 0, sizeof(cur_time_stamp));
2475                         cur_time_stamp.nSize = sizeof(cur_time_stamp);
2476                         cur_time_stamp.nVersion.nVersion = OMX_VERSION;
2477                         cur_time_stamp.nPortIndex = omx_clock_output_port;
2478                         error = OMX_GetConfig(omx_clock, OMX_IndexConfigTimeCurrentMediaTime,
2479                                         &cur_time_stamp);
2480                         if (error != OMX_ErrorNone) {
2481                                 Log::getInstance()->log("Video",Log::DEBUG,"getCurrentTimestamp OMX_IndexConfigTimeCurrentMediaTime failed %x",error);
2482                         } else {
2483                                 long long temp = cur_time_stamp.nTimestamp.nLowPart
2484                                                 | ((long long) cur_time_stamp.nTimestamp.nHighPart << 32);
2485                                 ncur_clock_time = cur_clock_time = temp * 10LL;
2486                         }
2487                 }
2488                 clock_mutex.Unlock();
2489                 pthread_setcancelstate(oldcancelstate, NULL);
2490                 pthread_setcanceltype(oldcanceltype, NULL);
2491         }
2492
2493         //ncur_clock_time -= startoffset;
2494         ncur_clock_time -= lastreftimeOMX;
2495         long long result = lastreftimePTS;
2496         if (lastreftimePTS==0) return 0; // invalid time
2497         result += (long long) (ncur_clock_time / 10000LL * 90LL);
2498         if (result < 0)
2499                 result = (1LL << 33) - result;
2500         //Log::getInstance()->log("Video", Log::DEBUG,"getCurrentTimestamp %lld %lld %lld %lld %lld %lld",ncur_clock_time,cur_clock_time,lastreftimeOMX,lastreftimePTS,result,startoffset);
2501
2502         return result;
2503
2504 }
2505
2506 // to be removed
2507 /*
2508 ULONG VideoOMX::timecodeToFrameNumber(ULLONG timecode)
2509 {
2510   if (format == PAL) return (ULONG)(((double)timecode / (double)90000) * (double)25);
2511   else               return (ULONG)(((double)timecode / (double)90000) * (double)30);
2512 }
2513
2514 */
2515 #ifdef DEV
2516 int VideoOMX::test()
2517 {
2518   return 0;
2519
2520 //  ULLONG stc = 0;
2521 //  return ioctl(fdVideo, AV_SET_VID_STC, &stc);
2522 /*
2523  // reset();
2524   return 1;
2525 */
2526 }
2527
2528 int VideoOMX::test2()
2529 {
2530   return 0;
2531 }
2532 #endif
2533
2534
2535
2536 long long VideoOMX::SetStartOffset(long long curreftime, bool *rsync)
2537 {
2538   *rsync=false;
2539   if (offsetnotset) {
2540     startoffset=curreftime;//offset is set for audio
2541     offsetnotset=false;
2542     offsetvideonotset=false;
2543   } else {
2544     if (offsetvideonotset) {
2545       offsetvideonotset=false;
2546       *rsync=true;
2547     } else {
2548       if ( (curreftime-lastrefvideotime)>10000000LL
2549         || (curreftime-lastrefvideotime)<-10000000LL) {//if pts jumps to big resync
2550         startoffset+=curreftime-lastrefvideotime;
2551         lastrefaudiotime+=curreftime-lastrefvideotime;
2552         //*rsync=true;
2553         offsetaudionotset=true;
2554
2555       }
2556     }
2557
2558   }
2559
2560   lastrefvideotime=curreftime;
2561
2562   return startoffset;
2563
2564 }
2565
2566 long long VideoOMX::SetStartAudioOffset(long long curreftime, bool *rsync)
2567 {
2568   *rsync=false;
2569   if (offsetnotset) {
2570     startoffset=curreftime;
2571     offsetnotset=false;
2572     offsetaudionotset=false;
2573   }else {
2574     if (offsetaudionotset) {
2575       offsetaudionotset=false;
2576       *rsync=true;
2577     } else {
2578       if ( (curreftime-lastrefaudiotime)>10000000LL
2579         || (curreftime-lastrefaudiotime)<-10000000LL) {//if pts jumps to big resync
2580         startoffset+=curreftime-lastrefaudiotime;
2581         lastrefvideotime+=curreftime-lastrefaudiotime;
2582         //*rsync=true;
2583         offsetvideonotset=true;
2584
2585       }
2586     }
2587
2588   }
2589   lastrefaudiotime=curreftime;
2590   return startoffset;
2591
2592 }
2593
2594 void VideoOMX::ResetTimeOffsets() {
2595   offsetnotset=true; //called from demuxer
2596   offsetvideonotset=true;
2597   offsetaudionotset=true;
2598   startoffset=0;
2599   lastrefaudiotime=0;
2600   lastrefvideotime=0;
2601   lastreftimeOMX=0;
2602   lastreftimePTS=0;
2603 }
2604
2605
2606 void VideoOMX::FirstFrameFix()
2607 {
2608         int oldcancelstate;
2609         int oldcanceltype;
2610         Demuxer* demux=Demuxer::getInstance();
2611         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2612         pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2613         clock_mutex.Lock();
2614         if (WaitForEvent(omx_vid_dec,OMX_EventPortSettingsChanged,0)){
2615                 WaitForEvent(omx_vid_deint,OMX_EventPortSettingsChanged,0); //clear old messages
2616                 OMX_ERRORTYPE error;
2617                 OMX_PARAM_PORTDEFINITIONTYPE port_def_type;
2618                 memset(&port_def_type,0,sizeof(port_def_type));
2619                 port_def_type.nSize=sizeof(port_def_type);
2620                 port_def_type.nVersion.nVersion=OMX_VERSION;
2621                 port_def_type.nPortIndex=omx_codec_output_port;
2622
2623                 error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
2624                 if (error != OMX_ErrorNone) {
2625                         Log::getInstance()->log("Video", Log::DEBUG,
2626                                         "OMX_IndexParamPortDefinition fix failed %x", error);
2627                         clock_mutex.Unlock();
2628                         return;
2629                 }
2630
2631
2632                 Log::getInstance()->log("Video", Log::DEBUG,
2633                                                         "Deinit first frame fix %d %d %d %d %d %d %d %d",port_def_type.format.video.nFrameWidth , demux->getHorizontalSize(),
2634                                                         port_def_type.format.video.nFrameHeight , demux->getVerticalSize(),port_def_type.format.video.nStride,
2635                                                         port_def_type.format.video.nSliceHeight, port_def_type.format.video.xFramerate,
2636                                                          port_def_type.format.video.bFlagErrorConcealment );
2637                 Log::getInstance()->log("Video", Log::DEBUG,
2638                                                                         "Deinit first frame fix2 %d  %d",
2639                                                                         port_def_type.format.video.eCompressionFormat ,
2640                                                                         port_def_type.format.video.eColorFormat );
2641                 first_frame=false;
2642
2643                 // we cause the video_decode to determine the interlacing properties
2644                 OMX_CONFIG_INTERLACETYPE il;
2645                 memset(&il,0,sizeof(il));
2646                 il.nSize=sizeof(il);
2647                 il.nVersion.nVersion=OMX_VERSION;
2648                 il.nPortIndex=omx_codec_output_port;
2649                 error=OMX_GetConfig(omx_vid_dec,OMX_IndexConfigCommonInterlace, &il);
2650                 if (error != OMX_ErrorNone) {
2651                         Log::getInstance()->log("Video", Log::DEBUG,
2652                                         "OMX_IndexConfigCommonInterlace fix failed %x", error);
2653                 }
2654
2655
2656                 DisablePort(omx_vid_dec,omx_codec_output_port,true);
2657                 DisablePort(omx_vid_sched,omx_shed_input_port,true);
2658                 if (dodeint) {
2659
2660                         DisablePort(omx_vid_deint,omx_deint_input_port,true);
2661                         // This is a dirty hack
2662                         DisablePort(omx_vid_deint,omx_deint_output_port,true);
2663
2664
2665                         port_def_type.nPortIndex=omx_deint_output_port;
2666                         error = OMX_SetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2667                                         &port_def_type);
2668                         if (error != OMX_ErrorNone) {
2669                                 Log::getInstance()->log("Video", Log::DEBUG,
2670                                                 "Set OMX_IndexParamPortDefinition1 failed %x", error);
2671                                 clock_mutex.Unlock();
2672                                 pthread_setcancelstate(oldcancelstate, NULL);
2673                                 pthread_setcanceltype(oldcanceltype, NULL);
2674                                 return;
2675                         }
2676                         // dirty hack end
2677
2678
2679                         port_def_type.nPortIndex=omx_deint_input_port;
2680                         error = OMX_SetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2681                                         &port_def_type);
2682                         if (error != OMX_ErrorNone) {
2683                                 Log::getInstance()->log("Video", Log::DEBUG,
2684                                                 "Set OMX_IndexParamPortDefinition1 failed %x", error);
2685                                 clock_mutex.Unlock();
2686                                 pthread_setcancelstate(oldcancelstate, NULL);
2687                                 pthread_setcanceltype(oldcanceltype, NULL);
2688                                 return;
2689                         }
2690                 //      WaitForEvent(omx_vid_dec,OMX_EventPortSettingsChanged);
2691
2692                         Log::getInstance()->log("Video", Log::DEBUG,
2693                                                                         "Marker");
2694                         EnablePort(omx_vid_deint,omx_deint_input_port,true);
2695                         WaitForEvent(omx_vid_deint,OMX_EventPortSettingsChanged);
2696                         port_def_type.nPortIndex=omx_deint_output_port;
2697                         error = OMX_GetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2698                                         &port_def_type);
2699                         if (error != OMX_ErrorNone) {
2700                                 Log::getInstance()->log("Video", Log::DEBUG,
2701                                                 "Get OMX_IndexParamPortDefinition2 failed %x", error);
2702                                 clock_mutex.Unlock();
2703                                 pthread_setcancelstate(oldcancelstate, NULL);
2704                                 pthread_setcanceltype(oldcanceltype, NULL);
2705                                 return;
2706                         }
2707                         Log::getInstance()->log("Video", Log::DEBUG,
2708                                         "Deinit first frame fix3 %d %d %d %d %d %d %d ",port_def_type.format.image.nFrameWidth , demux->getHorizontalSize(),
2709                                         port_def_type.format.image.nFrameHeight , demux->getVerticalSize(),port_def_type.format.image.nStride,
2710                                         port_def_type.format.image.nSliceHeight, /*port_def_type.format.image.xFramerate,*/
2711                                         port_def_type.format.image.bFlagErrorConcealment );
2712                         Log::getInstance()->log("Video", Log::DEBUG,
2713                                         "Deinit first frame fix4 %d  %d",
2714                                         port_def_type.format.image.eCompressionFormat ,
2715                                         port_def_type.format.image.eColorFormat );
2716                         DisablePort(omx_vid_deint,omx_deint_output_port,true);
2717
2718                 }
2719                 port_def_type.nPortIndex=omx_shed_input_port;
2720                 error = OMX_SetParameter(omx_vid_sched, OMX_IndexParamPortDefinition,
2721                                         &port_def_type);
2722                 if (error != OMX_ErrorNone) {
2723                         Log::getInstance()->log("Video", Log::DEBUG,
2724                                         "Set OMX_IndexParamPortDefinition3 failed %x", error);
2725                         clock_mutex.Unlock();
2726                         pthread_setcancelstate(oldcancelstate, NULL);
2727                         pthread_setcanceltype(oldcanceltype, NULL);
2728                         return;
2729                 }
2730                 WaitForEvent(omx_vid_sched,OMX_EventPortSettingsChanged);
2731
2732
2733                 if (dodeint) {
2734                         EnablePort(omx_vid_deint,omx_deint_output_port,true);
2735                 }
2736                 EnablePort(omx_vid_dec,omx_codec_output_port,true);
2737                 EnablePort(omx_vid_sched,omx_shed_input_port,true);
2738         }
2739         clock_mutex.Unlock();
2740         pthread_setcancelstate(oldcancelstate, NULL);
2741         pthread_setcanceltype(oldcanceltype, NULL);
2742
2743
2744
2745 }
2746
2747
2748 void VideoOMX::PutBufferToPres(OMX_BUFFERHEADERTYPE* buffer)
2749 {
2750
2751         OMX_ERRORTYPE error = ProtOMXEmptyThisBuffer(omx_vid_dec, buffer);
2752         if (error != OMX_ErrorNone) {
2753                 Log::getInstance()->log("Video", Log::DEBUG,
2754                                 "OMX_EmptyThisBuffer failed %x", error);
2755         }
2756         if (first_frame) FirstFrameFix();
2757
2758 }
2759
2760 OMX_ERRORTYPE VideoOMX::ProtOMXEmptyThisBuffer(OMX_HANDLETYPE handle, OMX_BUFFERHEADERTYPE* buffer)
2761 {
2762         // protect the call to empty this buffer
2763         int oldcancelstate;
2764         int oldcanceltype;
2765 /*      long long temp =buffer->nTimeStamp.nLowPart
2766                                                         | ((long long) buffer->nTimeStamp.nHighPart << 32);*/
2767
2768         //pthread_testcancel();
2769         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2770         pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2771         clock_mutex.Lock();
2772 // Diagnosis code
2773 /*      OMX_ERRORTYPE error;
2774         OMX_TIME_CONFIG_TIMESTAMPTYPE timestamp;
2775         memset(&timestamp, 0, sizeof(timestamp));
2776         timestamp.nSize = sizeof(timestamp);
2777         timestamp.nVersion.nVersion = OMX_VERSION;
2778         timestamp.nPortIndex =omx_clock_output_port;
2779
2780         error = OMX_GetConfig(omx_clock, OMX_IndexConfigTimeCurrentMediaTime,
2781                         &timestamp);
2782
2783         if (error != OMX_ErrorNone) {
2784                 Log::getInstance()->log("Audio", Log::DEBUG,
2785                                 "Init OMX_IndexConfigAudioRenderingLatencyfailed %x %d", error,
2786                                 omx_rend_input_port);
2787         }
2788         long long temp2 =timestamp.nTimestamp.nLowPart
2789                                                                 | ((long long) timestamp.nTimestamp.nHighPart << 32);
2790
2791
2792         Log::getInstance()->log("Video", Log::NOTICE, "OMXETB %x %lld %lld %x",handle,temp,temp2,buffer->nFlags);*/
2793         OMX_ERRORTYPE ret_val;
2794         ret_val=OMX_EmptyThisBuffer(handle,buffer);
2795         clock_mutex.Unlock();
2796         pthread_setcancelstate(oldcancelstate, NULL);
2797         pthread_setcanceltype(oldcanceltype, NULL);
2798         //pthread_testcancel();
2799         return ret_val;
2800 }
2801
2802 bool VideoOMX::detectIFrame(const UCHAR *buffer,unsigned int length)
2803 {
2804         const UCHAR* curbuf=buffer;
2805         const UCHAR* curbufend=buffer+length;
2806         unsigned int detector=0xFFFFFFFF;
2807         bool gotaud=false; // have seen access unit delimiter
2808
2809         while (curbuf!=curbufend) {
2810                 detector<<=8;
2811                 detector|=*curbuf;
2812                 if (h264) {
2813                         if (detector==0x00000109) {
2814                                 gotaud=true;
2815                                 detector=0xFFFFFFFF;
2816                         } else if (gotaud &&detector==0x00000001) {
2817                                 curbuf++;
2818                                 if (curbuf!=curbufend) {
2819                                         unsigned char picttype=(*curbuf)& 0x1F;
2820                                         return picttype==0x07;
2821                                 }
2822                         }
2823                 } else {
2824                         if (detector==0x00000100) {
2825                                 curbuf++;
2826                                 if (curbuf==curbufend) return false;
2827                                 curbuf++;
2828                                 if (curbuf==curbufend) return false;
2829                                 unsigned char picttype=((*curbuf) >> 3) & 0x07;
2830                                 return picttype==1;
2831                         }
2832                 }
2833                 curbuf++;
2834         }
2835
2836         return false; // no frame found
2837 }
2838
2839
2840
2841 bool VideoOMX::DrainTargetBufferFull()
2842 {
2843         //Check, if we have OMX output buffers
2844         bool full;
2845         input_bufs_omx_mutex.Lock();
2846         full=(input_bufs_omx_free.size()==0);
2847         input_bufs_omx_mutex.Unlock();
2848         checkForStalledBuffers(); // check if the decoder has a problem
2849         if (full && omx_vid_stalled && !omx_first_frame) {
2850                 omx_vid_stalled=false;
2851                 Log::getInstance()->log("Video", Log::DEBUG, "Decoder is stalled, do a reset!");
2852
2853                 int oldcancelstate;
2854                 int oldcanceltype;
2855                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2856                 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2857
2858                 clock_mutex.Lock();
2859                 FlushRenderingPipe();
2860                 omx_first_frame=true;
2861                 clock_mutex.Unlock();
2862
2863                 pthread_setcancelstate(oldcancelstate, NULL);
2864                 pthread_setcanceltype(oldcanceltype, NULL);
2865         }
2866         return full;
2867
2868 }
2869
2870 void VideoOMX::PrepareMediaSample(const MediaPacketList& mplist,UINT samplepos)
2871 {
2872
2873         mediapackets.clear();
2874         std::list<MediaPacket>::const_iterator begin=mplist.begin();
2875         std::list<MediaPacket>::const_iterator itty=mplist.begin();
2876         advance(itty,min(mplist.size(),10));
2877         mediapackets.insert(mediapackets.begin(),begin,itty);//front
2878
2879 }
2880
2881 UINT VideoOMX::DeliverMediaSample(UCHAR* buffer, UINT *samplepos)
2882 {
2883         int consumed=0;
2884         while (consumed < (int)mediapackets.size()) {
2885             DeliverMediaPacket(mediapackets[consumed], buffer, samplepos);
2886             if (*samplepos == mediapackets[consumed].length) {
2887                 *samplepos = 0;
2888                 consumed++;
2889                 //return 1;
2890             } else return consumed;
2891         }
2892         return consumed;
2893 }
2894
2895 UINT VideoOMX::DeliverMediaPacket(MediaPacket packet,
2896                 const UCHAR* buffer,
2897                 UINT *samplepos)
2898 {
2899         if (packet.type == MPTYPE_VIDEO_H264)
2900         {
2901                 h264=true;
2902         }
2903         else
2904         {
2905                 h264=false;
2906         }
2907
2908
2909         //Later add fail back code for libav
2910 /*      if (!videoon) {
2911                 *samplepos+=packet.length;
2912                 return packet.length;
2913         }*/
2914
2915
2916         if (!omx_running) return 0; // if we are not runnig do not do this
2917
2918         if (isClockPaused()) return 0; //Block if we pause
2919
2920 //      Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 1");
2921         //Log::getInstance()->log("Video", Log::DEBUG, "DeliverMediaPacketOMX time %lld",packet.presentation_time);
2922
2923
2924         /*First Check, if we have an video sample*/
2925         if (iframemode) {
2926                 //samplepos=0;
2927                 MILLISLEEP(10);
2928                 return 0; //Not in iframe mode!
2929         }
2930
2931         UINT headerstrip=0;
2932         if (packet.disconti) {
2933                 firstsynched=false;
2934                 if (cur_input_buf_omx) {
2935                         PutBufferToPres(cur_input_buf_omx);
2936                         cur_input_buf_omx=NULL;
2937                 }
2938         }
2939         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 2");
2940         /*Inspect PES-Header */
2941
2942 //      OMX_STATETYPE temp_state;
2943 //      OMX_GetState(omx_vid_dec,&temp_state);
2944
2945         if (*samplepos==0) {//stripheader
2946                 headerstrip=buffer[packet.pos_buffer+8]+9/*is this right*/;
2947         //      if (h264) Log::getInstance()->log("Video", Log::DEBUG, "PES info %x %x %x %x",
2948         //                      buffer[packet.pos_buffer+0],buffer[packet.pos_buffer+1],buffer[packet.pos_buffer+2],buffer[packet.pos_buffer+3]);
2949                 *samplepos+=headerstrip;
2950                 if (headerstrip>=packet.length) {
2951                      *samplepos=packet.length;// Packet is obviously damaged
2952                      return packet.length;//skip it!
2953                 }
2954                 if ( packet.synched ) {
2955                         if (!firstsynched) {
2956                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 2a");
2957                           // check if this is an I frame, the decoder does not like non I frames at startup!
2958                           if (!detectIFrame(buffer,packet.length)) {
2959                                   *samplepos=packet.length;//if we have not processed at least one
2960                                   //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 3");
2961                                   return packet.length;//synched packet ignore it!
2962                           }
2963                         }
2964                         if (cur_input_buf_omx) {
2965                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 4a");
2966                                 cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_ENDOFFRAME;
2967                                 PutBufferToPres(cur_input_buf_omx);
2968                                 cur_input_buf_omx=NULL;//write out old data
2969
2970                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 4b");
2971
2972                         }
2973                         firstsynched=true;
2974                 } else {
2975                         if (!firstsynched) {//
2976                                 *samplepos=packet.length;//if we have not processed at least one
2977                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 5");
2978                                 return packet.length;//synched packet ignore it!
2979                         }
2980                 }
2981         }
2982         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 6");
2983         if (!cur_input_buf_omx) {
2984                 input_bufs_omx_mutex.Lock();
2985                 if (input_bufs_omx_free.size()==0) {
2986                         input_bufs_omx_mutex.Unlock();
2987                         //Log::getInstance()->log("Video", Log::DEBUG, "Deliver MediaPacket no free sample");
2988                         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 7");
2989                         return 0; // we do not have a free media sample
2990
2991                 }
2992                 cur_input_buf_omx=input_bufs_omx_free.front();
2993                 cur_input_buf_omx->nFilledLen=0;
2994                 cur_input_buf_omx->nOffset=0;
2995                 cur_input_buf_omx->nTimeStamp=intToOMXTicks(0);
2996                 input_bufs_omx_free.pop_front();
2997                 input_bufs_omx_mutex.Unlock();
2998         }
2999
3000
3001
3002
3003         if (cur_input_buf_omx->nFilledLen==0) {//will only be changed on first packet
3004                 if (packet.synched) {
3005                 //      Log::getInstance()->log("Video", Log::DEBUG, "packet synched marker");
3006
3007                         //lastreftimePTS=packet.pts;
3008                    if (omx_first_frame) { // TODO time
3009                            cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_STARTTIME;
3010                            Log::getInstance()->log("Video", Log::DEBUG, "Starttime");
3011                            omx_first_frame=false;
3012                    } else {
3013                            cur_input_buf_omx->nFlags=0;
3014                            //cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_TIME_UNKNOWN;
3015                    }
3016                    lastreftimeOMX=packet.presentation_time;
3017                   // Log::getInstance()->log("Video", Log::DEBUG, "Time code %lld pts %lld", lastreftimeOMX,packet.pts);
3018                    lastreftimePTS=packet.pts;
3019                    cur_input_buf_omx->nTimeStamp=intToOMXTicks(lastreftimeOMX/10LL); // the clock component is faulty;
3020                 }
3021                 else
3022                 {
3023                         cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_TIME_UNKNOWN;
3024                         cur_input_buf_omx->nTimeStamp=intToOMXTicks(0);
3025                         //Log::getInstance()->log("Video", Log::DEBUG, "packet unsynched marker");
3026                 }
3027                 if (packet.disconti) cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_DISCONTINUITY;
3028
3029
3030
3031         }
3032         unsigned int haveToCopy=packet.length-*samplepos;
3033         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 8");
3034
3035         while (haveToCopy> (cur_input_buf_omx->nAllocLen-cur_input_buf_omx->nFilledLen)) {
3036                 //Log::getInstance()->log("Video", Log::DEBUG, "Big buffer %d %d %d",packet.length,cur_input_buf_omx->nAllocLen,cur_input_buf_omx->nFilledLen);
3037                 unsigned int cancopy=cur_input_buf_omx->nAllocLen-cur_input_buf_omx->nFilledLen;
3038                 memcpy(cur_input_buf_omx->pBuffer+cur_input_buf_omx->nFilledLen,buffer+packet.pos_buffer+*samplepos,cancopy);
3039                 haveToCopy-=cancopy;
3040                 cur_input_buf_omx->nFilledLen+=cancopy;
3041                 *samplepos+=cancopy;
3042                 // push old buffer out
3043                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 9");
3044
3045                 PutBufferToPres(cur_input_buf_omx);
3046                 cur_input_buf_omx=NULL;
3047                 // get5 new buffer
3048                 input_bufs_omx_mutex.Lock();
3049                 if (input_bufs_omx_free.size()==0) {
3050                         input_bufs_omx_mutex.Unlock();
3051                 //      Log::getInstance()->log("Video", Log::DEBUG, "Deliver MediaPacket no free sample2");
3052                         return *samplepos; // we do not have a free media sample
3053                 }
3054                 cur_input_buf_omx=input_bufs_omx_free.front();
3055                 cur_input_buf_omx->nFilledLen=0;
3056                 cur_input_buf_omx->nOffset=0;
3057                 cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_TIME_UNKNOWN;
3058                 cur_input_buf_omx->nTimeStamp=intToOMXTicks(0);
3059                 input_bufs_omx_free.pop_front();
3060                 input_bufs_omx_mutex.Unlock();
3061                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 10");
3062
3063         }
3064         memcpy(cur_input_buf_omx->pBuffer+cur_input_buf_omx->nFilledLen,
3065                         buffer+packet.pos_buffer+*samplepos,haveToCopy);
3066         cur_input_buf_omx->nFilledLen+=haveToCopy;
3067
3068 //      Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 11");
3069
3070         *samplepos+=haveToCopy;
3071
3072         return *samplepos;
3073
3074 }
3075
3076
3077
3078
3079 bool VideoOMX::displayIFrame(const UCHAR* buffer, UINT length) {
3080         if (!omx_running) return false;
3081         if (!iframemode)
3082                 EnterIframePlayback();
3083
3084         //int haveToCopy = length;
3085
3086         if (!cur_input_buf_omx) {
3087                 input_bufs_omx_mutex.Lock();
3088                 if (input_bufs_omx_free.size() == 0) {
3089                         input_bufs_omx_mutex.Unlock();
3090                 //      Log::getInstance()->log("Video", Log::DEBUG,
3091                         //              "Deliver MediaPacket no free sample");
3092                         return false; // we do not have a free media sample
3093
3094                 }
3095                 cur_input_buf_omx = input_bufs_omx_free.front();
3096                 cur_input_buf_omx->nFilledLen = 0;
3097                 cur_input_buf_omx->nOffset = 0;
3098                 cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3099                 input_bufs_omx_free.pop_front();
3100                 input_bufs_omx_mutex.Unlock();
3101         }
3102
3103         int read_pos = 0;
3104         unsigned int pattern, packet_length;
3105         unsigned int headerstrip = 0;
3106         bool first = true;
3107         if (length < 4){
3108                 return false;
3109         }
3110         //Now we strip the pes header
3111         pattern = (buffer[0] << 16) | (buffer[1] << 8) | (buffer[2]);
3112         while ((read_pos + 7) <= (int)length) {
3113                 pattern = ((pattern << 8) & 0xFFFFFFFF) | buffer[read_pos + 3];
3114                 if (pattern < 0x000001E0 || pattern > 0x000001EF) {
3115                         read_pos++;
3116                         continue;
3117                 } else {
3118                         headerstrip = buffer[read_pos + 8] + 9/*is this right*/;
3119                         packet_length = ((buffer[read_pos + 4] << 8)
3120                                         | (buffer[read_pos + 5])) + 6;
3121                         if (read_pos + packet_length > length)
3122                                 read_pos = length;
3123                         else {
3124                                 if ((headerstrip < packet_length)
3125                                                 && (cur_input_buf_omx->nFilledLen + packet_length
3126                                                                 - headerstrip) > cur_input_buf_omx->nAllocLen) {
3127                                         if (first) {
3128                                                 cur_input_buf_omx->nFlags = OMX_BUFFERFLAG_STARTTIME;
3129
3130                                         } else {
3131                                                 cur_input_buf_omx->nFlags
3132                                                                 |= OMX_BUFFERFLAG_TIME_UNKNOWN;
3133
3134                                         }
3135                                         cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3136                                         PutBufferToPres(cur_input_buf_omx);
3137                                         cur_input_buf_omx = NULL;
3138
3139                                         if (!cur_input_buf_omx) {
3140                                                 int count = 0;
3141                                                 while (count < 100 && omx_running && iframemode) {
3142                                                         count++;
3143
3144                                                         input_bufs_omx_mutex.Lock();
3145                                                         if (input_bufs_omx_free.size() == 0) {
3146                                                                 input_bufs_omx_mutex.Unlock();
3147                                         //                      Log::getInstance()->log("Video", Log::DEBUG,
3148                                                 //                              "Ifrane no free sample");
3149                                                                 MILLISLEEP(5);
3150                                                                 if (!omx_running) return false;
3151                                                                 continue;
3152                                                         }
3153                                                         cur_input_buf_omx = input_bufs_omx_free.front();
3154                                                         cur_input_buf_omx->nFilledLen = 0;
3155                                                         cur_input_buf_omx->nOffset = 0;
3156                                                         cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3157                                                         cur_input_buf_omx->nFlags|= OMX_BUFFERFLAG_TIME_UNKNOWN;
3158                                                         input_bufs_omx_free.pop_front();
3159                                                         input_bufs_omx_mutex.Unlock();
3160                                                         break;
3161                                                 }
3162                                                 if (!cur_input_buf_omx)
3163                                                         return false;
3164                                         }
3165
3166                                 }
3167                                 if (packet_length > headerstrip) {
3168                                         memcpy(
3169                                                         cur_input_buf_omx->pBuffer
3170                                                                         + cur_input_buf_omx->nFilledLen,
3171                                                         buffer + read_pos + headerstrip,
3172                                                         packet_length - headerstrip);
3173                                         cur_input_buf_omx->nFilledLen += packet_length
3174                                                         - headerstrip;
3175                                 }
3176                                 read_pos += packet_length;
3177
3178                                 pattern = (buffer[read_pos] << 16)
3179                                                 | (buffer[read_pos + 1] << 8) | (buffer[read_pos + 2]);
3180                         }
3181                 }
3182         }
3183
3184         if (first) {
3185                 cur_input_buf_omx->nFlags = OMX_BUFFERFLAG_STARTTIME;
3186
3187         } else {
3188                 cur_input_buf_omx->nFlags |= OMX_BUFFERFLAG_TIME_UNKNOWN;
3189
3190         }
3191         cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3192
3193         PutBufferToPres(cur_input_buf_omx);
3194         cur_input_buf_omx = NULL;
3195
3196
3197         MILLISLEEP(40); //Block a bit
3198         return true;
3199 }
3200
3201 int VideoOMX::EnterIframePlayback()
3202 {
3203         Log::getInstance()->log("Video", Log::DEBUG,
3204                                                 "EnterIframePlayback");
3205         if (cur_input_buf_omx) {
3206                 PutBufferToPres(cur_input_buf_omx);
3207                 cur_input_buf_omx = NULL;
3208         }
3209         Log::getInstance()->log("Video", Log::DEBUG,
3210                                                         "EnterIframePlayback 2");
3211         dynamic_cast<AudioOMX*>(Audio::getInstance())->DeAllocateCodecsOMX();
3212         DeAllocateCodecsOMX();
3213         AllocateCodecsOMX();
3214         Log::getInstance()->log("Video", Log::DEBUG,
3215                                                         "leave IframePlayback");
3216
3217         iframemode=true;
3218
3219         return 1;
3220 }
3221