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