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