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