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