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