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