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