]> git.vomp.tv Git - vompclient.git/blob - videoomx.cc
Fix major Bug in demuxer, fix audio playback on some channels
[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         if (clock_references>0) {
681                 OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
682                 memset(&clock_conf,0,sizeof(clock_conf));
683                 clock_conf.nSize=sizeof(clock_conf);
684                 clock_conf.nVersion.nVersion=OMX_VERSION;
685                 clock_conf.eState=OMX_TIME_ClockStateRunning;
686                 clock_conf.nStartTime=0;
687                 clock_conf.nOffset=0;
688                 clock_conf.nWaitMask=OMX_CLOCKPORT1;
689                 error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
690                 if (error!=OMX_ErrorNone) {
691                         Log::getInstance()->log("Video", Log::DEBUG, "ClockUnpause IndexConfigTimeClockState failed %x", error);
692                 }
693         }
694         clock_mutex.Unlock();
695 }
696
697
698 void VideoOMX::clockPause()
699 {
700         OMX_ERRORTYPE error;
701         clock_mutex.Lock();
702         if (clock_references>0) {
703                 OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
704                 memset(&clock_conf,0,sizeof(clock_conf));
705                 clock_conf.nSize=sizeof(clock_conf);
706                 clock_conf.nVersion.nVersion=OMX_VERSION;
707                 clock_conf.eState=OMX_TIME_ClockStateStopped;
708                 clock_conf.nStartTime=0;
709                 clock_conf.nOffset=0;
710                 clock_conf.nWaitMask=OMX_CLOCKPORT1;
711                 error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
712                 if (error!=OMX_ErrorNone) {
713                         Log::getInstance()->log("Video", Log::DEBUG, "ClockUnpause IndexConfigTimeClockState failed %x", error);
714                 }
715         }
716         clock_mutex.Unlock();
717 }
718
719
720
721 int VideoOMX::AllocateCodecsOMX()
722 {
723         OMX_ERRORTYPE error;
724         static OMX_CALLBACKTYPE callbacks= {&EventHandler_OMX,&EmptyBufferDone_OMX,&FillBufferDone_OMX};
725
726         Demuxer* demux=Demuxer::getInstance();
727
728         dodeint=false;
729         deint_first_frame=false;
730
731         Log::getInstance()->log("Video", Log::NOTICE, "Allocate Codecs OMX");
732         //Clock, move later to audio including events
733
734         if (deinterlace!=0 && demux->getHorizontalSize()<=720) { //only deinterlace SD material
735                 dodeint=true;
736                 deint_first_frame=true;
737
738                 Log::getInstance()->log("Video", Log::NOTICE, "Deinterlacing activated %d",deinterlace);
739
740         }
741
742
743         if (!getClockVideoandInit()){
744                 return 0;// get the clock and init it if necessary
745         }
746
747
748         if (!idleClock()) {
749                 Log::getInstance()->log("Video", Log::DEBUG, "idleClock failed");
750                 return 0;
751         }
752         /* TODO end */
753
754
755         clock_mutex.Lock();
756         if (h264) {
757                 error=OMX_GetHandle(&omx_vid_dec,VPE_OMX_H264_DECODER,NULL,&callbacks);
758         } else {
759                 error=OMX_GetHandle(&omx_vid_dec,VPE_OMX_MPEG2_DECODER,NULL,&callbacks);
760         }
761
762         if (error!=OMX_ErrorNone){
763                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video decoder failed %x", error);
764                 clock_mutex.Unlock();
765                 DeAllocateCodecsOMX();
766                 return 0;
767         }
768
769
770         Log::getInstance()->log("Video", Log::DEBUG, "Nmark3 ");
771         OMX_PORT_PARAM_TYPE p_param;
772         memset(&p_param,0,sizeof(p_param));
773         p_param.nSize=sizeof(p_param);
774         p_param.nVersion.nVersion=OMX_VERSION;
775         error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamVideoInit,&p_param);
776         if (error!=OMX_ErrorNone){
777                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX h264 decoder OMX_GetParameter failed %x", error);
778                 clock_mutex.Unlock();
779                 DeAllocateCodecsOMX();
780             return 0;
781         }
782         omx_codec_input_port=p_param.nStartPortNumber;
783         omx_codec_output_port=p_param.nStartPortNumber+1;
784
785         if (!DisablePort(omx_vid_dec,omx_codec_input_port) || !DisablePort(omx_vid_dec,omx_codec_output_port)) {
786                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX video decoder failed");
787                 clock_mutex.Unlock();
788                 DeAllocateCodecsOMX();
789                 return 0;
790         }
791
792         Log::getInstance()->log("Video", Log::DEBUG, "Nmark4 ");
793
794         OMX_PARAM_BRCMVIDEODECODEERRORCONCEALMENTTYPE conceal;
795         memset(&conceal,0,sizeof(conceal));
796         conceal.nSize=sizeof(conceal);
797         conceal.nVersion.nVersion=OMX_VERSION;
798         conceal.bStartWithValidFrame=OMX_FALSE;
799
800         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamBrcmVideoDecodeErrorConcealment,&conceal);
801         if (error!=OMX_ErrorNone){
802                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_IndexParamBrcmVideoDecodeErrorConcealment failed %x", error);
803                 clock_mutex.Unlock();
804                 DeAllocateCodecsOMX();
805                 return 0;
806         }
807
808         if (dodeint) {
809                 error = OMX_GetHandle(&omx_vid_deint, VPE_OMX_VIDEO_DEINTERLACE, NULL,
810                                 &callbacks);
811                 if (error != OMX_ErrorNone) {
812                         Log::getInstance()->log("Video", Log::DEBUG,
813                                         "Init OMX video deinterlacer failed %x", error);
814                         clock_mutex.Unlock();
815                         DeAllocateCodecsOMX();
816                         return 0;
817                 }
818
819                 error = OMX_GetParameter(omx_vid_deint, OMX_IndexParamImageInit,
820                                 &p_param);
821                 if (error != OMX_ErrorNone) {
822                         Log::getInstance()->log("Video", Log::DEBUG,
823                                         "Init OMX video deinterlacer OMX_GetParameter failed %x",
824                                         error);
825                         clock_mutex.Unlock();
826                         DeAllocateCodecsOMX();
827                         return 0;
828                 }
829                 omx_deint_input_port = p_param.nStartPortNumber;
830                 omx_deint_output_port = p_param.nStartPortNumber + 1;
831
832                 if (!DisablePort(omx_vid_deint, omx_deint_input_port, true)
833                                 || !DisablePort(omx_vid_deint, omx_deint_output_port, true)) {
834                         Log::getInstance()->log("Video", Log::DEBUG,
835                                         "Disable Ports OMX video deint failed");
836                         clock_mutex.Unlock();
837                         DeAllocateCodecsOMX();
838                         return 0;
839                 }
840
841         }
842
843
844         error=OMX_GetHandle(&omx_vid_sched,VPE_OMX_VIDEO_SCHED,NULL,&callbacks);
845         if (error!=OMX_ErrorNone){
846                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video scheduler failed %x", error);
847                 clock_mutex.Unlock();
848                 DeAllocateCodecsOMX();
849                 return 0;
850         }
851
852
853
854         error=OMX_GetParameter(omx_vid_sched,OMX_IndexParamVideoInit,&p_param);
855         if (error!=OMX_ErrorNone){
856                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video scheduler OMX_GetParameter failed %x", error);
857                 clock_mutex.Unlock();
858                 DeAllocateCodecsOMX();
859                 return 0;
860         }
861         omx_shed_input_port=p_param.nStartPortNumber;
862         omx_shed_output_port=p_param.nStartPortNumber+1;
863
864
865         error=OMX_GetParameter(omx_vid_sched,OMX_IndexParamOtherInit,&p_param);
866         if (error!=OMX_ErrorNone){
867                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video scheduler OMX_GetParameter failed %x", error);
868                 clock_mutex.Unlock();
869                 DeAllocateCodecsOMX();
870                 return 0;
871         }
872         omx_shed_clock_port=p_param.nStartPortNumber;
873         Log::getInstance()->log("Video", Log::DEBUG, "scheduler ports %d %d %d ",omx_shed_input_port,omx_shed_output_port,omx_shed_clock_port);
874
875
876         if (!DisablePort(omx_vid_sched,omx_shed_input_port,true) || !DisablePort(omx_vid_sched,omx_shed_output_port,true)
877                         || !DisablePort(omx_vid_sched,omx_shed_clock_port,true)) {
878                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX video shed failed");
879                 clock_mutex.Unlock();
880                 DeAllocateCodecsOMX();
881                 return 0;
882         }
883
884
885         error=OMX_GetHandle(&omx_vid_rend,VPE_OMX_VIDEO_REND,NULL,&callbacks);
886         if (error!=OMX_ErrorNone){
887                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video rend failed %x", error);
888                 clock_mutex.Unlock();
889                 DeAllocateCodecsOMX();
890                 return 0;
891         }
892
893         error=OMX_GetParameter(omx_vid_rend,OMX_IndexParamVideoInit,&p_param);
894         if (error!=OMX_ErrorNone){
895                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video rend OMX_GetParameter failed %x", error);
896                 clock_mutex.Unlock();
897                 DeAllocateCodecsOMX();
898                 return 0;
899         }
900         omx_rend_input_port=p_param.nStartPortNumber;
901         //omx_rend_output_port=p_param.nStartPortNumber+1;
902
903
904         if (!DisablePort(omx_vid_rend,omx_rend_input_port,true) /*|| !DisablePort(omx_vid_rend,omx_rend_output_port)*/
905                                 ) {
906                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX video rend failed");
907                 clock_mutex.Unlock();
908                 DeAllocateCodecsOMX();
909                 return 0;
910         }
911
912         //Setuo chain
913
914
915
916         error=OMX_SetupTunnel(omx_clock,omx_clock_output_port,omx_vid_sched,omx_shed_clock_port);
917         if (error!=OMX_ErrorNone){
918                 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);
919                 clock_mutex.Unlock();
920                 DeAllocateCodecsOMX();
921                 return 0;
922         }
923
924         if (!EnablePort(omx_clock,omx_clock_output_port,false) || !EnablePort(omx_vid_sched,omx_shed_clock_port,false)
925                                         ) {
926                 Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX clock shed failed");
927                 clock_mutex.Unlock();
928                 DeAllocateCodecsOMX();
929                 return 0;
930         }
931
932
933         Log::getInstance()->log("Video", Log::DEBUG, "mark2 ");
934         if (!ChangeComponentState(omx_vid_sched,OMX_StateIdle)) {
935                 Log::getInstance()->log("Video", Log::DEBUG, "vid_sched idle ChangeComponentState");
936                 clock_mutex.Unlock();
937                 DeAllocateCodecsOMX();
938                 return 0;
939         }
940
941
942
943         Log::getInstance()->log("Video", Log::DEBUG, "mark1 ");
944         if ( !CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_clock_port)) {
945                 clock_mutex.Unlock();
946                 DeAllocateCodecsOMX();
947                 return 0;
948         }
949
950
951
952
953         Log::getInstance()->log("Video", Log::DEBUG, "mark1 special ");
954         if ( !CommandFinished(omx_clock,OMX_CommandPortEnable,omx_clock_output_port)) {
955                 clock_mutex.Unlock();
956                 DeAllocateCodecsOMX();
957                 return 0;
958         }
959
960
961
962         Log::getInstance()->log("Video", Log::DEBUG, "mark1b ");
963
964
965 /*      error=OMX_SendCommand(omx_vid_dec,OMX_CommandStateSet,OMX_StateIdle,0);
966         if (error!=OMX_ErrorNone){
967                 Log::getInstance()->log("Video", Log::DEBUG, "vid_dec Send Command to OMX State Idle %x", error);
968                 return 0;
969         }*/
970
971         OMX_VIDEO_PARAM_PORTFORMATTYPE ft_type;
972         memset(&ft_type,0,sizeof(ft_type));
973         ft_type.nSize=sizeof(ft_type);
974         ft_type.nVersion.nVersion=OMX_VERSION;
975
976         ft_type.nPortIndex=omx_codec_input_port;
977         if (h264) {
978                 ft_type.eCompressionFormat=OMX_VIDEO_CodingAVC;
979         } else {
980                 ft_type.eCompressionFormat=OMX_VIDEO_CodingMPEG2;
981         }
982
983
984
985     ft_type.xFramerate=0;//25*(1<<16);//demux->getFrameRate()*(1<<16);
986     Log::getInstance()->log("Video", Log::DEBUG, "Framerate: %d",demux->getFrameRate());
987         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamVideoPortFormat,&ft_type);
988         if (error!=OMX_ErrorNone){
989                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexParamVideoPortFormat failed %x", error);
990                 clock_mutex.Unlock();
991                 DeAllocateCodecsOMX();
992                 return 0;
993         }
994
995
996         if (!ChangeComponentState(omx_vid_dec,OMX_StateIdle)) {
997                 Log::getInstance()->log("Video", Log::DEBUG, "vid_dec ChangeComponentState");
998                 clock_mutex.Unlock();
999                 DeAllocateCodecsOMX();
1000                 return 0;
1001         }
1002
1003
1004         if (!PrepareInputBufsOMX()) {
1005                 clock_mutex.Unlock();
1006                 DeAllocateCodecsOMX();
1007                 return 0;
1008         }
1009
1010         if (!dodeint) {
1011                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,omx_vid_sched,omx_shed_input_port);
1012                 if (error!=OMX_ErrorNone){
1013                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel dec to sched failed %x", error);
1014                         clock_mutex.Unlock();
1015                         DeAllocateCodecsOMX();
1016                         return 0;
1017                 }
1018
1019
1020
1021                 if (!EnablePort(omx_vid_dec,omx_codec_output_port,false) || !EnablePort(omx_vid_sched,omx_shed_input_port,false)
1022                 ) {
1023                         Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX codec shed failed");
1024                         clock_mutex.Unlock();
1025                         DeAllocateCodecsOMX();
1026                         return 0;
1027                 }
1028
1029                 if ( !CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_output_port) || !CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_input_port)) {
1030                         clock_mutex.Unlock();
1031                         DeAllocateCodecsOMX();
1032                         return 0;
1033                 }
1034
1035         } else {
1036
1037                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,omx_vid_deint,omx_deint_input_port);
1038                 if (error!=OMX_ErrorNone){
1039                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel dec to deint failed %x", error);
1040                         clock_mutex.Unlock();
1041                         DeAllocateCodecsOMX();
1042                         return 0;
1043                 }
1044
1045
1046
1047                 if (!EnablePort(omx_vid_dec,omx_codec_output_port,false) || !EnablePort(omx_vid_deint,omx_deint_input_port,false)
1048                 ) {
1049                         Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX codec deint failed");
1050                         clock_mutex.Unlock();
1051                         DeAllocateCodecsOMX();
1052                         return 0;
1053                 }
1054
1055                 if ( !CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_output_port) || !CommandFinished(omx_vid_deint,OMX_CommandPortEnable,omx_deint_input_port)) {
1056                         clock_mutex.Unlock();
1057                         DeAllocateCodecsOMX();
1058                         return 0;
1059                 }
1060
1061                 if (!ChangeComponentState(omx_vid_deint,OMX_StateIdle)) {
1062                         Log::getInstance()->log("Video", Log::DEBUG, "vid_deint ChangeComponentState");
1063                         clock_mutex.Unlock();
1064                         DeAllocateCodecsOMX();
1065                         return 0;
1066                 }
1067
1068                 OMX_CONFIG_IMAGEFILTERPARAMSTYPE imagefilter;
1069                 memset(&imagefilter,0,sizeof(imagefilter));
1070                 imagefilter.nSize=sizeof(imagefilter);
1071                 imagefilter.nVersion.nVersion=OMX_VERSION;
1072
1073                 imagefilter.nPortIndex=omx_deint_output_port;
1074                 imagefilter.nNumParams=1;
1075                 imagefilter.nParams[0]=3;//???
1076                 switch (deinterlace) {
1077                 case 1:
1078                         imagefilter.eImageFilter=OMX_ImageFilterDeInterlaceLineDouble; break;
1079                 case 2:
1080                         imagefilter.eImageFilter=OMX_ImageFilterDeInterlaceAdvanced; break;
1081                 case 3:
1082                         imagefilter.eImageFilter=OMX_ImageFilterFilm; break;
1083                 }
1084
1085
1086                 error=OMX_SetConfig(omx_vid_deint,OMX_IndexConfigCommonImageFilterParameters,&imagefilter);
1087                 if (error!=OMX_ErrorNone){
1088                         Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigCommonImageFilterParameters failed %x", error);
1089                         clock_mutex.Unlock();
1090                         DeAllocateCodecsOMX();
1091                         return 0;
1092                 }
1093
1094
1095                 error=OMX_SetupTunnel(omx_vid_deint,omx_deint_output_port,omx_vid_sched,omx_shed_input_port);
1096                 if (error!=OMX_ErrorNone){
1097                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel deint to sched failed %x", error);
1098                         clock_mutex.Unlock();
1099                         DeAllocateCodecsOMX();
1100                         return 0;
1101                 }
1102
1103                 if (!EnablePort(omx_vid_deint,omx_deint_output_port,false) || !EnablePort(omx_vid_sched,omx_shed_input_port,false)
1104                 ) {
1105                         Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX deint shed failed");
1106                         clock_mutex.Unlock();
1107                         DeAllocateCodecsOMX();
1108                         return 0;
1109                 }
1110
1111                 if ( !CommandFinished(omx_vid_deint,OMX_CommandPortEnable,omx_deint_output_port) || !CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_input_port)) {
1112                         clock_mutex.Unlock();
1113                         DeAllocateCodecsOMX();
1114                         return 0;
1115                 }
1116
1117         }
1118
1119         if (!ChangeComponentState(omx_vid_dec,OMX_StateExecuting)) {
1120                 Log::getInstance()->log("Video", Log::DEBUG, "omx_vid_dec ChangeComponentState Execute");
1121                 clock_mutex.Unlock();
1122                 DeAllocateCodecsOMX();
1123                 return 0;
1124         }
1125
1126         error=OMX_SetupTunnel(omx_vid_sched,omx_shed_output_port,omx_vid_rend,omx_rend_input_port);
1127         if (error!=OMX_ErrorNone){
1128                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel  sched to rend failed %x", error);
1129                 clock_mutex.Unlock();
1130                 DeAllocateCodecsOMX();
1131                 return 0;
1132         }
1133
1134         if (!EnablePort(omx_vid_sched,omx_shed_output_port,false) || !EnablePort(omx_vid_rend,omx_rend_input_port,false)
1135                                                         ) {
1136                 Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX  shed rend failed");
1137                 clock_mutex.Unlock();
1138                 DeAllocateCodecsOMX();
1139                 return 0;
1140         }
1141
1142         if (!CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_output_port)
1143                                         || !CommandFinished(omx_vid_rend,OMX_CommandPortEnable,omx_rend_input_port)) {
1144                 clock_mutex.Unlock();
1145                 DeAllocateCodecsOMX();
1146                 return 0;
1147         }
1148
1149         if (!ChangeComponentState(omx_vid_rend,OMX_StateIdle)) {
1150                 Log::getInstance()->log("Video", Log::DEBUG, "vid_rend ChangeComponentState");
1151                 clock_mutex.Unlock();
1152                 DeAllocateCodecsOMX();
1153                 return 0;
1154         }
1155
1156         if (dodeint) {
1157                 if (!ChangeComponentState(omx_vid_deint,OMX_StateExecuting)) {
1158                         Log::getInstance()->log("Video", Log::DEBUG, "vid_vid_deint ChangeComponentState");
1159                         clock_mutex.Unlock();
1160                         DeAllocateCodecsOMX();
1161                         return 0;
1162                 }
1163                 DisablePort(omx_vid_deint,omx_deint_output_port,false);
1164                 DisablePort(omx_vid_deint,omx_deint_input_port,false);
1165         }
1166
1167         if (!ChangeComponentState(omx_vid_sched,OMX_StateExecuting)) {
1168                 Log::getInstance()->log("Video", Log::DEBUG, "omx_vid_sched ChangeComponentState Execute");
1169                 clock_mutex.Unlock();
1170                 DeAllocateCodecsOMX();
1171                 return 0;
1172         }
1173
1174         if (!ChangeComponentState(omx_vid_rend,OMX_StateExecuting)) {
1175                 Log::getInstance()->log("Video", Log::DEBUG, "omx_vid_rend ChangeComponentState Execute");
1176                 clock_mutex.Unlock();
1177                 DeAllocateCodecsOMX();
1178                 return 0;
1179         }
1180
1181         //raspbi specifif
1182         /*OMX_CONFIG_DISPLAYREGIONTYPE dispconf;
1183         memset(&dispconf,0,sizeof(dispconf));
1184         dispconf.nSize=sizeof(dispconf);
1185         dispconf.nVersion.nVersion=OMX_VERSION;
1186
1187         dispconf.nPortIndex=omx_rend_input_port;
1188
1189         dispconf.set=OMX_DISPLAY_SET_LAYER ;
1190         dispconf.layer=1;
1191         error=OMX_SetConfig(omx_vid_rend,OMX_IndexConfigDisplayRegion,&dispconf);
1192         if (error!=OMX_ErrorNone){
1193                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigDisplayRegion failed %x", error);
1194                 clock_mutex.Unlock();
1195                 DeAllocateCodecsOMX();
1196                 return 0;
1197         }*/
1198
1199 /*      dispconf.set=OMX_DISPLAY_SET_FULLSCREEN ;
1200         dispconf.fullscreen=OMX_FALSE;
1201         error=OMX_SetParameter(omx_vid_rend,OMX_IndexConfigDisplayRegion,&dispconf);
1202         if (error!=OMX_ErrorNone){
1203                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigDisplayRegion failed %x", error);
1204                 clock_mutex.Unlock();
1205                 DeAllocateCodecsOMX();
1206                 return 0;
1207         }
1208
1209         dispconf.set=OMX_DISPLAY_SET_DEST_RECT;
1210         dispconf.dest_rect.x_offset=100;
1211         dispconf.dest_rect.y_offset=100;
1212         dispconf.dest_rect.width=640;
1213         dispconf.dest_rect.height=480;
1214         error=OMX_SetParameter(omx_vid_rend,OMX_IndexConfigDisplayRegion,&dispconf);
1215         if (error!=OMX_ErrorNone){
1216                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigDisplayRegion failed %x", error);
1217                 clock_mutex.Unlock();
1218                 DeAllocateCodecsOMX();
1219                 return 0;
1220         }*/
1221
1222
1223         playbacktimeoffset=-GetCurrentSystemTime();
1224         paused=false;
1225         iframemode=false;
1226         omx_running=true;
1227         clock_mutex.Unlock();
1228         updateMode();
1229         threadStart();
1230
1231         setClockExecutingandRunning();
1232
1233
1234
1235
1236
1237         return 1;
1238 }
1239
1240 int VideoOMX::idleClock()
1241 {
1242         OMX_ERRORTYPE error;
1243         OMX_STATETYPE temp_state;
1244         clock_mutex.Lock();
1245         OMX_GetState(omx_clock,&temp_state);
1246
1247         if (temp_state!=OMX_StateIdle) {
1248                 if (!ChangeComponentState(omx_clock,OMX_StateIdle)) {
1249                         Log::getInstance()->log("Video", Log::DEBUG, "omx_clock ChangeComponentState Idle failed");
1250                         clock_mutex.Unlock();
1251                         return 0;
1252                 }
1253         }
1254         clock_mutex.Unlock();
1255         return 1;
1256 }
1257
1258 int VideoOMX::setClockExecutingandRunning()
1259 {
1260         OMX_ERRORTYPE error;
1261         OMX_STATETYPE temp_state;
1262         clock_mutex.Lock();
1263         OMX_GetState(omx_clock,&temp_state);
1264
1265         if (temp_state!=OMX_StateExecuting) {
1266                 if (!ChangeComponentState(omx_clock,OMX_StateExecuting)) {
1267                         Log::getInstance()->log("Video", Log::DEBUG, "omx_clock ChangeComponentState Execute failed");
1268                         clock_mutex.Unlock();
1269                         DeAllocateCodecsOMX();
1270                         return 0;
1271                 }
1272         }
1273
1274         OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
1275         memset(&clock_conf,0,sizeof(clock_conf));
1276         clock_conf.nSize=sizeof(clock_conf);
1277         clock_conf.nVersion.nVersion=OMX_VERSION;
1278         clock_conf.eState=OMX_TIME_ClockStateRunning;
1279         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
1280         if (error!=OMX_ErrorNone) {
1281                 Log::getInstance()->log("Video", Log::DEBUG, "Clock IndexConfigTimeClockState failed %x", error);
1282                 clock_mutex.Unlock();
1283                 DeAllocateCodecsOMX();
1284                 return 0;
1285         }
1286         clock_mutex.Unlock();
1287         return 1;
1288
1289 }
1290
1291
1292 int VideoOMX::ChangeComponentState(OMX_HANDLETYPE handle,OMX_STATETYPE type) //needs to be called with locked mutex
1293 {
1294         OMX_ERRORTYPE error;
1295         error=OMX_SendCommand(handle,OMX_CommandStateSet,type,0);
1296         if (error!=OMX_ErrorNone){
1297                 Log::getInstance()->log("Video", Log::DEBUG, "handle %x Send Command to OMX State %x %x",handle,type, error);
1298                 return 0;
1299         }
1300
1301         if (!CommandFinished(handle,OMX_CommandStateSet,type)) {
1302                 return 0;
1303         }
1304
1305         return 1;
1306 }
1307
1308
1309 int VideoOMX::EnablePort(OMX_HANDLETYPE handle,OMX_U32 port,bool wait) //needs to be called with locked mutex
1310 {
1311         OMX_ERRORTYPE error;
1312         error=OMX_SendCommand(handle,OMX_CommandPortEnable,port,0);
1313         if (error!=OMX_ErrorNone){
1314                 Log::getInstance()->log("Video", Log::DEBUG, "handle %x Send Command to enable port %x %x",handle,port, error);
1315                 return 0;
1316         }
1317
1318         if (!wait) return 1;
1319         if (!CommandFinished(handle,OMX_CommandPortEnable,port)) {
1320                 return 0;
1321         }
1322
1323         return 1;
1324 }
1325
1326
1327 int VideoOMX::DisablePort(OMX_HANDLETYPE handle,OMX_U32 port,bool wait) //needs to be called with locked mutex
1328 {
1329         OMX_ERRORTYPE error;
1330         error=OMX_SendCommand(handle,OMX_CommandPortDisable,port,0);
1331         if (error!=OMX_ErrorNone){
1332                 Log::getInstance()->log("Video", Log::DEBUG, "handle %x Send Command to disable port %x %x",handle,port, error);
1333                 return 0;
1334         }
1335
1336         if (!wait) return 1;
1337         if (!CommandFinished(handle,OMX_CommandPortDisable,port)) {
1338                 return 0;
1339         }
1340
1341
1342         return 1;
1343 }
1344
1345 int VideoOMX::WaitForEvent(OMX_HANDLETYPE handle,OMX_U32 event) //needs to be called with locked mutex
1346 {
1347         int i=0;
1348         while (i<1000) {
1349                 omx_event_mutex.Lock();
1350                 list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1351                 while (itty!=omx_events.end()) {
1352
1353                         VPE_OMX_EVENT current=*itty;
1354                         if (current.handle==handle) { //this is ours
1355                                 if (current.event_type==OMX_EventError) {
1356                                         omx_events.erase(itty);
1357                                         omx_event_mutex.Unlock();
1358                                         Log::getInstance()->log("Video", Log::DEBUG, "WaitForEvent Finished on Error");
1359                                         return 0;
1360
1361                                 } else if (current.event_type==event) {
1362                                         omx_events.erase(itty);
1363                                         omx_event_mutex.Unlock();
1364                                         Log::getInstance()->log("Video", Log::DEBUG, "WaitForEvent Finished Completed");
1365                                         return 1;
1366                                 }
1367                         }
1368                         itty++;
1369
1370                 }
1371                 omx_event_mutex.Unlock();
1372                 MILLISLEEP(2);
1373                 i++;
1374
1375         }
1376         Log::getInstance()->log("Video", Log::DEBUG, "WaitForEvent waited too long %x %x",handle,event);
1377         return 0;
1378
1379 }
1380
1381
1382 int VideoOMX::CommandFinished(OMX_HANDLETYPE handle,OMX_U32 command,OMX_U32 data2) //needs to be called with locked mutex
1383 {
1384         int i=0;
1385         while (i<1000) {
1386                 omx_event_mutex.Lock();
1387                 list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1388                 while (itty!=omx_events.end()) {
1389
1390                         VPE_OMX_EVENT current=*itty;
1391                         if (current.handle==handle) { //this is ours
1392                                 if (current.event_type==OMX_EventError) {
1393                                         omx_events.erase(itty);
1394                                         omx_event_mutex.Unlock();
1395                                         Log::getInstance()->log("Video", Log::DEBUG, "Command Finished on Error");
1396                                         return 0;
1397
1398                                 } else if (current.event_type==OMX_EventCmdComplete && current.data1==command && current.data2==data2) {
1399                                         omx_events.erase(itty);
1400                                         omx_event_mutex.Unlock();
1401                                         //Log::getInstance()->log("Video", Log::DEBUG, "Command Finished Completed");
1402                                         return 1;
1403                                 }
1404                         }
1405                         itty++;
1406
1407                 }
1408                 omx_event_mutex.Unlock();
1409                 MILLISLEEP(2);
1410                 i++;
1411
1412         }
1413         Log::getInstance()->log("Video", Log::DEBUG, "CommandFinished waited too long %x %x %x",handle,command, data2);
1414         return 0;
1415
1416 }
1417
1418
1419
1420
1421
1422 int VideoOMX::PrepareInputBufsOMX() //needs to be called with locked mutex
1423 {
1424         OMX_ERRORTYPE error;
1425         OMX_PARAM_PORTDEFINITIONTYPE port_def_type;
1426         memset(&port_def_type,0,sizeof(port_def_type));
1427         port_def_type.nSize=sizeof(port_def_type);
1428         port_def_type.nVersion.nVersion=OMX_VERSION;
1429         port_def_type.nPortIndex=omx_codec_input_port;
1430
1431         error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
1432
1433         if (error!=OMX_ErrorNone){
1434                         Log::getInstance()->log("Video", Log::DEBUG, "Get OMX OMX_IndexParamPortDefinition failed %x", error);
1435         }
1436 /*      Log::getInstance()->log("Video", Log::DEBUG, "Port para %d %d %d %d %d %d %d", port_def_type.nBufferCountActual,
1437                         port_def_type.nBufferCountMin,port_def_type.nBufferSize,port_def_type.bEnabled,port_def_type.bPopulated,
1438                         port_def_type.bBuffersContiguous,port_def_type.nBufferAlignment);*/
1439
1440         port_def_type.nBufferCountActual=100;
1441         port_def_type.nBufferSize=max(port_def_type.nBufferSize,200000); // for transcoder important
1442
1443         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
1444
1445         if (error!=OMX_ErrorNone){
1446                         Log::getInstance()->log("Video", Log::DEBUG, "Set OMX OMX_IndexParamPortDefinition failed %x", error);
1447         }
1448
1449
1450         error=OMX_SendCommand(omx_vid_dec,OMX_CommandPortEnable,omx_codec_input_port,0);
1451         if (error!=OMX_ErrorNone){
1452                 Log::getInstance()->log("Video", Log::DEBUG, "Prepare Input bufs Send Command to enable port %x", error);
1453                 return 0;
1454         }
1455
1456         input_bufs_omx_mutex.Lock();
1457         for (unsigned int i=0; i< port_def_type.nBufferCountActual;i++) {
1458
1459         //      unsigned char* new_buffer_data=(unsigned char*)malloc(port_def_type.nbufferSize);
1460                 OMX_BUFFERHEADERTYPE *buf_head=NULL;
1461         /*      error=OMX_Usebuffer(omx_vid_dec,&buf_head,omx_codec_input_port,NULL,port_def_type.nbufferSize,new_buffer_data);
1462                 if (error!=OMX_ErrorNone){
1463                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_Usebuffer failed %x", error);
1464                         input_bufs_omx_mutex.Unlock();
1465                         return 0;
1466                 }*/
1467                 error=OMX_AllocateBuffer(omx_vid_dec,&buf_head,omx_codec_input_port,NULL,port_def_type.nBufferSize);
1468                 if (error!=OMX_ErrorNone){
1469                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_AllocateBuffer failed %x", error);
1470                                 input_bufs_omx_mutex.Unlock();
1471                         return 0;
1472                 }
1473                 input_bufs_omx_all.push_back(buf_head);
1474                 input_bufs_omx_free.push_back(buf_head);
1475         }
1476         omx_first_frame=true;
1477
1478         firstsynched=false;
1479         cur_input_buf_omx=NULL;
1480         input_bufs_omx_mutex.Unlock();
1481
1482
1483         Log::getInstance()->log("Video", Log::DEBUG, "PrepareInputBufsOMX mark3");
1484         if (!CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_input_port)) {
1485                 return 0;
1486         }
1487         Log::getInstance()->log("Video", Log::DEBUG, "PrepareInputBufsOMX mark4");
1488
1489         return 1;
1490 }
1491
1492 int VideoOMX::DestroyInputBufsOMX() //need s to be called with locked mutex
1493 {
1494         OMX_ERRORTYPE error;
1495
1496         cur_input_buf_omx=NULL;
1497         input_bufs_omx_mutex.Lock();
1498         for (int i=0; i< input_bufs_omx_all.size();i++) {
1499         //      free(input_bufs_omx_all[i]->pBuffer);
1500         //      input_bufs_omx_all[i]->pBuffer=NULL;
1501                 error=OMX_FreeBuffer(omx_vid_dec,omx_codec_input_port,input_bufs_omx_all[i]);
1502                 if (error!=OMX_ErrorNone){
1503                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_FreeBuffer failed %x", error);
1504                         input_bufs_omx_mutex.Unlock();
1505                         return 0;
1506                 }
1507
1508         }
1509         input_bufs_omx_all.clear();
1510         input_bufs_omx_free.clear();
1511         input_bufs_omx_present.clear();
1512         input_time_present.clear();
1513         input_is_last.clear();
1514         input_bufs_omx_mutex.Unlock();
1515
1516 }
1517
1518
1519
1520
1521 int VideoOMX::DeAllocateCodecsOMX()
1522 {
1523         OMX_ERRORTYPE error;
1524         omx_running=false;
1525           Log::getInstance()->log("Video", Log::DEBUG, "enter deallocatecodecsomx");
1526         threadStop();
1527
1528
1529    if (cur_input_buf_omx) {
1530                 cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_EOS;
1531                 OMX_ERRORTYPE error=ProtOMXEmptyThisBuffer(omx_vid_dec,cur_input_buf_omx);
1532                 if (error!=OMX_ErrorNone) {
1533                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_EmptyThisBuffer failed %x", error);
1534                 }
1535
1536                 cur_input_buf_omx=NULL;//write out old data
1537         }
1538    clock_mutex.Lock();
1539         if (omx_vid_dec) {
1540                 // first stop the omx elements
1541                 if (!ChangeComponentState(omx_vid_dec,OMX_StateIdle)) {
1542                         Log::getInstance()->log("Video", Log::DEBUG, "vid_dec ChangeComponentState");
1543
1544                 }
1545                 clock_mutex.Unlock();
1546
1547                 idleClock();
1548                 clock_mutex.Lock();
1549
1550                 if (dodeint) {
1551                         if (!ChangeComponentState(omx_vid_deint, OMX_StateIdle)) {
1552                                 Log::getInstance()->log("Video", Log::DEBUG,
1553                                                 "vid_deint ChangeComponentState");
1554
1555                         }
1556                 }
1557
1558
1559                 if (!ChangeComponentState(omx_vid_sched,OMX_StateIdle)) {
1560                         Log::getInstance()->log("Video", Log::DEBUG, "vid_shed ChangeComponentState");
1561
1562                 }
1563
1564                 if (!ChangeComponentState(omx_vid_rend,OMX_StateIdle)) {
1565                         Log::getInstance()->log("Video", Log::DEBUG, "vid_rend ChangeComponentState");
1566
1567                 }
1568
1569
1570
1571         // TODO proper deinit sequence
1572                 // first flush all buffers
1573
1574                 if (!dodeint) {
1575
1576                         error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
1577                                         omx_codec_output_port, NULL);
1578                         if (error != OMX_ErrorNone) {
1579                                 Log::getInstance()->log("Video", Log::DEBUG,
1580                                                 "OMX_Flush codec out failed %x", error);
1581
1582                         }
1583
1584                         error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
1585                                         omx_shed_input_port, NULL);
1586                         if (error != OMX_ErrorNone) {
1587                                 Log::getInstance()->log("Video", Log::DEBUG,
1588                                                 "OMX_Flush shed in failed %x", error);
1589
1590                         }
1591
1592                         if (!CommandFinished(omx_vid_dec, OMX_CommandFlush,
1593                                         omx_codec_output_port)) {
1594                                 Log::getInstance()->log("Video", Log::DEBUG,
1595                                                 "flush cmd codec  failed");
1596                         }
1597
1598                         if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
1599                                         omx_shed_input_port)) {
1600                                 Log::getInstance()->log("Video", Log::DEBUG,
1601                                                 "flush cmd  shed failed");
1602                         }
1603                 } else {
1604                         error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
1605                                         omx_codec_output_port, NULL);
1606                         if (error != OMX_ErrorNone) {
1607                                 Log::getInstance()->log("Video", Log::DEBUG,
1608                                                 "OMX_Flush codec out failed %x", error);
1609
1610                         }
1611
1612                         error = OMX_SendCommand(omx_vid_deint, OMX_CommandFlush,
1613                                         omx_deint_input_port, NULL);
1614                         if (error != OMX_ErrorNone) {
1615                                 Log::getInstance()->log("Video", Log::DEBUG,
1616                                                 "OMX_Flush deint in failed %x", error);
1617
1618                         }
1619
1620                         if (!CommandFinished(omx_vid_dec, OMX_CommandFlush,
1621                                         omx_codec_output_port)) {
1622                                 Log::getInstance()->log("Video", Log::DEBUG,
1623                                                 "flush cmd codec  failed");
1624                         }
1625
1626                         if (!CommandFinished(omx_vid_deint, OMX_CommandFlush,
1627                                         omx_deint_input_port)) {
1628                                 Log::getInstance()->log("Video", Log::DEBUG,
1629                                                 "flush cmd  deint failed");
1630                         }
1631
1632                         //m
1633                         error = OMX_SendCommand(omx_vid_deint, OMX_CommandFlush,
1634                                         omx_deint_output_port, NULL);
1635                         if (error != OMX_ErrorNone) {
1636                                 Log::getInstance()->log("Video", Log::DEBUG,
1637                                                 "OMX_Flush deint out failed %x", error);
1638
1639                         }
1640
1641                         error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
1642                                         omx_shed_input_port, NULL);
1643                         if (error != OMX_ErrorNone) {
1644                                 Log::getInstance()->log("Video", Log::DEBUG,
1645                                                 "OMX_Flush shed in failed %x", error);
1646
1647                         }
1648
1649                         if (!CommandFinished(omx_vid_deint, OMX_CommandFlush,
1650                                         omx_deint_output_port)) {
1651                                 Log::getInstance()->log("Video", Log::DEBUG,
1652                                                 "flush cmd deint  failed");
1653                         }
1654
1655                         if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
1656                                         omx_shed_input_port)) {
1657                                 Log::getInstance()->log("Video", Log::DEBUG,
1658                                                 "flush cmd  shed failed");
1659                         }
1660
1661
1662
1663                 }
1664
1665
1666
1667
1668                 error = OMX_SendCommand(omx_vid_rend, OMX_CommandFlush,
1669                                 omx_rend_input_port, NULL);
1670                 if (error != OMX_ErrorNone) {
1671                         Log::getInstance()->log("Video", Log::DEBUG,
1672                                         "OMX_Flush rend in failed %x", error);
1673
1674                 }
1675
1676                 error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
1677                                 omx_shed_output_port, NULL);
1678                 if (error != OMX_ErrorNone) {
1679                         Log::getInstance()->log("Video", Log::DEBUG,
1680                                         "OMX_Flush shed out failed %x", error);
1681
1682                 }
1683
1684
1685
1686                 if (!CommandFinished(omx_vid_rend, OMX_CommandFlush,
1687                                 omx_rend_input_port)) {
1688                         Log::getInstance()->log("Video", Log::DEBUG,
1689                                         "flush cmd shed rend failed");
1690                 }
1691
1692                 if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
1693                                 omx_shed_output_port)) {
1694                         Log::getInstance()->log("Video", Log::DEBUG,
1695                                         "flush cmd shed rend failed");
1696                 }
1697
1698
1699
1700
1701
1702                 error=OMX_SendCommand(omx_clock,OMX_CommandFlush, omx_clock_output_port, NULL);
1703                 if (error!=OMX_ErrorNone){
1704                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Flush clock out failed %x", error);
1705
1706                 }
1707
1708                 error=OMX_SendCommand(omx_vid_sched,OMX_CommandFlush, omx_shed_clock_port, NULL);
1709                 if (error!=OMX_ErrorNone){
1710                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Flush shed clock failed %x", error);
1711
1712                 }
1713
1714                 if (!CommandFinished(omx_clock,OMX_CommandFlush,omx_clock_output_port) ||
1715                         !CommandFinished(omx_vid_sched,OMX_CommandFlush,omx_shed_clock_port)) {
1716                                 Log::getInstance()->log("Video", Log::DEBUG, "flush cmd clock shed failed");
1717                 }
1718
1719
1720
1721
1722                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
1723                                 omx_codec_input_port, NULL);
1724                 if (error != OMX_ErrorNone) {
1725                         Log::getInstance()->log("Video", Log::DEBUG,
1726                                         "OMX_Flush codec out failed %x", error);
1727
1728                 }
1729
1730
1731
1732
1733                 DestroyInputBufsOMX();
1734
1735                 //todo flushing
1736                 if (!DisablePort(omx_vid_sched,omx_shed_output_port,true)) {
1737                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 2 ");
1738                 }
1739                 if (!DisablePort(omx_vid_rend,omx_rend_input_port,true)) {
1740                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 1");
1741                 }
1742
1743
1744
1745
1746                 if (!DisablePort(omx_vid_dec,omx_codec_output_port,true)) {
1747                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 6");
1748                 }
1749
1750
1751
1752                 if (!DisablePort(omx_vid_dec,omx_codec_input_port,true)) {
1753                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 7");
1754                 }
1755
1756                 if (dodeint) {
1757                         if (!DisablePort(omx_vid_deint,omx_deint_output_port,true)) {
1758                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 6a");
1759                         }
1760
1761
1762
1763                         if (!DisablePort(omx_vid_deint,omx_deint_input_port,true)) {
1764                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 7a");
1765                         }
1766                 }
1767
1768
1769
1770                 if (!DisablePort(omx_vid_sched,omx_shed_input_port,true)) {
1771                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 3");
1772                 }
1773
1774                 if (!DisablePort(omx_vid_sched,omx_shed_clock_port,true)) {
1775                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 4");
1776                 }
1777
1778                 if (!DisablePort(omx_clock,omx_clock_output_port,true)) {
1779                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 5");
1780                 }
1781
1782
1783
1784
1785                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,NULL,NULL);
1786                 if (error!=OMX_ErrorNone) {
1787                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
1788
1789                 }
1790
1791                 if (dodeint) {
1792                         error=OMX_SetupTunnel(omx_vid_deint,omx_deint_input_port,NULL,NULL);
1793                         if (error!=OMX_ErrorNone) {
1794                                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
1795                         }
1796
1797
1798                         error=OMX_SetupTunnel(omx_vid_deint,omx_deint_output_port,NULL,NULL);
1799                         if (error!=OMX_ErrorNone) {
1800                                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
1801                         }
1802                 }
1803
1804                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_input_port,NULL,NULL);
1805                 if (error!=OMX_ErrorNone) {
1806                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
1807
1808                 }
1809
1810
1811                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_output_port,NULL,NULL);
1812                 if (error!=OMX_ErrorNone) {
1813                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
1814
1815                 }
1816
1817                 error=OMX_SetupTunnel(omx_vid_rend,omx_rend_input_port,NULL,NULL);
1818                 if (error!=OMX_ErrorNone) {
1819                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
1820
1821                 }
1822
1823
1824                 error=OMX_SetupTunnel(omx_clock,omx_clock_output_port,NULL,NULL);
1825                 if (error!=OMX_ErrorNone) {
1826                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
1827
1828                 }
1829
1830                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_clock_port,NULL,NULL);
1831                 if (error!=OMX_ErrorNone) {
1832                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
1833
1834                 }
1835
1836
1837
1838
1839                 error=OMX_FreeHandle(omx_vid_dec);
1840                 error=OMX_FreeHandle(omx_vid_sched);
1841                 error=OMX_FreeHandle(omx_vid_rend);
1842                 if (dodeint) error=OMX_FreeHandle(omx_vid_deint);
1843                 omx_vid_dec=NULL;
1844                 clock_mutex.Unlock();
1845                 destroyClock();
1846                 if (error!=OMX_ErrorNone) {
1847                         Log::getInstance()->log("Video", Log::DEBUG, "FreeHandle failed %d", error);
1848                 }
1849         } else  clock_mutex.Unlock();
1850           Log::getInstance()->log("Video", Log::DEBUG, "leave deallocate codecs OMX");
1851
1852         return 1;
1853 }
1854
1855
1856 void VideoOMX::destroyClock()
1857 {
1858         clock_mutex.Lock();
1859         if (clock_references>0) {
1860                 clock_references--;
1861                 if (clock_references==0) {
1862                         OMX_ERRORTYPE error;
1863                         Log::getInstance()->log("Video", Log::DEBUG, "destroy omx clock");
1864                         error=OMX_FreeHandle(omx_clock);
1865                         if (error!=OMX_ErrorNone) {
1866                                 Log::getInstance()->log("Video", Log::DEBUG, "FreeHandle failed %d", error);
1867                         }
1868
1869                 }
1870         }
1871         clock_mutex.Unlock();
1872
1873 }
1874
1875 int VideoOMX::stop()
1876 {
1877   if (!initted) return 0;
1878   iframemode=false;
1879
1880   //Check if libav mode
1881   DeAllocateCodecsOMX();
1882
1883
1884
1885
1886 //  if (ioctl(fdVideo, AV_SET_VID_STOP, 0) != 0) return 0;
1887   return 1;
1888 }
1889
1890 int VideoOMX::reset()
1891 {
1892   if (!initted) return 0;
1893
1894   iframemode=false;
1895   DeAllocateCodecsOMX();
1896 //  if (ioctl(fdVideo, AV_SET_VID_RESET, 0x11) != 0) return 0;
1897   return 1;
1898 }
1899
1900 int VideoOMX::pause()
1901 {
1902   if (!initted) return 0;
1903   Log::getInstance()->log("Video", Log::DEBUG, "enter pause");
1904   if (!paused) {
1905           paused=true;
1906           //maybe also change omx clock?
1907           pausetimecode=GetCurrentSystemTime();
1908
1909   }
1910   return 1;
1911 }
1912
1913 int VideoOMX::unPause() // FIXME get rid - same as play!! Not here!
1914 {
1915   if (!initted) return 0;
1916   Log::getInstance()->log("Video", Log::DEBUG, "enter unpause");
1917
1918   if (paused) {
1919           playbacktimeoffset+=GetCurrentSystemTime()-pausetimecode;
1920           paused=false; // may be also change omx clock
1921   }
1922
1923   return 1;
1924 }
1925
1926 int VideoOMX::fastForward()
1927 {
1928   if (!initted) return 0;
1929
1930 //  if (ioctl(fdVideo, AV_SET_VID_libavWD, 1) != 0) return 0;
1931   return 1;
1932 }
1933
1934 int VideoOMX::unFastForward()
1935 {
1936   if (!initted) return 0;
1937
1938 //  if (ioctl(fdVideo, AV_SET_VID_RESET, 0x11) != 0) return 0; // don't need this.
1939
1940  //// if (ioctl(fdVideo, AV_SET_VID_PLAY, 0) != 0) return 0;
1941   return 1;
1942 }
1943
1944 int VideoOMX::attachFrameBuffer()
1945 {
1946   if (!initted) return 0;
1947
1948 //  if (ioctl(fdVideo, AV_SET_VID_FB, 0) != 0) return 0;
1949   return 1;
1950 }
1951
1952 int VideoOMX::blank(void)
1953 {
1954 //  if (ioctl(fdVideo, AV_SET_VID_FB, 1) != 0) return 0;
1955 //  if (ioctl(fdVideo, AV_SET_VID_FB, 0) != 0) return 0;
1956   return 1;
1957 }
1958
1959 ULLONG VideoOMX::getCurrentTimestamp()
1960 {
1961   if (iframemode) return 0;
1962   return lastreftimePTS;
1963 }
1964
1965 // to be removed
1966 /*
1967 ULONG VideoOMX::timecodeToFrameNumber(ULLONG timecode)
1968 {
1969   if (format == PAL) return (ULONG)(((double)timecode / (double)90000) * (double)25);
1970   else               return (ULONG)(((double)timecode / (double)90000) * (double)30);
1971 }
1972
1973 */
1974 #ifdef DEV
1975 int VideoOMX::test()
1976 {
1977   return 0;
1978
1979 //  ULLONG stc = 0;
1980 //  return ioctl(fdVideo, AV_SET_VID_STC, &stc);
1981 /*
1982  // reset();
1983   return 1;
1984 */
1985 }
1986
1987 int VideoOMX::test2()
1988 {
1989   return 0;
1990 }
1991 #endif
1992
1993
1994
1995 long long VideoOMX::SetStartOffset(long long curreftime, bool *rsync)
1996 {
1997   *rsync=false;
1998   if (offsetnotset) {
1999     startoffset=curreftime;//offset is set for audio
2000     offsetnotset=false;
2001     offsetvideonotset=false;
2002   } else {
2003     if (offsetvideonotset) {
2004       offsetvideonotset=false;
2005       *rsync=true;
2006     } else {
2007       if ( (curreftime-lastrefvideotime)>10000000LL
2008         || (curreftime-lastrefvideotime)<-10000000LL) {//if pts jumps to big resync
2009         startoffset+=curreftime-lastrefvideotime;
2010         lastrefaudiotime+=curreftime-lastrefvideotime;
2011         //*rsync=true;
2012         offsetaudionotset=true;
2013
2014       }
2015     }
2016
2017   }
2018
2019   lastrefvideotime=curreftime;
2020
2021   return startoffset;
2022
2023 }
2024
2025 long long VideoOMX::SetStartAudioOffset(long long curreftime, bool *rsync)
2026 {
2027   *rsync=false;
2028   if (offsetnotset) {
2029     startoffset=curreftime;
2030     offsetnotset=false;
2031     offsetaudionotset=false;
2032   }else {
2033     if (offsetaudionotset) {
2034       offsetaudionotset=false;
2035       *rsync=true;
2036     } else {
2037       if ( (curreftime-lastrefaudiotime)>10000000LL
2038         || (curreftime-lastrefaudiotime)<-10000000LL) {//if pts jumps to big resync
2039         startoffset+=curreftime-lastrefaudiotime;
2040         lastrefvideotime+=curreftime-lastrefaudiotime;
2041         //*rsync=true;
2042         offsetvideonotset=true;
2043
2044       }
2045     }
2046
2047   }
2048   lastrefaudiotime=curreftime;
2049   return startoffset;
2050
2051 }
2052
2053 void VideoOMX::ResetTimeOffsets() {
2054   offsetnotset=true; //called from demuxer
2055   offsetvideonotset=true;
2056   offsetaudionotset=true;
2057   startoffset=0;
2058   lastrefaudiotime=0;
2059   lastrefvideotime=0;
2060   lastreftimeOMX=0;
2061   lastreftimePTS=0;
2062 }
2063
2064 long long VideoOMX::GetCurrentSystemTime()
2065 {
2066         struct timespec ts;
2067         clock_gettime(CLOCK_MONOTONIC, &ts);
2068         return ts.tv_sec*10000000LL+ts.tv_nsec/100LL;
2069 }
2070
2071 void VideoOMX::WaitUntil(long long time)
2072 {
2073         struct timespec interval;
2074         interval.tv_sec=time/10000000LL;
2075         interval.tv_nsec=(time %10000000LL)*100LL;
2076         while (clock_nanosleep(CLOCK_MONOTONIC,TIMER_ABSTIME,&interval,NULL)==EINTR) {
2077                 //Log::getInstance()->log("Video", Log::DEBUG, "Wait until multi");
2078
2079         };
2080 }
2081
2082 bool VideoOMX::FrameSkip(long long pts)
2083 {
2084         //ok first calculate the absolute time
2085         bool skip=false;
2086         long long target_time=pts-playbacktimeoffset;
2087         // we have to wait untile the next frame
2088         long long offset=Demuxer::getInstance()->getFrameRate();
2089         if (offset==0) offset=25;
2090         offset=-2*10000000LL/offset;
2091         target_time+=offset;
2092         long long current_time=GetCurrentSystemTime();
2093         if (!skipping) {
2094                 if ((target_time-current_time)<-400000LL) {
2095                         skip=true; // we are too slow
2096                         skipping=true;
2097                 /*      Log::getInstance()->log("Video", Log::DEBUG,
2098                                                                                                                 "Skipping frames1 %lld %lld %d",target_time-current_time,pts,Demuxer::getInstance()->getFrameRate());
2099                         Log::getInstance()->log("Video", Log::DEBUG, "skip detail pts: %lld target: %lld sys: %lld off: %lld diff %lld",pts,target_time,current_time,offset,
2100                                                 target_time-current_time);*/
2101                 }  else {
2102                         skipping=false;
2103                 }
2104         } else {
2105                 if ((target_time - current_time) < 0000LL) { //skip a bit more
2106                         skip = true; // we are too slow
2107                         skipping = true;
2108                 /*      Log::getInstance()->log("Video", Log::DEBUG,"Skipping frames2 %lld %lld %d",target_time-current_time,pts,Demuxer::getInstance()->getFrameRate());
2109                         Log::getInstance()->log("Video", Log::DEBUG, "skip detail pts: %lld target: %lld sys: %lld off: %lld diff %lld",pts,target_time,current_time,offset,
2110                                                                         target_time-current_time);*/
2111                 } else {
2112                         skipping = false;
2113                 }
2114
2115         }
2116
2117         return skip;
2118 }
2119
2120 void VideoOMX::FrameWaitforDisplay(long long pts)
2121 {
2122         //ok first calculate the absolute time
2123         long long target_time=pts-playbacktimeoffset;
2124         // we have to wait untile the next frame
2125         long long offset=Demuxer::getInstance()->getFrameRate();
2126         long long current_time=GetCurrentSystemTime();
2127         if (offset==0) offset=25;
2128         offset=-2*10000000LL/offset;
2129         target_time+=offset;
2130         //Log::getInstance()->log("Video", Log::DEBUG, "Wait for display pts: %lld tg: %lld sys: %lld off: %lld diff %lld po: %lld",pts,target_time,current_time,offset,
2131         //                      target_time-current_time,playbacktimeoffset);
2132         if ((target_time-current_time)>2000000LL) target_time=current_time+2000000LL; // something is wrong do not wait too long
2133         //Log::getInstance()->log("Video", Log::DEBUG, "Wait for display pts: %lld tg: %lld sys: %lld off: %lld diff %lld po: %lld",pts,target_time,current_time,offset,
2134         //              target_time-current_time,playbacktimeoffset);
2135
2136         WaitUntil(target_time);
2137         //Log::getInstance()->log("Video", Log::DEBUG, "Wait for display out %lld",GetCurrentSystemTime());
2138 }
2139
2140 void VideoOMX::AdjustAudioPTS(long long pts)
2141 {
2142         long long newplaybacktimeoffset=pts-GetCurrentSystemTime();
2143 /*      if ((newplaybacktimeoffset-1000000LL)>playbacktimeoffset
2144             || (newplaybacktimeoffset+1000000LL)<playbacktimeoffset) {
2145                 Log::getInstance()->log("Video", Log::DEBUG, "Adjust Playbackoffsettime o: %lld n: %lld",
2146                                 playbacktimeoffset,newplaybacktimeoffset);*/
2147                 playbacktimeoffset=newplaybacktimeoffset;
2148
2149         //}
2150 }
2151
2152 void VideoOMX::threadPostStopCleanup()
2153 {
2154         //Doing nothing
2155         //goo;
2156         Log::getInstance()->log("Video", Log::DEBUG,
2157                                                                                                 "end thread");
2158 }
2159
2160
2161 void VideoOMX::threadMethod()
2162 {
2163         Log::getInstance()->log("Video", Log::DEBUG,
2164                                                                                 "start thread");
2165         while (true) {
2166
2167                 OMX_BUFFERHEADERTYPE* pict=NULL;
2168                 long long time;
2169                 bool islast;
2170                 if (!paused) {
2171                         input_bufs_omx_mutex.Lock();
2172                         if (input_bufs_omx_present.size()>0) {
2173
2174                                 pict=input_bufs_omx_present.front();
2175                                 time=input_time_present.front();
2176                                 islast=input_is_last.front();
2177                                 input_bufs_omx_present.pop_front();
2178                                 input_time_present.pop_front();
2179                                 input_is_last.pop_front();
2180                         }
2181                         input_bufs_omx_mutex.Unlock();
2182                 }
2183
2184                 if ( pict) {
2185                         //Log::getInstance()->log("Video", Log::DEBUG,
2186                         //                                                                                      "Got pict");
2187                         if (time!=0 && FrameSkip(time) && !(pict->nFlags &OMX_BUFFERFLAG_STARTTIME)) {
2188
2189                                 input_bufs_omx_mutex.Lock();
2190                                 input_bufs_omx_free.push_back(pict);
2191                                 input_bufs_omx_mutex.Unlock();
2192                                 //Log::getInstance()->log("Video", Log::DEBUG, "threadMethod Frameskip");
2193
2194                         } else {
2195                         //      Log::getInstance()->log("Video", Log::DEBUG,
2196                         //                                                                                      "prot empty this buffer in");
2197                                 OMX_ERRORTYPE error = ProtOMXEmptyThisBuffer(omx_vid_dec, pict);
2198                                 if (error != OMX_ErrorNone) {
2199                                         Log::getInstance()->log("Video", Log::DEBUG,
2200                                                         "OMX_EmptyThisBuffer failed %x", error);
2201                                 }
2202                         //      Log::getInstance()->log("Video", Log::DEBUG,
2203                         //                                                                                                                      "prot empty this buffer out");
2204                                 if (deint_first_frame && dodeint) DeinterlaceFix();
2205                                 if (islast) FrameWaitforDisplay(time);
2206                         }
2207                 } else {
2208                         MILLISLEEP(5);
2209                 }
2210
2211                 threadCheckExit();
2212         }
2213         Log::getInstance()->log("Video", Log::DEBUG,
2214                                                                                         "end thread");
2215 }
2216
2217 void VideoOMX::DeinterlaceFix()
2218 {
2219
2220         Demuxer* demux=Demuxer::getInstance();
2221         clock_mutex.Lock();
2222         OMX_ERRORTYPE error;
2223         OMX_PARAM_PORTDEFINITIONTYPE port_def_type;
2224         memset(&port_def_type,0,sizeof(port_def_type));
2225         port_def_type.nSize=sizeof(port_def_type);
2226         port_def_type.nVersion.nVersion=OMX_VERSION;
2227         port_def_type.nPortIndex=omx_codec_output_port;
2228
2229         error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
2230         if (error != OMX_ErrorNone) {
2231                 Log::getInstance()->log("Video", Log::DEBUG,
2232                                 "OMX_IndexParamPortDefinition fix failed %x", error);
2233                 clock_mutex.Unlock();
2234                 return;
2235         }
2236
2237         if (port_def_type.format.video.nFrameWidth == demux->getHorizontalSize()
2238                         && port_def_type.format.video.nFrameHeight == demux->getVerticalSize()){
2239                 Log::getInstance()->log("Video", Log::DEBUG,
2240                                                         "Deinit first frame fix");
2241                 deint_first_frame=false;
2242
2243                 WaitForEvent(omx_vid_dec,OMX_EventPortSettingsChanged);
2244                 DisablePort(omx_vid_dec,omx_codec_output_port,false);
2245                 DisablePort(omx_vid_sched,omx_shed_input_port,false);
2246                 DisablePort(omx_vid_deint,omx_deint_output_port,false);
2247                 DisablePort(omx_vid_deint,omx_deint_input_port,false);
2248
2249                 port_def_type.nPortIndex=omx_deint_input_port;
2250                 error = OMX_SetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2251                                 &port_def_type);
2252                 if (error != OMX_ErrorNone) {
2253                         Log::getInstance()->log("Video", Log::DEBUG,
2254                                         "Set OMX_IndexParamPortDefinition1 failed %x", error);
2255                         clock_mutex.Unlock();
2256                         return;
2257                 }
2258
2259                 port_def_type.nPortIndex=omx_deint_output_port;
2260                 error = OMX_SetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2261                                 &port_def_type);
2262                 if (error != OMX_ErrorNone) {
2263                         Log::getInstance()->log("Video", Log::DEBUG,
2264                                         "Set OMX_IndexParamPortDefinition2 failed %x", error);
2265                         clock_mutex.Unlock();
2266                         return;
2267                 }
2268
2269
2270                 EnablePort(omx_vid_dec,omx_codec_output_port,false);
2271                 EnablePort(omx_vid_deint,omx_deint_input_port,false);
2272                 EnablePort(omx_vid_deint,omx_deint_output_port,false);
2273                 EnablePort(omx_vid_sched,omx_shed_input_port,false);
2274         }
2275         clock_mutex.Unlock();
2276
2277
2278 }
2279
2280
2281 void VideoOMX::PutBufferToPres(OMX_BUFFERHEADERTYPE* buffer, long long time,bool islast)
2282 {
2283         input_bufs_omx_mutex.Lock();
2284         input_bufs_omx_present.push_back(buffer);
2285         input_time_present.push_back(time);
2286         input_is_last.push_back(islast);
2287         input_bufs_omx_mutex.Unlock();
2288
2289 }
2290
2291 OMX_ERRORTYPE VideoOMX::ProtOMXEmptyThisBuffer(OMX_HANDLETYPE handle, OMX_BUFFERHEADERTYPE* buffer)
2292 {
2293         // protect the call to empty this buffer
2294         int oldcancelstate;
2295         int oldcanceltype;
2296         pthread_testcancel();
2297         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2298         pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2299         clock_mutex.Lock();
2300         OMX_ERRORTYPE ret_val;
2301         ret_val=OMX_EmptyThisBuffer(handle,buffer);
2302         clock_mutex.Unlock();
2303         pthread_setcancelstate(oldcancelstate, NULL);
2304         pthread_setcanceltype(oldcanceltype, NULL);
2305         pthread_testcancel();
2306         return ret_val;
2307 }
2308
2309 void VideoOMX::PrepareMediaSample(const MediaPacketList& mplist,UINT samplepos)
2310 {
2311         
2312         mediapackets.clear();
2313         list<MediaPacket>::const_iterator begin=mplist.begin();
2314         list<MediaPacket>::const_iterator itty=mplist.begin();
2315         advance(itty,min(mplist.size(),10));
2316         mediapackets.insert(mediapackets.begin(),begin,itty);//front
2317         
2318 }
2319
2320 UINT VideoOMX::DeliverMediaSample(UCHAR* buffer, UINT *samplepos)
2321 {
2322         int consumed=0;
2323         while (consumed<mediapackets.size()) {
2324             DeliverMediaPacket(mediapackets[consumed], buffer, samplepos);
2325             if (*samplepos == mediapackets[consumed].length) {
2326                 *samplepos = 0;
2327                 consumed++;
2328                 //return 1;
2329             } else return consumed;
2330         }
2331         return consumed;
2332 }
2333
2334 UINT VideoOMX::DeliverMediaPacket(MediaPacket packet,
2335                 const UCHAR* buffer,
2336                 UINT *samplepos)
2337 {
2338         if (packet.type == MPTYPE_VIDEO_H264)
2339         {
2340                 h264=true;
2341         }
2342         else
2343         {
2344                 h264=false;
2345         }
2346
2347
2348         //Later add fail back code for libav
2349 /*      if (!videoon) {
2350                 *samplepos+=packet.length;
2351                 return packet.length;
2352         }*/
2353
2354
2355         if (!omx_running) return 0; // if we are not runnig do not do this
2356         if (paused) return 0; //Block if we pause
2357
2358         if (packet.synched && FrameSkip(packet.presentation_time)) {
2359                 *samplepos=packet.length;
2360                 Log::getInstance()->log("Video", Log::DEBUG, "DeliverMediaPacketOMX Frameskip");
2361                                 *samplepos=packet.length;
2362                 return packet.length;
2363         }
2364         //long long current_media_time=GetCurrentSystemTime()+playbacktimeoffset;
2365 /*      if (packet.synched &&
2366                         (packet.presentation_time<0 /*|| // preroll skip frames
2367                         (packet.presentation_time+5000000LL)<(current_media_time)*)) { // we are late skip
2368                 Log::getInstance()->log("Video", Log::DEBUG, "DeliverMediaPacketOMX Preroll or too late %lld %lld; %lld", packet.presentation_time,current_media_time,playbacktimeoffset);
2369                 *samplepos=packet.length;
2370                 return packet.length;
2371         }*/
2372
2373         OMX_ERRORTYPE error;
2374
2375         /*First Check, if we have an video sample*/
2376         if (iframemode) {
2377                 //samplepos=0;
2378                 MILLISLEEP(10);
2379                 return 0; //Not in iframe mode!
2380         }
2381
2382         UINT headerstrip=0;
2383         if (packet.disconti) {
2384                 firstsynched=false;
2385                 if (cur_input_buf_omx) {
2386                         PutBufferToPres(cur_input_buf_omx, lastreftimeOMX,true);
2387                         cur_input_buf_omx=NULL;
2388                 }
2389         }
2390
2391         /*Inspect PES-Header */
2392
2393 //      OMX_STATETYPE temp_state;
2394 //      OMX_GetState(omx_vid_dec,&temp_state);
2395
2396         if (*samplepos==0) {//stripheader
2397                 headerstrip=buffer[packet.pos_buffer+8]+9/*is this right*/;
2398         //      if (h264) Log::getInstance()->log("Video", Log::DEBUG, "PES info %x %x %x %x",
2399         //                      buffer[packet.pos_buffer+0],buffer[packet.pos_buffer+1],buffer[packet.pos_buffer+2],buffer[packet.pos_buffer+3]);
2400                 *samplepos+=headerstrip;
2401                 if ( packet.synched ) {
2402                         if (cur_input_buf_omx) {
2403                                 cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_ENDOFFRAME;
2404                                 PutBufferToPres(cur_input_buf_omx, lastreftimeOMX,true);
2405                                 cur_input_buf_omx=NULL;//write out old data
2406
2407
2408                         }
2409                         firstsynched=true;
2410                 } else {
2411                         if (!firstsynched) {//
2412                                 *samplepos=packet.length;//if we have not processed at least one
2413                                 return packet.length;//synched packet ignore it!
2414                         }
2415                 }
2416         }
2417
2418         if (!cur_input_buf_omx) {
2419                 input_bufs_omx_mutex.Lock();
2420                 if (input_bufs_omx_free.size()==0) {
2421                         input_bufs_omx_mutex.Unlock();
2422                         //Log::getInstance()->log("Video", Log::DEBUG, "Deliver MediaPacket no free sample");
2423                         return 0; // we do not have a free media sample
2424
2425                 }
2426                 cur_input_buf_omx=input_bufs_omx_free.front();
2427                 cur_input_buf_omx->nFilledLen=0;
2428                 cur_input_buf_omx->nOffset=0;
2429                 cur_input_buf_omx->nTimeStamp=0;
2430                 input_bufs_omx_free.pop_front();
2431                 input_bufs_omx_mutex.Unlock();
2432         }
2433
2434
2435
2436
2437         if (cur_input_buf_omx->nFilledLen==0) {//will only be changed on first packet
2438                 if (packet.synched) {
2439                 //      Log::getInstance()->log("Video", Log::DEBUG, "packet synched marker");
2440
2441                         //lastreftimePTS=packet.pts;
2442                    if (omx_first_frame) { // TODO time
2443                            cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_STARTTIME;
2444                            Log::getInstance()->log("Video", Log::DEBUG, "Starttime");
2445                            omx_first_frame=false;
2446                    } else {
2447                            //cur_input_buf_omx->nFlags=0;
2448                            cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_TIME_UNKNOWN;
2449                    }
2450                    lastreftimeOMX=packet.presentation_time;
2451                   // Log::getInstance()->log("Video", Log::DEBUG, "Time code %lld pts %lld", lastreftimeOMX,packet.pts);
2452                    lastreftimePTS=packet.pts;
2453                    cur_input_buf_omx->nTimeStamp=0;//lastreftimeOMX; // the clock component is faulty;
2454                 }
2455                 else
2456                 {
2457                         cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_TIME_UNKNOWN;
2458                         cur_input_buf_omx->nTimeStamp=0;
2459                         //Log::getInstance()->log("Video", Log::DEBUG, "packet unsynched marker");
2460                         //  ms->SetSyncPoint(TRUE);
2461                 }
2462                 if (packet.disconti) cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_DISCONTINUITY;
2463
2464
2465
2466         }
2467         unsigned int haveToCopy=packet.length-*samplepos;
2468
2469         while (haveToCopy> (cur_input_buf_omx->nAllocLen-cur_input_buf_omx->nFilledLen)) {
2470                 //Log::getInstance()->log("Video", Log::DEBUG, "Big buffer %d %d %d",packet.length,cur_input_buf_omx->nAllocLen,cur_input_buf_omx->nFilledLen);
2471                 unsigned int cancopy=cur_input_buf_omx->nAllocLen-cur_input_buf_omx->nFilledLen;
2472                 memcpy(cur_input_buf_omx->pBuffer+cur_input_buf_omx->nFilledLen,buffer+packet.pos_buffer+*samplepos,cancopy);
2473                 haveToCopy-=cancopy;
2474                 cur_input_buf_omx->nFilledLen+=cancopy;
2475                 *samplepos+=cancopy;
2476                 // push old buffer out
2477
2478                 PutBufferToPres(cur_input_buf_omx, lastreftimeOMX,false);
2479                 cur_input_buf_omx=NULL;
2480                 // get5 new buffer
2481                 input_bufs_omx_mutex.Lock();
2482                 if (input_bufs_omx_free.size()==0) {
2483                         input_bufs_omx_mutex.Unlock();
2484                 //      Log::getInstance()->log("Video", Log::DEBUG, "Deliver MediaPacket no free sample2");
2485                         return *samplepos; // we do not have a free media sample
2486                 }
2487                 cur_input_buf_omx=input_bufs_omx_free.front();
2488                 cur_input_buf_omx->nFilledLen=0;
2489                 cur_input_buf_omx->nOffset=0;
2490                 cur_input_buf_omx->nTimeStamp=0;
2491                 input_bufs_omx_free.pop_front();
2492                 input_bufs_omx_mutex.Unlock();
2493
2494                 cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_TIME_UNKNOWN;
2495
2496         }
2497         memcpy(cur_input_buf_omx->pBuffer+cur_input_buf_omx->nFilledLen,
2498                         buffer+packet.pos_buffer+*samplepos,haveToCopy);
2499         cur_input_buf_omx->nFilledLen+=haveToCopy;
2500
2501
2502
2503         *samplepos+=haveToCopy;
2504
2505         return *samplepos;
2506
2507 }
2508
2509
2510
2511
2512 bool VideoOMX::displayIFrame(const UCHAR* buffer, UINT length) {
2513         if (!omx_running) return false;
2514         if (!iframemode)
2515                 EnterIframePlayback();
2516
2517         int haveToCopy = length;
2518
2519         if (!cur_input_buf_omx) {
2520                 input_bufs_omx_mutex.Lock();
2521                 if (input_bufs_omx_free.size() == 0) {
2522                         input_bufs_omx_mutex.Unlock();
2523                 //      Log::getInstance()->log("Video", Log::DEBUG,
2524                         //              "Deliver MediaPacket no free sample");
2525                         return false; // we do not have a free media sample
2526
2527                 }
2528                 cur_input_buf_omx = input_bufs_omx_free.front();
2529                 cur_input_buf_omx->nFilledLen = 0;
2530                 cur_input_buf_omx->nOffset = 0;
2531                 cur_input_buf_omx->nTimeStamp = 0;
2532                 input_bufs_omx_free.pop_front();
2533                 input_bufs_omx_mutex.Unlock();
2534         }
2535
2536         int read_pos = 0;
2537         unsigned int pattern, packet_length;
2538         unsigned int headerstrip = 0;
2539         bool first = true;
2540         if (length < 4){
2541                 return false;
2542         }
2543         //Now we strip the pes header
2544         pattern = (buffer[0] << 16) | (buffer[1] << 8) | (buffer[2]);
2545         while (read_pos + 7 <= length) {
2546                 pattern = ((pattern << 8) & 0xFFFFFFFF) | buffer[read_pos + 3];
2547                 if (pattern < 0x000001E0 || pattern > 0x000001EF) {
2548                         read_pos++;
2549                         continue;
2550                 } else {
2551                         headerstrip = buffer[read_pos + 8] + 9/*is this right*/;
2552                         packet_length = ((buffer[read_pos + 4] << 8)
2553                                         | (buffer[read_pos + 5])) + 6;
2554                         if (read_pos + packet_length > length)
2555                                 read_pos = length;
2556                         else {
2557                                 if ((headerstrip < packet_length)
2558                                                 && (cur_input_buf_omx->nFilledLen + packet_length
2559                                                                 - headerstrip) > cur_input_buf_omx->nAllocLen) {
2560                                         if (first) {
2561                                                 cur_input_buf_omx->nFlags = OMX_BUFFERFLAG_STARTTIME;
2562
2563                                         } else {
2564                                                 cur_input_buf_omx->nFlags
2565                                                                 |= OMX_BUFFERFLAG_TIME_UNKNOWN;
2566
2567                                         }
2568                                         cur_input_buf_omx->nTimeStamp = 0;
2569                                         PutBufferToPres(cur_input_buf_omx, 0,false);
2570                                         cur_input_buf_omx = NULL;
2571
2572                                         if (!cur_input_buf_omx) {
2573                                                 int count = 0;
2574                                                 while (count < 100 && omx_running && iframemode) {
2575                                                         count++;
2576
2577                                                         input_bufs_omx_mutex.Lock();
2578                                                         if (input_bufs_omx_free.size() == 0) {
2579                                                                 input_bufs_omx_mutex.Unlock();
2580                                         //                      Log::getInstance()->log("Video", Log::DEBUG,
2581                                                 //                              "Ifrane no free sample");
2582                                                                 MILLISLEEP(5);
2583                                                                 if (!omx_running) return false;
2584                                                                 continue;
2585                                                         }
2586                                                         cur_input_buf_omx = input_bufs_omx_free.front();
2587                                                         cur_input_buf_omx->nFilledLen = 0;
2588                                                         cur_input_buf_omx->nOffset = 0;
2589                                                         cur_input_buf_omx->nTimeStamp = 0;
2590                                                         input_bufs_omx_free.pop_front();
2591                                                         input_bufs_omx_mutex.Unlock();
2592                                                         break;
2593                                                 }
2594                                                 if (!cur_input_buf_omx)
2595                                                         return false;
2596                                         }
2597
2598                                 }
2599                                 if (packet_length > headerstrip) {
2600                                         memcpy(
2601                                                         cur_input_buf_omx->pBuffer
2602                                                                         + cur_input_buf_omx->nFilledLen,
2603                                                         buffer + read_pos + headerstrip,
2604                                                         packet_length - headerstrip);
2605                                         cur_input_buf_omx->nFilledLen += packet_length
2606                                                         - headerstrip;
2607                                 }
2608                                 read_pos += packet_length;
2609
2610                                 pattern = (buffer[read_pos] << 16)
2611                                                 | (buffer[read_pos + 1] << 8) | (buffer[read_pos + 2]);
2612                         }
2613                 }
2614         }
2615
2616         if (first) {
2617                 cur_input_buf_omx->nFlags = OMX_BUFFERFLAG_STARTTIME;
2618
2619         } else {
2620                 cur_input_buf_omx->nFlags |= OMX_BUFFERFLAG_TIME_UNKNOWN;
2621
2622         }
2623         cur_input_buf_omx->nTimeStamp = 0;
2624         PutBufferToPres(cur_input_buf_omx, 0,false);
2625         cur_input_buf_omx = NULL;
2626
2627
2628         MILLISLEEP(40); //Block a bit
2629         return true;
2630 }
2631
2632 int VideoOMX::EnterIframePlayback()
2633 {
2634         clock_mutex.Lock();
2635         if (cur_input_buf_omx) {
2636                 PutBufferToPres(cur_input_buf_omx, lastreftimeOMX,true);
2637
2638                 cur_input_buf_omx = NULL;
2639         }
2640         clock_mutex.Unlock();
2641         iframemode=true;
2642
2643         return 1;
2644 }
2645