]> git.vomp.tv Git - vompclient.git/blob - videoomx.cc
Windows readme and makefile updated!
[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, "Deinter 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         clock_mutex.Lock();
1807         omx_event_mutex.Lock();
1808         list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1809         while (itty!=omx_events.end()) {
1810                 VPE_OMX_EVENT current=*itty;
1811                 if (current.event_type==OMX_EventParamOrConfigChanged && current.data1==omx_codec_output_port
1812                                 && current.handle==omx_vid_dec && current.data2==OMX_IndexConfigBufferStall) {
1813                         OMX_ERRORTYPE error;
1814                         OMX_CONFIG_BUFFERSTALLTYPE stall_conf;
1815                         memset(&stall_conf,0,sizeof(stall_conf));
1816                         stall_conf.nSize=sizeof(stall_conf);
1817                         stall_conf.nVersion.nVersion=OMX_VERSION;
1818                         stall_conf.nPortIndex=omx_codec_output_port;
1819                         stall_conf.nDelay=200000;
1820
1821                         error=OMX_GetConfig(omx_vid_dec,OMX_IndexConfigBufferStall,&stall_conf);
1822                         if (error!=OMX_ErrorNone){
1823                                         Log::getInstance()->log("Video", Log::DEBUG, "Get OMX_IndexConfigBufferStall failed %x", error);
1824                                         clock_mutex.Unlock();
1825                                         omx_event_mutex.Unlock();
1826                                         return ;
1827                                 }
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         clock_mutex.Unlock();
1842 }
1843
1844
1845
1846
1847 int VideoOMX::CommandFinished(OMX_HANDLETYPE handle,OMX_U32 command,OMX_U32 data2) //needs to be called with locked mutex
1848 {
1849         int i=0;
1850         while (i<200/*1000*/) {
1851                 omx_event_mutex.Lock();
1852                 list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1853                 while (itty!=omx_events.end()) {
1854
1855                         VPE_OMX_EVENT current=*itty;
1856                         if (current.handle==handle) { //this is ours
1857                                 if (current.event_type==OMX_EventError) {
1858                                         omx_events.erase(itty);
1859                                         omx_event_mutex.Unlock();
1860                                         Log::getInstance()->log("Video", Log::DEBUG, "Command Finished on Error %x",current.data1);
1861                                         return 0;
1862
1863                                 } else if (current.event_type==OMX_EventCmdComplete && current.data1==command && current.data2==data2) {
1864                                         omx_events.erase(itty);
1865                                         omx_event_mutex.Unlock();
1866                                         //Log::getInstance()->log("Video", Log::DEBUG, "Command Finished Completed");
1867                                         return 1;
1868                                 }
1869                         }
1870                         itty++;
1871
1872                 }
1873                 omx_event_mutex.Unlock();
1874                 omx_event_ready_signal.waitForSignalTimed(10);
1875                 //MILLISLEEP(2);
1876                 i++;
1877
1878         }
1879         Log::getInstance()->log("Video", Log::DEBUG, "CommandFinished waited too long %x %x %x",handle,command, data2);
1880         return 0;
1881
1882 }
1883
1884
1885
1886 int VideoOMX::PrepareInputBufsOMX() //needs to be called with locked mutex
1887 {
1888         OMX_ERRORTYPE error;
1889         OMX_PARAM_PORTDEFINITIONTYPE port_def_type;
1890         memset(&port_def_type,0,sizeof(port_def_type));
1891         port_def_type.nSize=sizeof(port_def_type);
1892         port_def_type.nVersion.nVersion=OMX_VERSION;
1893         port_def_type.nPortIndex=omx_codec_input_port;
1894
1895         error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
1896
1897         if (error!=OMX_ErrorNone){
1898                         Log::getInstance()->log("Video", Log::DEBUG, "Get OMX OMX_IndexParamPortDefinition failed %x", error);
1899         }
1900 /*      Log::getInstance()->log("Video", Log::DEBUG, "Port para %d %d %d %d %d %d %d", port_def_type.nBufferCountActual,
1901                         port_def_type.nBufferCountMin,port_def_type.nBufferSize,port_def_type.bEnabled,port_def_type.bPopulated,
1902                         port_def_type.bBuffersContiguous,port_def_type.nBufferAlignment);*/
1903
1904         port_def_type.nBufferCountActual=100;
1905         port_def_type.nBufferSize=max(port_def_type.nBufferSize,150000); // for transcoder important
1906
1907         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
1908
1909         if (error!=OMX_ErrorNone){
1910                         Log::getInstance()->log("Video", Log::DEBUG, "Set OMX OMX_IndexParamPortDefinition failed %x", error);
1911         }
1912
1913
1914         error=OMX_SendCommand(omx_vid_dec,OMX_CommandPortEnable,omx_codec_input_port,0);
1915         if (error!=OMX_ErrorNone){
1916                 Log::getInstance()->log("Video", Log::DEBUG, "Prepare Input bufs Send Command to enable port %x", error);
1917                 return 0;
1918         }
1919
1920         input_bufs_omx_mutex.Lock();
1921         for (unsigned int i=0; i< port_def_type.nBufferCountActual;i++) {
1922
1923         //      unsigned char* new_buffer_data=(unsigned char*)malloc(port_def_type.nbufferSize);
1924                 OMX_BUFFERHEADERTYPE *buf_head=NULL;
1925         /*      error=OMX_Usebuffer(omx_vid_dec,&buf_head,omx_codec_input_port,NULL,port_def_type.nbufferSize,new_buffer_data);
1926                 if (error!=OMX_ErrorNone){
1927                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_Usebuffer failed %x", error);
1928                         input_bufs_omx_mutex.Unlock();
1929                         return 0;
1930                 }*/
1931                 error=OMX_AllocateBuffer(omx_vid_dec,&buf_head,omx_codec_input_port,NULL,port_def_type.nBufferSize);
1932                 if (error!=OMX_ErrorNone){
1933                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_AllocateBuffer failed %x", error);
1934                                 input_bufs_omx_mutex.Unlock();
1935                         return 0;
1936                 }
1937                 input_bufs_omx_all.push_back(buf_head);
1938                 input_bufs_omx_free.push_back(buf_head);
1939         }
1940         omx_first_frame=true;
1941
1942         firstsynched=false;
1943         cur_input_buf_omx=NULL;
1944         input_bufs_omx_mutex.Unlock();
1945
1946
1947         Log::getInstance()->log("Video", Log::DEBUG, "PrepareInputBufsOMX mark3");
1948         if (!CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_input_port)) {
1949                 return 0;
1950         }
1951         Log::getInstance()->log("Video", Log::DEBUG, "PrepareInputBufsOMX mark4");
1952
1953         return 1;
1954 }
1955
1956 int VideoOMX::DestroyInputBufsOMX() //need s to be called with locked mutex
1957 {
1958         OMX_ERRORTYPE error;
1959
1960         cur_input_buf_omx=NULL;
1961         input_bufs_omx_mutex.Lock();
1962         for (int i=0; i< input_bufs_omx_all.size();i++) {
1963         //      free(input_bufs_omx_all[i]->pBuffer);
1964         //      input_bufs_omx_all[i]->pBuffer=NULL;
1965                 error=OMX_FreeBuffer(omx_vid_dec,omx_codec_input_port,input_bufs_omx_all[i]);
1966                 if (error!=OMX_ErrorNone){
1967                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_FreeBuffer failed %x", error);
1968                         input_bufs_omx_mutex.Unlock();
1969                         return 0;
1970                 }
1971
1972         }
1973         input_bufs_omx_all.clear();
1974         input_bufs_omx_free.clear();
1975         input_bufs_omx_mutex.Unlock();
1976
1977 }
1978
1979
1980
1981 int VideoOMX::FlushRenderingPipe()
1982 {
1983         OMX_ERRORTYPE error;
1984
1985         if (!dodeint) {
1986
1987                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
1988                                 omx_codec_output_port, NULL);
1989                 if (error != OMX_ErrorNone) {
1990                         Log::getInstance()->log("Video", Log::DEBUG,
1991                                         "OMX_Flush codec out 1 failed %x", error);
1992
1993                 }
1994
1995                 error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
1996                                 omx_shed_input_port, NULL);
1997                 if (error != OMX_ErrorNone) {
1998                         Log::getInstance()->log("Video", Log::DEBUG,
1999                                         "OMX_Flush shed in 2 failed %x", error);
2000
2001                 }
2002
2003                 if (!CommandFinished(omx_vid_dec, OMX_CommandFlush,
2004                                 omx_codec_output_port)) {
2005                         Log::getInstance()->log("Video", Log::DEBUG,
2006                                         "flush cmd codec  3 failed");
2007                 }
2008
2009                 if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
2010                                 omx_shed_input_port)) {
2011                         Log::getInstance()->log("Video", Log::DEBUG,
2012                                         "flush cmd  shed 4 failed");
2013                 }
2014         } else {
2015                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
2016                                 omx_codec_output_port, NULL);
2017                 if (error != OMX_ErrorNone) {
2018                         Log::getInstance()->log("Video", Log::DEBUG,
2019                                         "OMX_Flush codec out 5 failed %x", error);
2020
2021                 }
2022
2023                 error = OMX_SendCommand(omx_vid_deint, OMX_CommandFlush,
2024                                 omx_deint_input_port, NULL);
2025                 if (error != OMX_ErrorNone) {
2026                         Log::getInstance()->log("Video", Log::DEBUG,
2027                                         "OMX_Flush deint in 6 failed %x", error);
2028
2029                 }
2030
2031                 if (!CommandFinished(omx_vid_dec, OMX_CommandFlush,
2032                                 omx_codec_output_port)) {
2033                         Log::getInstance()->log("Video", Log::DEBUG,
2034                                         "flush cmd codec  7 failed");
2035                 }
2036
2037                 if (!CommandFinished(omx_vid_deint, OMX_CommandFlush,
2038                                 omx_deint_input_port)) {
2039                         Log::getInstance()->log("Video", Log::DEBUG,
2040                                         "flush cmd  deint 8 failed");
2041                 }
2042
2043                 //m
2044                 error = OMX_SendCommand(omx_vid_deint, OMX_CommandFlush,
2045                                 omx_deint_output_port, NULL);
2046                 if (error != OMX_ErrorNone) {
2047                         Log::getInstance()->log("Video", Log::DEBUG,
2048                                         "OMX_Flush deint out 9 failed %x", error);
2049
2050                 }
2051
2052                 error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
2053                                 omx_shed_input_port, NULL);
2054                 if (error != OMX_ErrorNone) {
2055                         Log::getInstance()->log("Video", Log::DEBUG,
2056                                         "OMX_Flush shed in 10 failed %x", error);
2057
2058                 }
2059
2060                 if (!CommandFinished(omx_vid_deint, OMX_CommandFlush,
2061                                 omx_deint_output_port)) {
2062                         Log::getInstance()->log("Video", Log::DEBUG,
2063                                         "flush cmd deint 11 failed");
2064                 }
2065
2066                 if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
2067                                 omx_shed_input_port)) {
2068                         Log::getInstance()->log("Video", Log::DEBUG,
2069                                         "flush cmd  shed 12 failed");
2070                 }
2071
2072
2073
2074         }
2075
2076
2077
2078
2079         error = OMX_SendCommand(omx_vid_rend, OMX_CommandFlush,
2080                         omx_rend_input_port, NULL);
2081         if (error != OMX_ErrorNone) {
2082                 Log::getInstance()->log("Video", Log::DEBUG,
2083                                 "OMX_Flush rend in failed %x", error);
2084
2085         }
2086
2087         error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
2088                         omx_shed_output_port, NULL);
2089         if (error != OMX_ErrorNone) {
2090                 Log::getInstance()->log("Video", Log::DEBUG,
2091                                 "OMX_Flush shed out failed %x", error);
2092
2093         }
2094
2095
2096
2097         if (!CommandFinished(omx_vid_rend, OMX_CommandFlush,
2098                         omx_rend_input_port)) {
2099                 Log::getInstance()->log("Video", Log::DEBUG,
2100                                 "flush cmd shed rend failed");
2101         }
2102
2103         if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
2104                         omx_shed_output_port)) {
2105                 Log::getInstance()->log("Video", Log::DEBUG,
2106                                 "flush cmd shed rend failed");
2107         }
2108 }
2109
2110
2111 int VideoOMX::DeAllocateCodecsOMX()
2112 {
2113         OMX_ERRORTYPE error;
2114         omx_running=false;
2115           Log::getInstance()->log("Video", Log::DEBUG, "enter deallocatecodecsomx");
2116
2117    if (cur_input_buf_omx) {
2118                 cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_EOS;
2119                 OMX_ERRORTYPE error=ProtOMXEmptyThisBuffer(omx_vid_dec,cur_input_buf_omx);
2120                 if (error!=OMX_ErrorNone) {
2121                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_EmptyThisBuffer failed %x", error);
2122                 }
2123
2124                 cur_input_buf_omx=NULL;//write out old data
2125         }
2126    clock_mutex.Lock();
2127    clearEvents();
2128         if (omx_vid_dec) {
2129                 // first stop the omx elements
2130                 if (!ChangeComponentState(omx_vid_dec,OMX_StateIdle)) {
2131                         Log::getInstance()->log("Video", Log::DEBUG, "vid_dec ChangeComponentState");
2132
2133                 }
2134                 clock_mutex.Unlock();
2135
2136                 idleClock();
2137                 clock_mutex.Lock();
2138
2139                 if (dodeint) {
2140                         if (!ChangeComponentState(omx_vid_deint, OMX_StateIdle)) {
2141                                 Log::getInstance()->log("Video", Log::DEBUG,
2142                                                 "vid_deint ChangeComponentState");
2143
2144                         }
2145                 }
2146
2147
2148                 if (!ChangeComponentState(omx_vid_sched,OMX_StateIdle)) {
2149                         Log::getInstance()->log("Video", Log::DEBUG, "vid_shed ChangeComponentState");
2150
2151                 }
2152
2153                 if (!ChangeComponentState(omx_vid_rend,OMX_StateIdle)) {
2154                         Log::getInstance()->log("Video", Log::DEBUG, "vid_rend ChangeComponentState");
2155
2156                 }
2157
2158
2159
2160         // TODO proper deinit sequence
2161                 // first flush all buffers
2162                 FlushRenderingPipe();
2163
2164
2165
2166
2167
2168                 error=OMX_SendCommand(omx_clock,OMX_CommandFlush, omx_clock_output_port, NULL);
2169                 if (error!=OMX_ErrorNone){
2170                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Flush clock out failed %x", error);
2171
2172                 }
2173
2174                 error=OMX_SendCommand(omx_vid_sched,OMX_CommandFlush, omx_shed_clock_port, NULL);
2175                 if (error!=OMX_ErrorNone){
2176                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Flush shed clock failed %x", error);
2177
2178                 }
2179
2180                 if (!CommandFinished(omx_clock,OMX_CommandFlush,omx_clock_output_port) ||
2181                         !CommandFinished(omx_vid_sched,OMX_CommandFlush,omx_shed_clock_port)) {
2182                                 Log::getInstance()->log("Video", Log::DEBUG, "flush cmd clock shed failed");
2183                 }
2184
2185
2186
2187
2188                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
2189                                 omx_codec_input_port, NULL);
2190                 if (error != OMX_ErrorNone) {
2191                         Log::getInstance()->log("Video", Log::DEBUG,
2192                                         "OMX_Flush codec out failed %x", error);
2193
2194                 }
2195
2196
2197
2198
2199                 DestroyInputBufsOMX();
2200
2201                 //todo flushing
2202                 if (!DisablePort(omx_vid_sched,omx_shed_output_port,true)) {
2203                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 2 ");
2204                 }
2205                 if (!DisablePort(omx_vid_rend,omx_rend_input_port,true)) {
2206                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 1");
2207                 }
2208
2209
2210
2211
2212                 if (!DisablePort(omx_vid_dec,omx_codec_output_port,true)) {
2213                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 6");
2214                 }
2215
2216
2217
2218                 if (!DisablePort(omx_vid_dec,omx_codec_input_port,true)) {
2219                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 7");
2220                 }
2221
2222                 if (dodeint) {
2223                         if (!DisablePort(omx_vid_deint,omx_deint_output_port,true)) {
2224                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 6a");
2225                         }
2226
2227
2228
2229                         if (!DisablePort(omx_vid_deint,omx_deint_input_port,true)) {
2230                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 7a");
2231                         }
2232                 }
2233
2234
2235
2236                 if (!DisablePort(omx_vid_sched,omx_shed_input_port,true)) {
2237                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 3");
2238                 }
2239
2240                 if (!DisablePort(omx_vid_sched,omx_shed_clock_port,true)) {
2241                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 4");
2242                 }
2243
2244                 if (!DisablePort(omx_clock,omx_clock_output_port,true)) {
2245                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 5");
2246                 }
2247
2248
2249
2250
2251                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,NULL,NULL);
2252                 if (error!=OMX_ErrorNone) {
2253                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2254
2255                 }
2256
2257                 if (dodeint) {
2258                         error=OMX_SetupTunnel(omx_vid_deint,omx_deint_input_port,NULL,NULL);
2259                         if (error!=OMX_ErrorNone) {
2260                                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2261                         }
2262
2263
2264                         error=OMX_SetupTunnel(omx_vid_deint,omx_deint_output_port,NULL,NULL);
2265                         if (error!=OMX_ErrorNone) {
2266                                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2267                         }
2268                 }
2269
2270                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_input_port,NULL,NULL);
2271                 if (error!=OMX_ErrorNone) {
2272                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2273
2274                 }
2275
2276
2277                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_output_port,NULL,NULL);
2278                 if (error!=OMX_ErrorNone) {
2279                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2280
2281                 }
2282
2283                 error=OMX_SetupTunnel(omx_vid_rend,omx_rend_input_port,NULL,NULL);
2284                 if (error!=OMX_ErrorNone) {
2285                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2286
2287                 }
2288
2289
2290                 error=OMX_SetupTunnel(omx_clock,omx_clock_output_port,NULL,NULL);
2291                 if (error!=OMX_ErrorNone) {
2292                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2293
2294                 }
2295
2296                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_clock_port,NULL,NULL);
2297                 if (error!=OMX_ErrorNone) {
2298                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2299
2300                 }
2301
2302
2303
2304
2305                 error=OMX_FreeHandle(omx_vid_dec);
2306                 error=OMX_FreeHandle(omx_vid_sched);
2307                 error=OMX_FreeHandle(omx_vid_rend);
2308                 if (dodeint) error=OMX_FreeHandle(omx_vid_deint);
2309                 omx_vid_dec=NULL;
2310                 clock_mutex.Unlock();
2311                 destroyClock();
2312                 if (error!=OMX_ErrorNone) {
2313                         Log::getInstance()->log("Video", Log::DEBUG, "FreeHandle failed %d", error);
2314                 }
2315         } else  clock_mutex.Unlock();
2316           Log::getInstance()->log("Video", Log::DEBUG, "leave deallocate codecs OMX");
2317
2318         return 1;
2319 }
2320
2321
2322 void VideoOMX::destroyClock()
2323 {
2324         clock_mutex.Lock();
2325         if (clock_references>0) {
2326                 clock_references--;
2327                 if (clock_references==0) {
2328                         OMX_ERRORTYPE error;
2329                         Log::getInstance()->log("Video", Log::DEBUG, "destroy omx clock");
2330                         error=OMX_FreeHandle(omx_clock);
2331                         if (error!=OMX_ErrorNone) {
2332                                 Log::getInstance()->log("Video", Log::DEBUG, "FreeHandle failed %d", error);
2333                         }
2334
2335                 }
2336         }
2337         clock_mutex.Unlock();
2338
2339 }
2340
2341 int VideoOMX::stop()
2342 {
2343   if (!initted) return 0;
2344   iframemode=false;
2345
2346   //Check if libav mode
2347   DeAllocateCodecsOMX();
2348
2349
2350
2351
2352 //  if (ioctl(fdVideo, AV_SET_VID_STOP, 0) != 0) return 0;
2353   return 1;
2354 }
2355
2356 int VideoOMX::reset()
2357 {
2358   if (!initted) return 0;
2359
2360   iframemode=false;
2361   DeAllocateCodecsOMX();
2362 //  if (ioctl(fdVideo, AV_SET_VID_RESET, 0x11) != 0) return 0;
2363   return 1;
2364 }
2365
2366 int VideoOMX::pause()
2367 {
2368   if (!initted) return 0;
2369   Log::getInstance()->log("Video", Log::DEBUG, "enter pause");
2370  // clockPause();
2371   // ignore it audio handles this
2372   return 1;
2373 }
2374
2375 int VideoOMX::unPause() // FIXME get rid - same as play!! Not here!
2376 {
2377   if (!initted) return 0;
2378   Log::getInstance()->log("Video", Log::DEBUG, "enter unpause");
2379
2380   //clockUnpause();
2381   //ignore it audio handles this
2382
2383   return 1;
2384 }
2385
2386 int VideoOMX::fastForward()
2387 {
2388   if (!initted) return 0;
2389
2390 //  if (ioctl(fdVideo, AV_SET_VID_libavWD, 1) != 0) return 0;
2391   return 1;
2392 }
2393
2394 int VideoOMX::unFastForward()
2395 {
2396   if (!initted) return 0;
2397
2398 //  if (ioctl(fdVideo, AV_SET_VID_RESET, 0x11) != 0) return 0; // don't need this.
2399
2400  //// if (ioctl(fdVideo, AV_SET_VID_PLAY, 0) != 0) return 0;
2401   return 1;
2402 }
2403
2404 int VideoOMX::attachFrameBuffer()
2405 {
2406   if (!initted) return 0;
2407
2408 //  if (ioctl(fdVideo, AV_SET_VID_FB, 0) != 0) return 0;
2409   return 1;
2410 }
2411
2412 int VideoOMX::blank(void)
2413 {
2414 //  if (ioctl(fdVideo, AV_SET_VID_FB, 1) != 0) return 0;
2415 //  if (ioctl(fdVideo, AV_SET_VID_FB, 0) != 0) return 0;
2416   return 1;
2417 }
2418
2419 ULLONG VideoOMX::getCurrentTimestamp() {
2420         if (iframemode)
2421                 return 0;
2422         long long ncur_clock_time = cur_clock_time;
2423         if (omx_running) {
2424                 int oldcancelstate;
2425                 int oldcanceltype;
2426                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2427                 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2428                 clock_mutex.Lock();
2429                 OMX_ERRORTYPE error;
2430                 OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
2431                 memset(&clock_conf, 0, sizeof(clock_conf));
2432                 clock_conf.nSize = sizeof(clock_conf);
2433                 clock_conf.nVersion.nVersion = OMX_VERSION;
2434                 error= OMX_GetConfig(omx_clock, OMX_IndexConfigTimeClockState,
2435                                 &clock_conf);
2436                 if (error != OMX_ErrorNone) {
2437                         Log::getInstance()->log("Video", Log::DEBUG,"getCurrentTimestamp IndexConfigTimeClockState failed %x",error);
2438                 }
2439
2440                 if (clock_conf.eState == OMX_TIME_ClockStateRunning) {
2441
2442                         OMX_TIME_CONFIG_TIMESTAMPTYPE cur_time_stamp;
2443                         memset(&cur_time_stamp, 0, sizeof(cur_time_stamp));
2444                         cur_time_stamp.nSize = sizeof(cur_time_stamp);
2445                         cur_time_stamp.nVersion.nVersion = OMX_VERSION;
2446                         cur_time_stamp.nPortIndex = omx_clock_output_port;
2447                         error = OMX_GetConfig(omx_clock, OMX_IndexConfigTimeCurrentMediaTime,
2448                                         &cur_time_stamp);
2449                         if (error != OMX_ErrorNone) {
2450                                 Log::getInstance()->log("Video",Log::DEBUG,"getCurrentTimestamp OMX_IndexConfigTimeCurrentMediaTime failed %x",error);
2451                         } else {
2452                                 long long temp = cur_time_stamp.nTimestamp.nLowPart
2453                                                 | ((long long) cur_time_stamp.nTimestamp.nHighPart << 32);
2454                                 ncur_clock_time = cur_clock_time = temp * 10LL;
2455                         }
2456                 }
2457                 clock_mutex.Unlock();
2458                 pthread_setcancelstate(oldcancelstate, NULL);
2459                 pthread_setcanceltype(oldcanceltype, NULL);
2460         }
2461
2462         //ncur_clock_time -= startoffset;
2463         ncur_clock_time -= lastreftimeOMX;
2464         long long result = lastreftimePTS;
2465         if (lastreftimePTS==0) return 0; // invalid time
2466         result += (long long) (ncur_clock_time / 10000LL * 90LL);
2467         if (result < 0)
2468                 result = (1LL << 33) - result;
2469         //Log::getInstance()->log("Video", Log::DEBUG,"getCurrentTimestamp %lld %lld %lld %lld %lld %lld",ncur_clock_time,cur_clock_time,lastreftimeOMX,lastreftimePTS,result,startoffset);
2470
2471         return result;
2472
2473 }
2474
2475 // to be removed
2476 /*
2477 ULONG VideoOMX::timecodeToFrameNumber(ULLONG timecode)
2478 {
2479   if (format == PAL) return (ULONG)(((double)timecode / (double)90000) * (double)25);
2480   else               return (ULONG)(((double)timecode / (double)90000) * (double)30);
2481 }
2482
2483 */
2484 #ifdef DEV
2485 int VideoOMX::test()
2486 {
2487   return 0;
2488
2489 //  ULLONG stc = 0;
2490 //  return ioctl(fdVideo, AV_SET_VID_STC, &stc);
2491 /*
2492  // reset();
2493   return 1;
2494 */
2495 }
2496
2497 int VideoOMX::test2()
2498 {
2499   return 0;
2500 }
2501 #endif
2502
2503
2504
2505 long long VideoOMX::SetStartOffset(long long curreftime, bool *rsync)
2506 {
2507   *rsync=false;
2508   if (offsetnotset) {
2509     startoffset=curreftime;//offset is set for audio
2510     offsetnotset=false;
2511     offsetvideonotset=false;
2512   } else {
2513     if (offsetvideonotset) {
2514       offsetvideonotset=false;
2515       *rsync=true;
2516     } else {
2517       if ( (curreftime-lastrefvideotime)>10000000LL
2518         || (curreftime-lastrefvideotime)<-10000000LL) {//if pts jumps to big resync
2519         startoffset+=curreftime-lastrefvideotime;
2520         lastrefaudiotime+=curreftime-lastrefvideotime;
2521         //*rsync=true;
2522         offsetaudionotset=true;
2523
2524       }
2525     }
2526
2527   }
2528
2529   lastrefvideotime=curreftime;
2530
2531   return startoffset;
2532
2533 }
2534
2535 long long VideoOMX::SetStartAudioOffset(long long curreftime, bool *rsync)
2536 {
2537   *rsync=false;
2538   if (offsetnotset) {
2539     startoffset=curreftime;
2540     offsetnotset=false;
2541     offsetaudionotset=false;
2542   }else {
2543     if (offsetaudionotset) {
2544       offsetaudionotset=false;
2545       *rsync=true;
2546     } else {
2547       if ( (curreftime-lastrefaudiotime)>10000000LL
2548         || (curreftime-lastrefaudiotime)<-10000000LL) {//if pts jumps to big resync
2549         startoffset+=curreftime-lastrefaudiotime;
2550         lastrefvideotime+=curreftime-lastrefaudiotime;
2551         //*rsync=true;
2552         offsetvideonotset=true;
2553
2554       }
2555     }
2556
2557   }
2558   lastrefaudiotime=curreftime;
2559   return startoffset;
2560
2561 }
2562
2563 void VideoOMX::ResetTimeOffsets() {
2564   offsetnotset=true; //called from demuxer
2565   offsetvideonotset=true;
2566   offsetaudionotset=true;
2567   startoffset=0;
2568   lastrefaudiotime=0;
2569   lastrefvideotime=0;
2570   lastreftimeOMX=0;
2571   lastreftimePTS=0;
2572 }
2573
2574
2575 void VideoOMX::FirstFrameFix()
2576 {
2577         int oldcancelstate;
2578         int oldcanceltype;
2579         Demuxer* demux=Demuxer::getInstance();
2580         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2581         pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2582         clock_mutex.Lock();
2583         if (WaitForEvent(omx_vid_dec,OMX_EventPortSettingsChanged,0)){
2584                 WaitForEvent(omx_vid_deint,OMX_EventPortSettingsChanged,0); //clear old messages
2585                 OMX_ERRORTYPE error;
2586                 OMX_PARAM_PORTDEFINITIONTYPE port_def_type;
2587                 memset(&port_def_type,0,sizeof(port_def_type));
2588                 port_def_type.nSize=sizeof(port_def_type);
2589                 port_def_type.nVersion.nVersion=OMX_VERSION;
2590                 port_def_type.nPortIndex=omx_codec_output_port;
2591
2592                 error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
2593                 if (error != OMX_ErrorNone) {
2594                         Log::getInstance()->log("Video", Log::DEBUG,
2595                                         "OMX_IndexParamPortDefinition fix failed %x", error);
2596                         clock_mutex.Unlock();
2597                         return;
2598                 }
2599
2600
2601                 Log::getInstance()->log("Video", Log::DEBUG,
2602                                                         "Deinit first frame fix %d %d %d %d %d %d %d %d",port_def_type.format.video.nFrameWidth , demux->getHorizontalSize(),
2603                                                         port_def_type.format.video.nFrameHeight , demux->getVerticalSize(),port_def_type.format.video.nStride,
2604                                                         port_def_type.format.video.nSliceHeight, port_def_type.format.video.xFramerate,
2605                                                          port_def_type.format.video.bFlagErrorConcealment );
2606                 Log::getInstance()->log("Video", Log::DEBUG,
2607                                                                         "Deinit first frame fix2 %d  %d",
2608                                                                         port_def_type.format.video.eCompressionFormat ,
2609                                                                         port_def_type.format.video.eColorFormat );
2610                 first_frame=false;
2611
2612                 // we cause the video_decode to determine the interlacing properties
2613                 OMX_CONFIG_INTERLACETYPE il;
2614                 memset(&il,0,sizeof(il));
2615                 il.nSize=sizeof(il);
2616                 il.nVersion.nVersion=OMX_VERSION;
2617                 il.nPortIndex=omx_codec_output_port;
2618                 error=OMX_GetConfig(omx_vid_dec,OMX_IndexConfigCommonInterlace, &il);
2619                 if (error != OMX_ErrorNone) {
2620                         Log::getInstance()->log("Video", Log::DEBUG,
2621                                         "OMX_IndexConfigCommonInterlace fix failed %x", error);
2622                 }
2623
2624
2625                 DisablePort(omx_vid_dec,omx_codec_output_port,true);
2626                 DisablePort(omx_vid_sched,omx_shed_input_port,true);
2627                 if (dodeint) {
2628
2629                         DisablePort(omx_vid_deint,omx_deint_input_port,true);
2630                         // This is a dirty hack
2631                         DisablePort(omx_vid_deint,omx_deint_output_port,true);
2632
2633
2634                         port_def_type.nPortIndex=omx_deint_output_port;
2635                         error = OMX_SetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2636                                         &port_def_type);
2637                         if (error != OMX_ErrorNone) {
2638                                 Log::getInstance()->log("Video", Log::DEBUG,
2639                                                 "Set OMX_IndexParamPortDefinition1 failed %x", error);
2640                                 clock_mutex.Unlock();
2641                                 pthread_setcancelstate(oldcancelstate, NULL);
2642                                 pthread_setcanceltype(oldcanceltype, NULL);
2643                                 return;
2644                         }
2645                         // dirty hack end
2646
2647
2648                         port_def_type.nPortIndex=omx_deint_input_port;
2649                         error = OMX_SetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2650                                         &port_def_type);
2651                         if (error != OMX_ErrorNone) {
2652                                 Log::getInstance()->log("Video", Log::DEBUG,
2653                                                 "Set OMX_IndexParamPortDefinition1 failed %x", error);
2654                                 clock_mutex.Unlock();
2655                                 pthread_setcancelstate(oldcancelstate, NULL);
2656                                 pthread_setcanceltype(oldcanceltype, NULL);
2657                                 return;
2658                         }
2659                 //      WaitForEvent(omx_vid_dec,OMX_EventPortSettingsChanged);
2660
2661                         Log::getInstance()->log("Video", Log::DEBUG,
2662                                                                         "Marker");
2663                         EnablePort(omx_vid_deint,omx_deint_input_port,true);
2664                         WaitForEvent(omx_vid_deint,OMX_EventPortSettingsChanged);
2665                         port_def_type.nPortIndex=omx_deint_output_port;
2666                         error = OMX_GetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2667                                         &port_def_type);
2668                         if (error != OMX_ErrorNone) {
2669                                 Log::getInstance()->log("Video", Log::DEBUG,
2670                                                 "Get OMX_IndexParamPortDefinition2 failed %x", error);
2671                                 clock_mutex.Unlock();
2672                                 pthread_setcancelstate(oldcancelstate, NULL);
2673                                 pthread_setcanceltype(oldcanceltype, NULL);
2674                                 return;
2675                         }
2676                         Log::getInstance()->log("Video", Log::DEBUG,
2677                                         "Deinit first frame fix3 %d %d %d %d %d %d %d %d",port_def_type.format.video.nFrameWidth , demux->getHorizontalSize(),
2678                                         port_def_type.format.video.nFrameHeight , demux->getVerticalSize(),port_def_type.format.video.nStride,
2679                                         port_def_type.format.video.nSliceHeight, port_def_type.format.video.xFramerate,
2680                                         port_def_type.format.video.bFlagErrorConcealment );
2681                         Log::getInstance()->log("Video", Log::DEBUG,
2682                                         "Deinit first frame fix4 %d  %d",
2683                                         port_def_type.format.video.eCompressionFormat ,
2684                                         port_def_type.format.video.eColorFormat );
2685                         DisablePort(omx_vid_deint,omx_deint_output_port,true);
2686
2687                 }
2688                 port_def_type.nPortIndex=omx_shed_input_port;
2689                 error = OMX_SetParameter(omx_vid_sched, OMX_IndexParamPortDefinition,
2690                                         &port_def_type);
2691                 if (error != OMX_ErrorNone) {
2692                         Log::getInstance()->log("Video", Log::DEBUG,
2693                                         "Set OMX_IndexParamPortDefinition3 failed %x", error);
2694                         clock_mutex.Unlock();
2695                         pthread_setcancelstate(oldcancelstate, NULL);
2696                         pthread_setcanceltype(oldcanceltype, NULL);
2697                         return;
2698                 }
2699                 WaitForEvent(omx_vid_sched,OMX_EventPortSettingsChanged);
2700
2701
2702                 if (dodeint) {
2703                         EnablePort(omx_vid_deint,omx_deint_output_port,true);
2704                 }
2705                 EnablePort(omx_vid_dec,omx_codec_output_port,true);
2706                 EnablePort(omx_vid_sched,omx_shed_input_port,true);
2707         }
2708         clock_mutex.Unlock();
2709         pthread_setcancelstate(oldcancelstate, NULL);
2710         pthread_setcanceltype(oldcanceltype, NULL);
2711
2712
2713
2714 }
2715
2716
2717 void VideoOMX::PutBufferToPres(OMX_BUFFERHEADERTYPE* buffer)
2718 {
2719
2720         OMX_ERRORTYPE error = ProtOMXEmptyThisBuffer(omx_vid_dec, buffer);
2721         if (error != OMX_ErrorNone) {
2722                 Log::getInstance()->log("Video", Log::DEBUG,
2723                                 "OMX_EmptyThisBuffer failed %x", error);
2724         }
2725         if (first_frame) FirstFrameFix();
2726
2727 }
2728
2729 OMX_ERRORTYPE VideoOMX::ProtOMXEmptyThisBuffer(OMX_HANDLETYPE handle, OMX_BUFFERHEADERTYPE* buffer)
2730 {
2731         // protect the call to empty this buffer
2732         int oldcancelstate;
2733         int oldcanceltype;
2734 /*      long long temp =buffer->nTimeStamp.nLowPart
2735                                                         | ((long long) buffer->nTimeStamp.nHighPart << 32);*/
2736
2737         //pthread_testcancel();
2738         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2739         pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2740         clock_mutex.Lock();
2741 // Diagnosis code
2742 /*      OMX_ERRORTYPE error;
2743         OMX_TIME_CONFIG_TIMESTAMPTYPE timestamp;
2744         memset(&timestamp, 0, sizeof(timestamp));
2745         timestamp.nSize = sizeof(timestamp);
2746         timestamp.nVersion.nVersion = OMX_VERSION;
2747         timestamp.nPortIndex =omx_clock_output_port;
2748
2749         error = OMX_GetConfig(omx_clock, OMX_IndexConfigTimeCurrentMediaTime,
2750                         &timestamp);
2751
2752         if (error != OMX_ErrorNone) {
2753                 Log::getInstance()->log("Audio", Log::DEBUG,
2754                                 "Init OMX_IndexConfigAudioRenderingLatencyfailed %x %d", error,
2755                                 omx_rend_input_port);
2756         }
2757         long long temp2 =timestamp.nTimestamp.nLowPart
2758                                                                 | ((long long) timestamp.nTimestamp.nHighPart << 32);
2759
2760
2761         Log::getInstance()->log("Video", Log::NOTICE, "OMXETB %x %lld %lld %x",handle,temp,temp2,buffer->nFlags);*/
2762         OMX_ERRORTYPE ret_val;
2763         ret_val=OMX_EmptyThisBuffer(handle,buffer);
2764         clock_mutex.Unlock();
2765         pthread_setcancelstate(oldcancelstate, NULL);
2766         pthread_setcanceltype(oldcanceltype, NULL);
2767         //pthread_testcancel();
2768         return ret_val;
2769 }
2770
2771 bool VideoOMX::detectIFrame(const UCHAR *buffer,unsigned int length)
2772 {
2773         const UCHAR* curbuf=buffer;
2774         const UCHAR* curbufend=buffer+length;
2775         unsigned int detector=0xFFFFFFFF;
2776         bool gotaud=false; // have seen access unit delimiter
2777
2778         while (curbuf!=curbufend) {
2779                 detector<<=8;
2780                 detector|=*curbuf;
2781                 if (h264) {
2782                         if (detector==0x00000109) {
2783                                 gotaud=true;
2784                                 detector=0xFFFFFFFF;
2785                         } else if (gotaud &&detector==0x00000001) {
2786                                 curbuf++;
2787                                 if (curbuf!=curbufend) {
2788                                         unsigned char picttype=(*curbuf)& 0x1F;
2789                                         return picttype==0x07;
2790                                 }
2791                         }
2792                 } else {
2793                         if (detector==0x00000100) {
2794                                 curbuf++;
2795                                 if (curbuf==curbufend) return false;
2796                                 curbuf++;
2797                                 if (curbuf==curbufend) return false;
2798                                 unsigned char picttype=((*curbuf) >> 3) & 0x07;
2799                                 return picttype==1;
2800                         }
2801                 }
2802                 curbuf++;
2803         }
2804
2805         return false; // no frame found
2806 }
2807
2808
2809
2810 bool VideoOMX::DrainTargetBufferFull()
2811 {
2812         //Check, if we have OMX output buffers
2813         bool full;
2814         input_bufs_omx_mutex.Lock();
2815         full=(input_bufs_omx_free.size()==0);
2816         input_bufs_omx_mutex.Unlock();
2817         checkForStalledBuffers(); // check if the decoder has a problem
2818         if (full && omx_vid_stalled && !omx_first_frame) {
2819                 omx_vid_stalled=false;
2820                 Log::getInstance()->log("Video", Log::DEBUG, "Decoder is stalled, do a reset!");
2821                 clock_mutex.Lock();
2822                 FlushRenderingPipe();
2823                 omx_first_frame=true;
2824                 clock_mutex.Unlock();
2825         }
2826         return full;
2827
2828 }
2829
2830 void VideoOMX::PrepareMediaSample(const MediaPacketList& mplist,UINT samplepos)
2831 {
2832
2833         mediapackets.clear();
2834         list<MediaPacket>::const_iterator begin=mplist.begin();
2835         list<MediaPacket>::const_iterator itty=mplist.begin();
2836         advance(itty,min(mplist.size(),10));
2837         mediapackets.insert(mediapackets.begin(),begin,itty);//front
2838
2839 }
2840
2841 UINT VideoOMX::DeliverMediaSample(UCHAR* buffer, UINT *samplepos)
2842 {
2843         int consumed=0;
2844         while (consumed<mediapackets.size()) {
2845             DeliverMediaPacket(mediapackets[consumed], buffer, samplepos);
2846             if (*samplepos == mediapackets[consumed].length) {
2847                 *samplepos = 0;
2848                 consumed++;
2849                 //return 1;
2850             } else return consumed;
2851         }
2852         return consumed;
2853 }
2854
2855 UINT VideoOMX::DeliverMediaPacket(MediaPacket packet,
2856                 const UCHAR* buffer,
2857                 UINT *samplepos)
2858 {
2859         if (packet.type == MPTYPE_VIDEO_H264)
2860         {
2861                 h264=true;
2862         }
2863         else
2864         {
2865                 h264=false;
2866         }
2867
2868
2869         //Later add fail back code for libav
2870 /*      if (!videoon) {
2871                 *samplepos+=packet.length;
2872                 return packet.length;
2873         }*/
2874
2875
2876         if (!omx_running) return 0; // if we are not runnig do not do this
2877
2878         if (isClockPaused()) return 0; //Block if we pause
2879
2880 //      Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 1");
2881         //Log::getInstance()->log("Video", Log::DEBUG, "DeliverMediaPacketOMX time %lld",packet.presentation_time);
2882
2883
2884
2885         OMX_ERRORTYPE error;
2886
2887         /*First Check, if we have an video sample*/
2888         if (iframemode) {
2889                 //samplepos=0;
2890                 MILLISLEEP(10);
2891                 return 0; //Not in iframe mode!
2892         }
2893
2894         UINT headerstrip=0;
2895         if (packet.disconti) {
2896                 firstsynched=false;
2897                 if (cur_input_buf_omx) {
2898                         PutBufferToPres(cur_input_buf_omx);
2899                         cur_input_buf_omx=NULL;
2900                 }
2901         }
2902         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 2");
2903         /*Inspect PES-Header */
2904
2905 //      OMX_STATETYPE temp_state;
2906 //      OMX_GetState(omx_vid_dec,&temp_state);
2907
2908         if (*samplepos==0) {//stripheader
2909                 headerstrip=buffer[packet.pos_buffer+8]+9/*is this right*/;
2910         //      if (h264) Log::getInstance()->log("Video", Log::DEBUG, "PES info %x %x %x %x",
2911         //                      buffer[packet.pos_buffer+0],buffer[packet.pos_buffer+1],buffer[packet.pos_buffer+2],buffer[packet.pos_buffer+3]);
2912                 *samplepos+=headerstrip;
2913                 if (headerstrip>=packet.length) {
2914                      *samplepos=packet.length;// Packet is obviously damaged
2915                      return packet.length;//skip it!
2916                 }
2917                 if ( packet.synched ) {
2918                         if (!firstsynched) {
2919                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 2a");
2920                           // check if this is an I frame, the decoder does not like non I frames at startup!
2921                           if (!detectIFrame(buffer,packet.length)) {
2922                                   *samplepos=packet.length;//if we have not processed at least one
2923                                   //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 3");
2924                                   return packet.length;//synched packet ignore it!
2925                           }
2926                         }
2927                         if (cur_input_buf_omx) {
2928                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 4a");
2929                                 cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_ENDOFFRAME;
2930                                 PutBufferToPres(cur_input_buf_omx);
2931                                 cur_input_buf_omx=NULL;//write out old data
2932
2933                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 4b");
2934
2935                         }
2936                         firstsynched=true;
2937                 } else {
2938                         if (!firstsynched) {//
2939                                 *samplepos=packet.length;//if we have not processed at least one
2940                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 5");
2941                                 return packet.length;//synched packet ignore it!
2942                         }
2943                 }
2944         }
2945         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 6");
2946         if (!cur_input_buf_omx) {
2947                 input_bufs_omx_mutex.Lock();
2948                 if (input_bufs_omx_free.size()==0) {
2949                         input_bufs_omx_mutex.Unlock();
2950                         //Log::getInstance()->log("Video", Log::DEBUG, "Deliver MediaPacket no free sample");
2951                         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 7");
2952                         return 0; // we do not have a free media sample
2953
2954                 }
2955                 cur_input_buf_omx=input_bufs_omx_free.front();
2956                 cur_input_buf_omx->nFilledLen=0;
2957                 cur_input_buf_omx->nOffset=0;
2958                 cur_input_buf_omx->nTimeStamp=intToOMXTicks(0);
2959                 input_bufs_omx_free.pop_front();
2960                 input_bufs_omx_mutex.Unlock();
2961         }
2962
2963
2964
2965
2966         if (cur_input_buf_omx->nFilledLen==0) {//will only be changed on first packet
2967                 if (packet.synched) {
2968                 //      Log::getInstance()->log("Video", Log::DEBUG, "packet synched marker");
2969
2970                         //lastreftimePTS=packet.pts;
2971                    if (omx_first_frame) { // TODO time
2972                            cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_STARTTIME;
2973                            Log::getInstance()->log("Video", Log::DEBUG, "Starttime");
2974                            omx_first_frame=false;
2975                    } else {
2976                            cur_input_buf_omx->nFlags=0;
2977                            //cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_TIME_UNKNOWN;
2978                    }
2979                    lastreftimeOMX=packet.presentation_time;
2980                   // Log::getInstance()->log("Video", Log::DEBUG, "Time code %lld pts %lld", lastreftimeOMX,packet.pts);
2981                    lastreftimePTS=packet.pts;
2982                    cur_input_buf_omx->nTimeStamp=intToOMXTicks(lastreftimeOMX/10LL); // the clock component is faulty;
2983                 }
2984                 else
2985                 {
2986                         cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_TIME_UNKNOWN;
2987                         cur_input_buf_omx->nTimeStamp=intToOMXTicks(0);
2988                         //Log::getInstance()->log("Video", Log::DEBUG, "packet unsynched marker");
2989                 }
2990                 if (packet.disconti) cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_DISCONTINUITY;
2991
2992
2993
2994         }
2995         unsigned int haveToCopy=packet.length-*samplepos;
2996         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 8");
2997
2998         while (haveToCopy> (cur_input_buf_omx->nAllocLen-cur_input_buf_omx->nFilledLen)) {
2999                 //Log::getInstance()->log("Video", Log::DEBUG, "Big buffer %d %d %d",packet.length,cur_input_buf_omx->nAllocLen,cur_input_buf_omx->nFilledLen);
3000                 unsigned int cancopy=cur_input_buf_omx->nAllocLen-cur_input_buf_omx->nFilledLen;
3001                 memcpy(cur_input_buf_omx->pBuffer+cur_input_buf_omx->nFilledLen,buffer+packet.pos_buffer+*samplepos,cancopy);
3002                 haveToCopy-=cancopy;
3003                 cur_input_buf_omx->nFilledLen+=cancopy;
3004                 *samplepos+=cancopy;
3005                 // push old buffer out
3006                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 9");
3007
3008                 PutBufferToPres(cur_input_buf_omx);
3009                 cur_input_buf_omx=NULL;
3010                 // get5 new buffer
3011                 input_bufs_omx_mutex.Lock();
3012                 if (input_bufs_omx_free.size()==0) {
3013                         input_bufs_omx_mutex.Unlock();
3014                 //      Log::getInstance()->log("Video", Log::DEBUG, "Deliver MediaPacket no free sample2");
3015                         return *samplepos; // we do not have a free media sample
3016                 }
3017                 cur_input_buf_omx=input_bufs_omx_free.front();
3018                 cur_input_buf_omx->nFilledLen=0;
3019                 cur_input_buf_omx->nOffset=0;
3020                 cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_TIME_UNKNOWN;
3021                 cur_input_buf_omx->nTimeStamp=intToOMXTicks(0);
3022                 input_bufs_omx_free.pop_front();
3023                 input_bufs_omx_mutex.Unlock();
3024                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 10");
3025
3026         }
3027         memcpy(cur_input_buf_omx->pBuffer+cur_input_buf_omx->nFilledLen,
3028                         buffer+packet.pos_buffer+*samplepos,haveToCopy);
3029         cur_input_buf_omx->nFilledLen+=haveToCopy;
3030
3031 //      Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 11");
3032
3033         *samplepos+=haveToCopy;
3034
3035         return *samplepos;
3036
3037 }
3038
3039
3040
3041
3042 bool VideoOMX::displayIFrame(const UCHAR* buffer, UINT length) {
3043         if (!omx_running) return false;
3044         if (!iframemode)
3045                 EnterIframePlayback();
3046
3047         int haveToCopy = length;
3048
3049         if (!cur_input_buf_omx) {
3050                 input_bufs_omx_mutex.Lock();
3051                 if (input_bufs_omx_free.size() == 0) {
3052                         input_bufs_omx_mutex.Unlock();
3053                 //      Log::getInstance()->log("Video", Log::DEBUG,
3054                         //              "Deliver MediaPacket no free sample");
3055                         return false; // we do not have a free media sample
3056
3057                 }
3058                 cur_input_buf_omx = input_bufs_omx_free.front();
3059                 cur_input_buf_omx->nFilledLen = 0;
3060                 cur_input_buf_omx->nOffset = 0;
3061                 cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3062                 input_bufs_omx_free.pop_front();
3063                 input_bufs_omx_mutex.Unlock();
3064         }
3065
3066         int read_pos = 0;
3067         unsigned int pattern, packet_length;
3068         unsigned int headerstrip = 0;
3069         bool first = true;
3070         if (length < 4){
3071                 return false;
3072         }
3073         //Now we strip the pes header
3074         pattern = (buffer[0] << 16) | (buffer[1] << 8) | (buffer[2]);
3075         while (read_pos + 7 <= length) {
3076                 pattern = ((pattern << 8) & 0xFFFFFFFF) | buffer[read_pos + 3];
3077                 if (pattern < 0x000001E0 || pattern > 0x000001EF) {
3078                         read_pos++;
3079                         continue;
3080                 } else {
3081                         headerstrip = buffer[read_pos + 8] + 9/*is this right*/;
3082                         packet_length = ((buffer[read_pos + 4] << 8)
3083                                         | (buffer[read_pos + 5])) + 6;
3084                         if (read_pos + packet_length > length)
3085                                 read_pos = length;
3086                         else {
3087                                 if ((headerstrip < packet_length)
3088                                                 && (cur_input_buf_omx->nFilledLen + packet_length
3089                                                                 - headerstrip) > cur_input_buf_omx->nAllocLen) {
3090                                         if (first) {
3091                                                 cur_input_buf_omx->nFlags = OMX_BUFFERFLAG_STARTTIME;
3092
3093                                         } else {
3094                                                 cur_input_buf_omx->nFlags
3095                                                                 |= OMX_BUFFERFLAG_TIME_UNKNOWN;
3096
3097                                         }
3098                                         cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3099                                         PutBufferToPres(cur_input_buf_omx);
3100                                         cur_input_buf_omx = NULL;
3101
3102                                         if (!cur_input_buf_omx) {
3103                                                 int count = 0;
3104                                                 while (count < 100 && omx_running && iframemode) {
3105                                                         count++;
3106
3107                                                         input_bufs_omx_mutex.Lock();
3108                                                         if (input_bufs_omx_free.size() == 0) {
3109                                                                 input_bufs_omx_mutex.Unlock();
3110                                         //                      Log::getInstance()->log("Video", Log::DEBUG,
3111                                                 //                              "Ifrane no free sample");
3112                                                                 MILLISLEEP(5);
3113                                                                 if (!omx_running) return false;
3114                                                                 continue;
3115                                                         }
3116                                                         cur_input_buf_omx = input_bufs_omx_free.front();
3117                                                         cur_input_buf_omx->nFilledLen = 0;
3118                                                         cur_input_buf_omx->nOffset = 0;
3119                                                         cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3120                                                         cur_input_buf_omx->nFlags|= OMX_BUFFERFLAG_TIME_UNKNOWN;
3121                                                         input_bufs_omx_free.pop_front();
3122                                                         input_bufs_omx_mutex.Unlock();
3123                                                         break;
3124                                                 }
3125                                                 if (!cur_input_buf_omx)
3126                                                         return false;
3127                                         }
3128
3129                                 }
3130                                 if (packet_length > headerstrip) {
3131                                         memcpy(
3132                                                         cur_input_buf_omx->pBuffer
3133                                                                         + cur_input_buf_omx->nFilledLen,
3134                                                         buffer + read_pos + headerstrip,
3135                                                         packet_length - headerstrip);
3136                                         cur_input_buf_omx->nFilledLen += packet_length
3137                                                         - headerstrip;
3138                                 }
3139                                 read_pos += packet_length;
3140
3141                                 pattern = (buffer[read_pos] << 16)
3142                                                 | (buffer[read_pos + 1] << 8) | (buffer[read_pos + 2]);
3143                         }
3144                 }
3145         }
3146
3147         if (first) {
3148                 cur_input_buf_omx->nFlags = OMX_BUFFERFLAG_STARTTIME;
3149
3150         } else {
3151                 cur_input_buf_omx->nFlags |= OMX_BUFFERFLAG_TIME_UNKNOWN;
3152
3153         }
3154         cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3155
3156         PutBufferToPres(cur_input_buf_omx);
3157         cur_input_buf_omx = NULL;
3158
3159
3160         MILLISLEEP(40); //Block a bit
3161         return true;
3162 }
3163
3164 int VideoOMX::EnterIframePlayback()
3165 {
3166         Log::getInstance()->log("Video", Log::DEBUG,
3167                                                 "EnterIframePlayback");
3168         if (cur_input_buf_omx) {
3169                 PutBufferToPres(cur_input_buf_omx);
3170                 cur_input_buf_omx = NULL;
3171         }
3172         Log::getInstance()->log("Video", Log::DEBUG,
3173                                                         "EnterIframePlayback 2");
3174         ((AudioOMX*)Audio::getInstance())->DeAllocateCodecsOMX();
3175         DeAllocateCodecsOMX();
3176         AllocateCodecsOMX();
3177         Log::getInstance()->log("Video", Log::DEBUG,
3178                                                         "leave IframePlayback");
3179
3180         iframemode=true;
3181
3182         return 1;
3183 }
3184