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