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