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