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