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