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