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