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