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