]> git.vomp.tv Git - vompclient.git/blob - videoomx.cc
Rename Remote class to Input, RemoteLinux to InputLinux
[vompclient.git] / videoomx.cc
1 /*
2     Copyright 2004-2005 Chris Tallon, 2009-12 Marten Richter
3
4     This file is part of VOMP.
5
6     VOMP is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     VOMP is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with VOMP; if not, write to the Free Software
18     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19 */
20
21 #include "videoomx.h"
22 #include "audioomx.h"
23 #include "demuxer.h"
24 #include "vdr.h"
25 #include "woptionpane.h"
26 #include "osdopenvg.h"
27 #include "boxstack.h"
28 #include "input.h"
29
30 #include <bcm_host.h>
31
32 #include <linux/fb.h>
33
34 // temp
35 #include "log.h"
36
37 //A lot of parts of this file are heavily inspired by xbmc omx implementations
38
39 VideoOMX::VideoOMX() {
40
41         omx_running = false;
42
43         omx_vid_dec = 0;
44         cur_input_buf_omx = NULL;
45         omx_h264 = omx_mpeg2 = true;
46         clock_references = 0;
47
48         omx_vid_stalled = false;
49
50         offsetnotset = true;
51         offsetvideonotset = true;
52         offsetaudionotset = true;
53         startoffset = 0;
54         lastrefaudiotime = 0;
55         lastrefvideotime = 0;
56         lastreftimeOMX = 0;
57         lastreftimePTS = 0;
58         firstsynched = false;
59         cur_clock_time=0;
60         mpeg2_supported=false;
61         //cur_pts=0;
62
63         mode=NORMAL;
64         xpos=ypos=0.f;
65         deinterlace=2; //advanced
66
67         signalon=false;
68         outputinterlaced=0;
69
70         strcpy(L_VPE_OMX_CLOCK, VPE_OMX_CLOCK);
71         strcpy(L_VPE_OMX_H264_DECODER, VPE_OMX_H264_DECODER);
72         strcpy(L_VPE_OMX_MPEG2_DECODER, VPE_OMX_MPEG2_DECODER);
73         strcpy(L_VPE_OMX_VIDEO_SCHED, VPE_OMX_VIDEO_SCHED);
74         strcpy(L_VPE_OMX_VIDEO_REND, VPE_OMX_VIDEO_REND);
75         strcpy(L_VPE_OMX_VIDEO_DEINTERLACE, VPE_OMX_VIDEO_DEINTERLACE);
76 }
77
78 VideoOMX::~VideoOMX()
79 {
80   instance = NULL;
81 }
82
83 int VideoOMX::init(UCHAR tformat)
84 {
85   if (initted) return 0;
86   initted = 1;
87
88   int ret=vc_gencmd_send("codec_enabled MPG2");
89   if (ret!=0) {
90           Log::getInstance()->log("Video", Log::DEBUG, "vc_gencmd_send failed %x",ret);
91   } else {
92           char buffer[1024];
93           ret=vc_gencmd_read_response(buffer,sizeof(buffer));
94           if (ret!=0) {
95                   Log::getInstance()->log("Video", Log::DEBUG, "vc_gencmd_read_response failed %x",ret);
96           } else {
97                   if (STRCASECMP(buffer,"MPG2=enabled")==0) {
98                           mpeg2_supported=true;
99                   } else if (STRCASECMP(buffer,"MPG2=disabled")==0) {
100                           mpeg2_supported=false;
101                   } else {
102                           Log::getInstance()->log("Video", Log::DEBUG, "Undefined mpg codec answer %s",buffer);
103                   }
104           }
105   }
106
107   if (!setFormat(tformat))           { shutdown(); return 0; }
108   if (!setConnection(HDMI))  { shutdown(); return 0; }
109   if (!setAspectRatio(ASPECT4X3,12,11))    { shutdown(); return 0; }
110   if (!setMode(NORMAL))              { shutdown(); return 0; }
111   if (!setSource())                  { shutdown(); return 0; }
112   if (!attachFrameBuffer())          { shutdown(); return 0; }
113
114   setTVsize(ASPECT16X9);
115   selectVideoMode(0);
116
117
118   OMX_ERRORTYPE error;
119         error = OMX_Init();
120         if (error != OMX_ErrorNone) {
121                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX failed %x",
122                                 error);
123                 return 0;
124         }
125
126
127
128
129
130   //stop();
131
132
133
134   return 1;
135 }
136
137
138
139
140 OMX_ERRORTYPE VideoOMX::EventHandler_OMX(OMX_IN OMX_HANDLETYPE handle,OMX_IN OMX_PTR appdata,
141            OMX_IN OMX_EVENTTYPE event_type,OMX_IN OMX_U32 data1,
142            OMX_IN OMX_U32 data2,OMX_IN OMX_PTR event_data) {
143
144         //Log::getInstance()->log("Video", Log::NOTICE, "eventHandler %x %x %x %x %x",handle,event_type,data1,data2,event_data);
145
146         struct VPE_OMX_EVENT  new_event;
147         new_event.handle=handle;
148         new_event.appdata=appdata;
149         new_event.event_type=event_type;
150         new_event.data1=data1;
151         new_event.data2=data2;
152         new_event.event_data=event_data;
153
154         VideoOMX *video=(VideoOMX *)getInstance();
155         video->AddOmxEvent(new_event);
156
157 /*      switch (event_type) {
158         case OMX_EventCmdComplete: {
159
160         } break;
161         }*/
162
163         return OMX_ErrorNone;
164
165 }
166
167 void VideoOMX::AddOmxEvent(VPE_OMX_EVENT  new_event)
168 {
169         omx_event_mutex.Lock();
170     omx_events.push_back(new_event);
171         omx_event_mutex.Unlock();
172         omx_event_ready_signal.signal();
173 }
174
175
176 OMX_ERRORTYPE VideoOMX::EmptyBufferDone_OMX(OMX_IN OMX_HANDLETYPE hcomp,OMX_IN OMX_PTR appdata,OMX_IN OMX_BUFFERHEADERTYPE* buffer){
177
178 //      Log::getInstance()->log("Video", Log::NOTICE, "EmptyBufferDone");
179         VideoOMX *video=(VideoOMX *)getInstance();
180 /*      long long temp =buffer->nTimeStamp.nLowPart
181                                                                 | ((long long) buffer->nTimeStamp.nHighPart << 32);
182         Log::getInstance()->log("Video", Log::NOTICE, "EBD Video %lld  %x",temp,buffer->nFlags);*/
183         video->ReturnEmptyOMXBuffer(buffer);
184         return OMX_ErrorNone;
185
186 }
187
188 void VideoOMX::ReturnEmptyOMXBuffer(OMX_BUFFERHEADERTYPE* buffer){
189         input_bufs_omx_mutex.Lock();
190         //Log::getInstance()->log("Video", Log::NOTICE, "ReturnEmptyOMXBuffer %d %d",input_bufs_omx_free.size(),input_bufs_omx_all.size());
191         input_bufs_omx_free.push_back(buffer);
192         //Log::getInstance()->log("Video", Log::NOTICE, "ReturnEmptyOMXBuffer %d",input_bufs_omx_free.size());
193         input_bufs_omx_mutex.Unlock();
194         omx_event_ready_signal.signal();
195 }
196
197  OMX_ERRORTYPE VideoOMX::FillBufferDone_OMX(OMX_IN OMX_HANDLETYPE hcomp, OMX_IN OMX_PTR appdata,OMX_IN OMX_BUFFERHEADERTYPE* buffer) {
198          //Log::getInstance()->log("Video", Log::NOTICE, "FillBufferDone");
199         return OMX_ErrorNone;
200 }
201
202
203
204 int VideoOMX::shutdown()
205 {
206   if (!initted) return 0;
207   initted = 0;
208   Log::getInstance()->log("Video", Log::NOTICE, "Shutdown video module");
209
210   DeAllocateCodecsOMX();
211   OMX_Deinit();
212   //vc_tv_show_info(0); // back to console
213   // Restore console
214   int fd_fbset=0;
215   struct fb_var_screeninfo screeninfo;
216   fd_fbset=open("/dev/fb0",O_RDONLY);
217   if (fd_fbset<0) {
218           Log::getInstance()->log("Video", Log::CRIT, "Could not open frame buffer device %d", fd_fbset);
219           return 0;
220   }
221   if (ioctl(fd_fbset, FBIOGET_VSCREENINFO, &screeninfo)){
222           close(fd_fbset);
223           Log::getInstance()->log("Video", Log::CRIT, "Could not FBIOGET_VSCREENINFO frame buffer device");
224           return 0;
225   }
226   screeninfo.bits_per_pixel=8;
227   if (ioctl(fd_fbset, FBIOPUT_VSCREENINFO, &screeninfo)){
228           Log::getInstance()->log("Video", Log::CRIT, "Could not FBIOPUT_VSCREENINFO frame buffer device");
229   }
230   screeninfo.bits_per_pixel=16;
231   if (ioctl(fd_fbset, FBIOPUT_VSCREENINFO, &screeninfo)){
232           Log::getInstance()->log("Video", Log::CRIT, "Could not FBIOPUT_VSCREENINFO frame buffer device");
233   }
234   close(fd_fbset);
235   return 1;
236 }
237
238
239
240 bool VideoOMX::loadOptionsfromServer(VDR* vdr)
241 {
242         Log::getInstance()->log("Video", Log::DEBUG, "VideoOMX config load");
243     char *name=vdr->configLoad("VideoOMX","SDDeinterlacing");
244
245     if (name != NULL) {
246                 if (STRCASECMP(name, "None") == 0) {
247                         deinterlace = 0;
248                 }/* else if (STRCASECMP(name, "LineDouble") == 0) {
249                         deinterlace = 1;
250                 }*/ else if (STRCASECMP(name, "Advanced") == 0) {
251                         deinterlace = 2;
252                 } /*else if (STRCASECMP(name, "Crazy") == 0) {
253                         deinterlace = 3; // this does not activate deinterlacing but a image filter, just for fun
254                 }*/ else if (STRCASECMP(name, "Fast") == 0) {
255                         deinterlace = 4;
256                 }
257                 Log::getInstance()->log("Video", Log::DEBUG, "Set deinterlacing to %s %d",name,deinterlace);
258                 delete[] name;
259         }
260
261    return true;
262
263 }
264
265 bool VideoOMX::handleOptionChanges(Option* option)
266 {
267     if (Video::handleOptionChanges(option))
268                 return true;
269         switch (option->id) {
270         case 1: {
271                 if (STRCASECMP(option->options[option->userSetChoice], "None") == 0) {
272                         deinterlace = 0;
273                 } /*else if (STRCASECMP(option->options[option->userSetChoice], "LineDouble")
274                                 == 0) {
275                         deinterlace = 1;
276                 }*/ else if (STRCASECMP(option->options[option->userSetChoice], "Advanced")
277                                 == 0) {
278                         deinterlace = 2;
279                 } /*else if (STRCASECMP(option->options[option->userSetChoice], "Crazy")
280                                 == 0) {
281                         deinterlace = 3;
282                 }*/ else if (STRCASECMP(option->options[option->userSetChoice], "Fast")
283                         == 0) {
284                         deinterlace = 4;
285                 }
286                 Log::getInstance()->log("Video", Log::DEBUG, "Set deinterlacing to %s %d",option->options[option->userSetChoice],deinterlace);
287                 return true;
288         }
289         break;
290         };
291         return false;
292
293 }
294
295 bool VideoOMX::saveOptionstoServer()
296 {
297
298     switch (deinterlace) {
299         case 0:
300                 VDR::getInstance()->configSave("VideoOMX","SDDeinterlacing", "None");
301                 break;
302         /*case 1:
303                 VDR::getInstance()->configSave("VideoOMX","SDDeinterlacing", "LineDouble");
304                 break;*/
305         case 2:
306                 VDR::getInstance()->configSave("VideoOMX","SDDeinterlacing", "Advanced");
307                 break;
308         /*case 3:
309                 VDR::getInstance()->configSave("VideoOMX","SDDeinterlacing", "Crazy");
310                 break;*/
311         case 4:
312                 VDR::getInstance()->configSave("VideoOMX", "SDDeinterlacing", "Fast");
313                 break;
314         };
315
316     return true;
317 }
318
319 /*Option(UINT id, const char* displayText, const char* configSection, const char* configKey, UINT optionType,
320            UINT numChoices, UINT defaultChoice, UINT startInt,
321            const char * const * options, const char * const * optionkeys = NULL, AbstractOption* handler=NULL);*/
322
323 bool VideoOMX::addOptionsToPanes(int panenumber,Options *options,WOptionPane* pane)
324 {
325     if (!Video::addOptionsToPanes(panenumber,options,pane)) return false;
326
327
328     Option* option;
329     if (panenumber == 2)
330     {
331                 static const char* deinterlaceopts[] = { "None", "Fast",/*"LineDouble",*/"Advanced"/*,"Crazy"*/ };
332         option = new Option(1,tr("SD Deinterlacing"), "VideoOMX","SDDeinterlacing",Option::TYPE_TEXT,/*4,2*/3,2,0,deinterlaceopts,NULL,false,this);
333         options->push_back(option);
334         pane->addOptionLine(option);
335     }
336
337     return true;
338 }
339
340
341
342 int VideoOMX::setTVsize(UCHAR ttvsize)
343 {
344   if (tvsize!=ttvsize) pendingmodechange=true;
345   tvsize=ttvsize;
346   return 1;
347 }
348
349 UCHAR VideoOMX::getTVsize()       {
350         /*if (hdmi)*/
351         return ASPECT16X9; // in order that aspect ratio changes are reported
352         //return tvsize;
353 }
354
355 void VideoOMX::executePendingModeChanges()
356 {
357         if (pendingmodechange) {
358                 Log::getInstance()->log("Video", Log::NOTICE, "Execute pending mode change");
359                 Osd::getInstance()->shutdown();
360                 selectVideoMode(0);
361                 Osd::getInstance()->restore();
362                 Osd::getInstance()->init();
363                 BoxStack::getInstance()->redrawAllBoxes();
364                 initted = 1;
365         }
366 }
367
368 int VideoOMX::setDefaultAspect()
369 {
370   return setAspectRatio(tvsize,parx,pary);
371 }
372
373
374
375 int VideoOMX::setFormat(UCHAR tformat)
376 {
377   if (!initted) return 0;
378   if ((tformat != PAL) && (tformat != NTSC)
379                   && (tformat != PAL_M) && (tformat != NTSC_J)) return 0;
380   format = PAL;
381   tvsystem = tformat;
382
383   if (format == PAL)
384   {
385     screenWidth = 720;
386     screenHeight = 576;
387   }
388
389 //  selectVideoMode(0);
390
391   return 1;
392 }
393
394 void VideoOMX::selectVideoMode(int interlaced)
395 {
396         TV_GET_STATE_RESP_T tvstate;
397         vc_tv_get_state(&tvstate);
398
399         if ((tvstate.state & VC_HDMI_UNPLUGGED)) {
400                 hdmi = false;
401                 Log::getInstance()->log("Video", Log::NOTICE, "HDMI unplugged");
402         } else {
403                 hdmi = true;
404                 Log::getInstance()->log("Video", Log::NOTICE, "HDMI plugged");
405                 if (connection==COMPOSITERGB) {
406                         hdmi=false;
407                         Log::getInstance()->log("Video", Log::NOTICE, "SDTV set");
408                 } else {
409                         hdmi=true;
410                         Log::getInstance()->log("Video", Log::NOTICE, "HDMI set");
411                 }
412         }
413
414
415         if (hdmi) {
416                 TV_SUPPORTED_MODE_T all_supp_modes[200];
417                 HDMI_RES_GROUP_T pref_group;
418                 TV_SUPPORTED_MODE_T  *mymode=NULL;
419                 TV_SUPPORTED_MODE_T  *mymode_second_best=NULL;
420                 // bool got_optimum=false;
421                 uint32_t pref_mode;
422                 HDMI_RES_GROUP_T group=HDMI_RES_GROUP_CEA;
423                 int all_my_modes=vc_tv_hdmi_get_supported_modes(HDMI_RES_GROUP_CEA,
424                                 all_supp_modes,200,
425                                 &pref_group,&pref_mode);
426                 if (all_my_modes<=0) {
427                         group=HDMI_RES_GROUP_DMT;
428                         all_my_modes=vc_tv_hdmi_get_supported_modes(HDMI_RES_GROUP_DMT,
429                                         all_supp_modes,200,
430                                         &pref_group,&pref_mode);
431                         Log::getInstance()->log("Video", Log::NOTICE, "No CEA fall back to DMT modes ");
432                 }
433
434
435
436
437                 int target_fps=50;
438                 if (format==PAL)target_fps=50;
439                 else if (format==NTSC) target_fps=60;
440
441                 //Now first determine native resolution
442                 int native_width=1920;
443                 int native_height=1080;
444                 for (int i=0;i<all_my_modes;i++) {
445                         if (all_supp_modes[i].native) {
446                                 mymode=all_supp_modes+i;
447                                 Log::getInstance()->log("Video", Log::NOTICE, "Found native mode %dx%d %d Hz i: %d",
448                                                 mymode->width,mymode->height,mymode->frame_rate,mymode->scan_mode);
449                                 native_width=mymode->width;
450                                 native_height=mymode->height;
451                         }
452
453                 }
454                 //Now find the mode which matches best
455                 for (int i=0;i<all_my_modes;i++) {
456                         TV_SUPPORTED_MODE_T  *curmode=all_supp_modes+i;
457                         if (curmode->width==native_width &&
458                                         curmode->height==native_height &&
459                                         curmode->frame_rate==target_fps) {
460                                 if(curmode->scan_mode==interlaced) {
461                                         //got_optimum=true;
462                                         mymode=curmode;
463                                         Log::getInstance()->log("Video", Log::NOTICE, "Found optimum mode %dx%d %d Hz i: %d",
464                                                         mymode->width,mymode->height,mymode->frame_rate,mymode->scan_mode);
465                                 } else {
466                                         mymode_second_best=curmode;
467                                         Log::getInstance()->log("Video", Log::NOTICE, "Found close to optimum mode %dx%d %d Hz i: %d",
468                                                         mymode_second_best->width,mymode_second_best->height,
469                                                         mymode_second_best->frame_rate,mymode_second_best->scan_mode);
470                                 }
471
472                         }
473                 }
474                 Input::getInstance()->shutdown();
475                 vc_tv_power_off();
476                 if (mymode) {
477                         Log::getInstance()->log("Video", Log::NOTICE, "Switch to optimum mode");
478                         vc_tv_hdmi_power_on_explicit(HDMI_MODE_HDMI,group,mymode->code);
479                 } else if (mymode_second_best) {
480                         Log::getInstance()->log("Video", Log::NOTICE, "Switch to close to optimum mode");
481                         vc_tv_hdmi_power_on_explicit(HDMI_MODE_HDMI,group,mymode_second_best->code);
482                 } else {
483                         Log::getInstance()->log("Video", Log::NOTICE, "Switch to prefered mode");
484                         vc_tv_hdmi_power_on_best(1920,1080,target_fps,interlaced?HDMI_INTERLACED:HDMI_NONINTERLACED,
485                                         (EDID_MODE_MATCH_FLAG_T)(HDMI_MODE_MATCH_FRAMERATE|HDMI_MODE_MATCH_RESOLUTION|HDMI_MODE_MATCH_SCANMODE));
486                 }
487                 hdmi=true;
488                 outputinterlaced=interlaced;
489         } else {
490                 /* analog tv case */
491                 Log::getInstance()->log("Video", Log::NOTICE, "Analog tv case");
492                 Input::getInstance()->shutdown();
493                 vc_tv_power_off();
494                 SDTV_MODE_T setmode=SDTV_MODE_PAL;
495                 SDTV_OPTIONS_T options;
496
497                 switch (tvsize) {
498                 default:
499                 case ASPECT16X9:
500                         Log::getInstance()->log("Video", Log::NOTICE, "SDTV aspect 16:9");
501                         options.aspect=SDTV_ASPECT_16_9; break;
502                 case ASPECT4X3:
503                         Log::getInstance()->log("Video", Log::NOTICE, "SDTV aspect 4:3");
504                         options.aspect=SDTV_ASPECT_4_3; break;
505                 case ASPECT14X9:
506                         Log::getInstance()->log("Video", Log::NOTICE, "SDTV aspect 14:9");
507                         options.aspect=SDTV_ASPECT_14_9; break;
508                 };
509
510                 if (format==PAL) setmode=SDTV_MODE_PAL;
511                 else if (format==NTSC) setmode=SDTV_MODE_NTSC;
512                 else if (format==PAL_M)setmode=SDTV_MODE_PAL_M;
513                 else if (format==NTSC_J) setmode=SDTV_MODE_NTSC_J;
514                 vc_tv_sdtv_power_on(setmode,&options);
515                 hdmi=false;
516         }
517
518         Input::getInstance()->init("");
519
520
521         signalon=true;
522         pendingmodechange=false;
523
524 }
525
526
527 int VideoOMX::setConnection(UCHAR tconnection)
528 {
529   if (!initted) return 0;
530   if ((tconnection != COMPOSITERGB)  && (tconnection != HDMI)) return 0;
531   if (connection!=tconnection) pendingmodechange=true;
532   connection = tconnection;
533
534 //  if (ioctl(fdVideo, AV_SET_VID_OUTPUT, connection) != 0) return 0;
535   return 1;
536 }
537
538 int VideoOMX::setAspectRatio(UCHAR taspectRatio, int tparx,int tpary)
539 {
540   if (!initted) return 0;
541   //if ((taspectRatio != ASPECT4X3) && (taspectRatio != ASPECT16X9)) return 0;
542   aspectRatio = taspectRatio;
543   parx=tparx;
544   pary=tpary;
545
546   Log::getInstance()->log("Video", Log::DEBUG, "Setting aspect to %i: PAR %d %d", aspectRatio,parx,pary);
547
548   updateMode();
549 //  if (ioctl(fdVideo, AV_SET_VID_RATIO, aspectRatio) != 0) return 0;
550   return 1;
551 }
552
553 int VideoOMX::setMode(UCHAR tmode)
554 {
555   if (!initted) return 0;
556   if (tmode==LETTERBOX || tmode==NORMAL) mode=tmode;
557   updateMode();
558   return 1;
559 }
560
561 bool VideoOMX::setVideoDisplay(VideoDisplay display)
562 {
563         if (!initted) return false;
564         switch (display.mode)
565         {
566         case None: return true; //??
567         case Fullscreen: {
568                 windowed = false;
569
570         } break;
571         case Quarter: {
572                 windowed =true;
573                 xpos = ((float) display.x) / ((float) screenWidth);
574                 ypos = ((float) display.y) / ((float) screenHeight);
575                 width = 0.5f;
576                 height = 0.5f;
577         } break;
578
579         case Eighth: {
580                 windowed =true;
581                 xpos = ((float) display.x) / ((float) screenWidth);
582                 ypos = ((float) display.y) / ((float) screenHeight);
583                 width = 0.25f;
584                 height = 0.25f;
585         } break;
586
587         case Window: {
588                 windowed =true;
589                 xpos = ((float) display.x) / ((float) screenWidth);
590                 ypos = ((float) display.y) / ((float) screenHeight);
591                 width = ((float) display.width) / ((float) screenWidth);
592                 height = ((float) display.height) / ((float) screenHeight);
593         }break;
594         }
595         updateMode();
596         return true;
597 }
598
599
600 void VideoOMX::updateMode()
601 {
602         clock_mutex.Lock();
603         if (omx_running) {
604                 int oldcancelstate;
605                 int oldcanceltype;
606                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
607                 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
608                 OMX_ERRORTYPE error;
609                 OMX_CONFIG_DISPLAYREGIONTYPE dispconf;
610                 memset(&dispconf, 0, sizeof(dispconf));
611                 dispconf.nSize = sizeof(dispconf);
612                 dispconf.nVersion.nVersion = OMX_VERSION;
613                 dispconf.nPortIndex = omx_rend_input_port;
614                 dispconf.layer = 1;
615                 dispconf.set = OMX_DISPLAY_SET_LAYER;
616                 error = OMX_SetParameter(omx_vid_rend, OMX_IndexConfigDisplayRegion,
617                                 &dispconf);
618                 if (error != OMX_ErrorNone) {
619                         Log::getInstance()->log("Video", Log::DEBUG,
620                                         "Set OMX_IndexConfigDisplayRegion1 failed %x", error);
621                         pthread_setcancelstate(oldcancelstate, NULL);
622                         pthread_setcanceltype(oldcanceltype, NULL);
623                         clock_mutex.Unlock();
624                         return;
625                 }
626
627
628                 dispconf.pixel_x =parx;
629                 dispconf.pixel_y=pary;
630                 dispconf.set = OMX_DISPLAY_SET_PIXEL;
631                 error = OMX_SetParameter(omx_vid_rend, OMX_IndexConfigDisplayRegion,
632                                 &dispconf);
633                 if (error != OMX_ErrorNone) {
634                         Log::getInstance()->log("Video", Log::DEBUG,
635                                         "Set OMX_IndexConfigDisplayRegion5 failed %x", error);
636                         pthread_setcancelstate(oldcancelstate, NULL);
637                         pthread_setcanceltype(oldcanceltype, NULL);
638                         clock_mutex.Unlock();
639                         return;
640                 }
641
642
643
644                 dispconf.set = OMX_DISPLAY_SET_FULLSCREEN;
645                 if (!windowed) {
646                         //Set Fullscreen
647                         dispconf.fullscreen = OMX_TRUE;
648                 } else {
649                         dispconf.fullscreen = OMX_FALSE;
650                 }
651                 error = OMX_SetParameter(omx_vid_rend, OMX_IndexConfigDisplayRegion,
652                                 &dispconf);
653                 if (error != OMX_ErrorNone) {
654                         Log::getInstance()->log("Video", Log::DEBUG,
655                                         "Set OMX_IndexConfigDisplayRegion2 failed %x", error);
656                         pthread_setcancelstate(oldcancelstate, NULL);
657                         pthread_setcanceltype(oldcanceltype, NULL);
658                         clock_mutex.Unlock();
659                         return;
660                 }
661
662                 dispconf.set = OMX_DISPLAY_SET_MODE;
663                 if (!windowed) {
664                         dispconf.mode = (mode == NORMAL) ? OMX_DISPLAY_MODE_FILL
665                                         : OMX_DISPLAY_MODE_LETTERBOX;
666                 } else {
667                         dispconf.mode = OMX_DISPLAY_MODE_LETTERBOX;
668                 }
669                 error = OMX_SetParameter(omx_vid_rend, OMX_IndexConfigDisplayRegion,
670                                 &dispconf);
671                 if (error != OMX_ErrorNone) {
672                         Log::getInstance()->log("Video", Log::DEBUG,
673                                         "Set OMX_IndexConfigDisplayRegion3 failed %x", error);
674                         pthread_setcancelstate(oldcancelstate, NULL);
675                         pthread_setcanceltype(oldcanceltype, NULL);
676                         clock_mutex.Unlock();
677                         return;
678                 }
679
680                 if (windowed) {
681                         unsigned int display_width, display_height;
682                         display_width = display_height = 0;
683                         if (graphics_get_display_size(0, &display_width, &display_height)
684                                         < 0) {
685                                 Log::getInstance()->log("OSD", Log::WARN,
686                                                 "Getting display size failed! (BCM API) ");
687                                 pthread_setcancelstate(oldcancelstate, NULL);
688                                 pthread_setcanceltype(oldcanceltype, NULL);
689                                 clock_mutex.Unlock();
690                                 return;
691                         }
692                         //UnSetFullscreen with window
693                         dispconf.set = OMX_DISPLAY_SET_DEST_RECT;
694                         dispconf.dest_rect.x_offset
695                                         = (int) (xpos * ((float) display_width));
696                         dispconf.dest_rect.y_offset = (int) (ypos
697                                         * ((float) display_height));
698                         dispconf.dest_rect.width = (int) (width * ((float) display_width));
699                         dispconf.dest_rect.height = (int) (height * ((float) display_height));
700                         Log::getInstance()->log("Video", Log::DEBUG,
701                                                                         "Set dest_rect as %d %d %d %d", dispconf.dest_rect.x_offset,dispconf.dest_rect.y_offset,
702                                                                         dispconf.dest_rect.width , dispconf.dest_rect.height);
703
704                         error = OMX_SetParameter(omx_vid_rend,
705                                         OMX_IndexConfigDisplayRegion, &dispconf);
706                         if (error != OMX_ErrorNone) {
707                                 Log::getInstance()->log("Video", Log::DEBUG,
708                                                 "Set OMX_IndexConfigDisplayRegion failed %x", error);
709                                 pthread_setcancelstate(oldcancelstate, NULL);
710                                 pthread_setcanceltype(oldcanceltype, NULL);
711                                 clock_mutex.Unlock();
712                                 return;
713                         }
714                 }
715                 pthread_setcancelstate(oldcancelstate, NULL);
716                 pthread_setcanceltype(oldcanceltype, NULL);
717
718         }
719         clock_mutex.Unlock();
720 }
721
722 int VideoOMX::signalOff()
723 {
724         //TODO reinit osd
725         Log::getInstance()->log("Video", Log::NOTICE, "signalOff");
726         Osd::getInstance()->stopUpdate(); // turn off drawing thread
727         Input::getInstance()->shutdown();
728         vc_tv_power_off();
729         Input::getInstance()->init("");
730         signalon=false;
731     return 1;
732 }
733
734 int VideoOMX::signalOn()
735 {
736   if (!signalon)  {
737           Osd::getInstance()->shutdown();
738           Log::getInstance()->log("Video", Log::NOTICE, "signalOn");
739           selectVideoMode(0);
740           Osd::getInstance()->restore();
741           Osd::getInstance()->init();
742           BoxStack::getInstance()->redrawAllBoxes();
743           initted=1;
744
745   }
746   return 1;
747 }
748
749 int VideoOMX::setSource()
750 {
751   if (!initted) return 0;
752
753   // What does this do...
754 //  if (ioctl(fdVideo, AV_SET_VID_SRC, 1) != 0) return 0;
755   return 1;
756 }
757
758 int VideoOMX::setPosition(int x, int y) {
759         if (!initted)
760                 return 0;
761         xpos = ((float) x*2.f) / ((float) screenWidth);
762         ypos = ((float) y*2.f) / ((float) screenHeight);
763
764         updateMode();
765         return 1;
766 }
767
768 int VideoOMX::sync()
769 {
770   if (!initted) return 0;
771
772 //  if (ioctl(fdVideo, AV_SET_VID_SYNC, 2) != 0) return 0;
773   return 1;
774 }
775
776 void VideoOMX::interlaceSwitch4Demux() {
777         return;
778         Demuxer *demux=Demuxer::getInstance();
779
780         if (hdmi) { // only switch if hdmi and HD or interlaced SD material
781
782
783                 //OMX_Deinit();
784                 int set_interlaced=0;
785                 if (demux->getHorizontalSize()>720  && demux->getInterlaced()) {
786                         set_interlaced=1;
787                 }
788                 Log::getInstance()->log("Video", Log::NOTICE, "switch interlacing %d %d %d",demux->getInterlaced(),outputinterlaced,set_interlaced);
789                 if (outputinterlaced!=set_interlaced) {
790                         selectVideoMode(set_interlaced);
791                         Osd::getInstance()->shutdown();
792                         Osd::getInstance()->restore();
793                         Osd::getInstance()->init();
794                         BoxStack::getInstance()->redrawAllBoxes();
795                         initted=1;
796                 }
797                 //OMX_Init();
798
799
800         }
801
802
803 }
804
805
806 int VideoOMX::play() {
807         if (!initted)
808                 return 0;
809         iframemode = false;
810         Log::getInstance()->log("Video", Log::DEBUG, "enter play");
811
812         interlaceSwitch4Demux();
813
814         if (AllocateCodecsOMX()) {
815                 return 1;
816                 // Otherwise fall back to libav
817         } else {
818                 if (h264) {
819                         omx_h264 = false;
820                         Log::getInstance()->log("Video", Log::NOTICE,
821                                         "Allocate Codecs OMX failed assume h264 unsupported");
822                 } else {
823                         omx_mpeg2 = false;
824                         Log::getInstance()->log("Video", Log::NOTICE,
825                                         "Allocate Codecs OMX failed assume mpeg2 unsupported");
826                 }
827         }
828
829         return 0;
830
831 }
832
833
834 int VideoOMX::initClock()
835 {
836         OMX_ERRORTYPE error;
837         clock_mutex.Lock();
838         if (clock_references==0)
839         {
840
841                 static OMX_CALLBACKTYPE callbacks= {&EventHandler_OMX,&EmptyBufferDone_OMX,&FillBufferDone_OMX};
842                 omx_event_mutex.Lock();
843                 omx_events.clear();
844                 omx_event_mutex.Unlock();
845
846                 error=OMX_GetHandle(&omx_clock,L_VPE_OMX_CLOCK,NULL,&callbacks);
847
848                 if (error!=OMX_ErrorNone) {
849                         Log::getInstance()->log("Video", Log::DEBUG, "Init OMX clock failed %x", error);
850                         clock_mutex.Unlock();
851                         DeAllocateCodecsOMX();
852                         return 0;
853                 }
854
855                 /* TODO Clock config to separate method */
856                 OMX_PORT_PARAM_TYPE p_param;
857                 memset(&p_param,0,sizeof(p_param));
858                 p_param.nSize=sizeof(p_param);
859                 p_param.nVersion.nVersion=OMX_VERSION;
860                 error=OMX_GetParameter(omx_clock,OMX_IndexParamOtherInit,&p_param);
861                 if (error!=OMX_ErrorNone) {
862                         Log::getInstance()->log("Video", Log::DEBUG, "Init clock OMX_GetParameter failed %x", error);
863                         clock_mutex.Unlock();
864                         DeAllocateCodecsOMX();
865                         return 0;
866                 }
867                 omx_clock_output_port=p_param.nStartPortNumber;
868
869                 for (unsigned int i=0;i<p_param.nPorts;i++) {
870                         if (!DisablePort(omx_clock,p_param.nStartPortNumber+i,true) ) {
871                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX clock failed %d",i);
872                                 clock_mutex.Unlock();
873                                 DeAllocateCodecsOMX();
874                                 return 0;
875                         }
876                 }
877
878
879
880
881         }
882         Log::getInstance()->log("Video", Log::DEBUG, "init omx clock %x %x",this,omx_clock);
883         clock_references++;
884         clock_mutex.Unlock();
885         return 1;
886 }
887
888 int VideoOMX::getClockAudioandInit(OMX_HANDLETYPE *p_omx_clock,OMX_U32 *p_omx_clock_output_port)
889 {
890         OMX_ERRORTYPE error;
891         *p_omx_clock=NULL;
892         *p_omx_clock_output_port=0;
893
894         if (!initClock()) {
895                 return 0;
896         }
897         clock_mutex.Lock();
898
899         OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE refclock;
900         memset(&refclock,0,sizeof(refclock));
901         refclock.nSize=sizeof(refclock);
902         refclock.nVersion.nVersion=OMX_VERSION;
903
904         refclock.eClock=OMX_TIME_RefClockAudio;
905
906         //refclock.eClock=OMX_TIME_RefClockVideo;
907         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeActiveRefClock,&refclock);
908         if (error!=OMX_ErrorNone){
909                 Log::getInstance()->log("Video", Log::DEBUG, "Clock OMX_IndexConfigTimeActiveRefClock failed %x", error);
910                 clock_mutex.Unlock();
911                 DeAllocateCodecsOMX();
912                 return 0;
913         }
914
915         OMX_PORT_PARAM_TYPE p_param;
916         memset(&p_param,0,sizeof(p_param));
917         p_param.nSize=sizeof(p_param);
918         p_param.nVersion.nVersion=OMX_VERSION;
919         error=OMX_GetParameter(omx_clock,OMX_IndexParamOtherInit,&p_param);
920         if (error!=OMX_ErrorNone){
921                 Log::getInstance()->log("Video", Log::DEBUG, "Init clock OMX_GetParameter failed %x", error);
922                 clock_mutex.Unlock();
923                 DeAllocateCodecsOMX();
924                 return 0;
925         }
926
927         OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
928         memset(&clock_conf,0,sizeof(clock_conf));
929         clock_conf.nSize=sizeof(clock_conf);
930         clock_conf.nVersion.nVersion=OMX_VERSION;
931         clock_conf.eState=OMX_TIME_ClockStateWaitingForStartTime;
932         clock_conf.nStartTime=intToOMXTicks(0);
933         clock_conf.nOffset=intToOMXTicks(0);
934         if (clock_references==1) clock_conf.nWaitMask=OMX_CLOCKPORT1;
935         else clock_conf.nWaitMask=OMX_CLOCKPORT0|OMX_CLOCKPORT1;
936         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
937         if (error!=OMX_ErrorNone) {
938                 Log::getInstance()->log("Video", Log::DEBUG, "AuI Clock IndexConfigTimeClockState failed %x", error);
939         }
940
941
942         *p_omx_clock_output_port=p_param.nStartPortNumber+1;
943         *p_omx_clock=omx_clock;
944         clock_mutex.Unlock();
945         return 1;
946 }
947
948 int VideoOMX::getClockVideoandInit()
949 {
950         OMX_ERRORTYPE error;
951
952         if (!initClock()) {
953                 return 0;
954         }
955         clock_mutex.Lock();
956
957         if (clock_references==1) { // only if no audio is attached to this clock!
958                 OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE refclock;
959                 memset(&refclock,0,sizeof(refclock));
960                 refclock.nSize=sizeof(refclock);
961                 refclock.nVersion.nVersion=OMX_VERSION;
962
963                 //refclock.eClock=OMX_TIME_RefClockAudio;
964
965                 refclock.eClock=OMX_TIME_RefClockVideo;
966                 error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeActiveRefClock,&refclock);
967                 if (error!=OMX_ErrorNone) {
968                         Log::getInstance()->log("Video", Log::DEBUG, "Clock OMX_IndexConfigTimeActiveRefClock failed %x", error);
969                         clock_mutex.Unlock();
970                         DeAllocateCodecsOMX();
971                         return 0;
972                 }
973         }
974
975         OMX_PORT_PARAM_TYPE p_param;
976         memset(&p_param,0,sizeof(p_param));
977         p_param.nSize=sizeof(p_param);
978         p_param.nVersion.nVersion=OMX_VERSION;
979         error=OMX_GetParameter(omx_clock,OMX_IndexParamOtherInit,&p_param);
980         if (error!=OMX_ErrorNone){
981                 Log::getInstance()->log("Video", Log::DEBUG, "Init clock OMX_GetParameter failed %x", error);
982                 clock_mutex.Unlock();
983                 DeAllocateCodecsOMX();
984                 return 0;
985         }
986
987
988         OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
989         memset(&clock_conf,0,sizeof(clock_conf));
990         clock_conf.nSize=sizeof(clock_conf);
991         clock_conf.nVersion.nVersion=OMX_VERSION;
992         clock_conf.eState=OMX_TIME_ClockStateStopped;
993         clock_conf.nStartTime=intToOMXTicks(0);
994         clock_conf.nOffset=intToOMXTicks(0);
995         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
996         if (error!=OMX_ErrorNone) {
997                 Log::getInstance()->log("Video", Log::DEBUG, "VuI Clock IndexConfigTimeClockState failed %x", error);
998         }
999
1000
1001         memset(&clock_conf,0,sizeof(clock_conf));
1002         clock_conf.nSize=sizeof(clock_conf);
1003         clock_conf.nVersion.nVersion=OMX_VERSION;
1004         clock_conf.eState=OMX_TIME_ClockStateWaitingForStartTime;
1005         clock_conf.nStartTime=intToOMXTicks(0);
1006         clock_conf.nOffset=intToOMXTicks(0);
1007         if (clock_references==1) clock_conf.nWaitMask=OMX_CLOCKPORT0;
1008         else clock_conf.nWaitMask=OMX_CLOCKPORT0|OMX_CLOCKPORT1;
1009         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
1010         if (error!=OMX_ErrorNone) {
1011                 Log::getInstance()->log("Video", Log::DEBUG, "VuI Clock IndexConfigTimeClockState failed %x", error);
1012         }
1013
1014         omx_clock_output_port=p_param.nStartPortNumber;
1015         clock_mutex.Unlock();
1016
1017         return 1;
1018 }
1019
1020 void VideoOMX::clockUnpause()
1021 {
1022         OMX_ERRORTYPE error;
1023         Log::getInstance()->log("Video", Log::NOTICE, "enter Clockunpause");
1024         clock_mutex.Lock();
1025         if (clock_references>0 && clockpaused) {
1026                 OMX_TIME_CONFIG_SCALETYPE scale_type;
1027                 memset(&scale_type,0,sizeof(scale_type));
1028                 scale_type.nSize=sizeof(scale_type);
1029                 scale_type.nVersion.nVersion=OMX_VERSION;
1030                 scale_type.xScale=1<<16;
1031                 error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeScale,&scale_type);
1032                 if (error!=OMX_ErrorNone) {
1033                         Log::getInstance()->log("Video", Log::DEBUG, "ClockUnpause OMX_IndexConfigTimeScale failed %x", error);
1034                 }
1035                 Log::getInstance()->log("Video", Log::NOTICE, "set playback speed ClockUnpause");
1036                 clockpaused=false;
1037         }
1038         clock_mutex.Unlock();
1039 }
1040
1041
1042 void VideoOMX::clockPause()
1043 {
1044         OMX_ERRORTYPE error;
1045         Log::getInstance()->log("Video", Log::NOTICE, "enter ClockPause");
1046         clock_mutex.Lock();
1047         if (clock_references>0 && !clockpaused) {
1048                 OMX_TIME_CONFIG_SCALETYPE scale_type;
1049                 memset(&scale_type,0,sizeof(scale_type));
1050                 scale_type.nSize=sizeof(scale_type);
1051                 scale_type.nVersion.nVersion=OMX_VERSION;
1052                 scale_type.xScale=0;
1053                 error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeScale,&scale_type);
1054                 if (error!=OMX_ErrorNone) {
1055                         Log::getInstance()->log("Video", Log::DEBUG, "ClockPause OMX_IndexConfigTimeScale failed %x", error);
1056                 }
1057                 Log::getInstance()->log("Video", Log::NOTICE, "set playback speed ClockPause");
1058                 clockpaused=true;
1059         }
1060         clock_mutex.Unlock();
1061 }
1062
1063
1064
1065 int VideoOMX::AllocateCodecsOMX()
1066 {
1067         OMX_ERRORTYPE error;
1068         static OMX_CALLBACKTYPE callbacks= {&EventHandler_OMX,&EmptyBufferDone_OMX,&FillBufferDone_OMX};
1069
1070         Demuxer* demux=Demuxer::getInstance();
1071
1072         dodeint=false;
1073         first_frame=true;
1074
1075         Log::getInstance()->log("Video", Log::NOTICE, "Allocate Codecs OMX");
1076         //Clock, move later to audio including events
1077
1078         Log::getInstance()->log("Video", Log::NOTICE, "Deinter VideoType %d x %d i: %d", demux->getHorizontalSize(),demux->getVerticalSize(),demux->getInterlaced());
1079         if (deinterlace!=0 && /*(demux->getHorizontalSize()<=720 ) &&*/ demux->getInterlaced()) { 
1080                 dodeint=true;
1081
1082
1083                 Log::getInstance()->log("Video", Log::NOTICE, "Deinterlacing activated %d",deinterlace);
1084
1085         }
1086
1087
1088         if (!getClockVideoandInit()){
1089                 return 0;// get the clock and init it if necessary
1090         }
1091
1092
1093         if (!idleClock()) {
1094                 Log::getInstance()->log("Video", Log::DEBUG, "idleClock failed");
1095                 return 0;
1096         }
1097         /* TODO end */
1098
1099         clock_mutex.Lock();
1100         if (h264) {
1101                 error=OMX_GetHandle(&omx_vid_dec,L_VPE_OMX_H264_DECODER,NULL,&callbacks);
1102         } else {
1103                 error=OMX_GetHandle(&omx_vid_dec,L_VPE_OMX_MPEG2_DECODER,NULL,&callbacks);
1104         }
1105
1106         if (error!=OMX_ErrorNone){
1107                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video decoder failed %x", error);
1108                 clock_mutex.Unlock();
1109                 DeAllocateCodecsOMX();
1110                 return 0;
1111         }
1112
1113
1114         Log::getInstance()->log("Video", Log::DEBUG, "Nmark3 ");
1115         OMX_PORT_PARAM_TYPE p_param;
1116         memset(&p_param,0,sizeof(p_param));
1117         p_param.nSize=sizeof(p_param);
1118         p_param.nVersion.nVersion=OMX_VERSION;
1119         error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamVideoInit,&p_param);
1120         if (error!=OMX_ErrorNone){
1121                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX h264 decoder OMX_GetParameter failed %x", error);
1122                 clock_mutex.Unlock();
1123                 DeAllocateCodecsOMX();
1124             return 0;
1125         }
1126         omx_codec_input_port=p_param.nStartPortNumber;
1127         omx_codec_output_port=p_param.nStartPortNumber+1;
1128
1129         if (!DisablePort(omx_vid_dec,omx_codec_input_port) || !DisablePort(omx_vid_dec,omx_codec_output_port)) {
1130                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX video decoder failed");
1131                 clock_mutex.Unlock();
1132                 DeAllocateCodecsOMX();
1133                 return 0;
1134         }
1135
1136         Log::getInstance()->log("Video", Log::DEBUG, "Nmark4 ");
1137
1138         OMX_PARAM_BRCMVIDEODECODEERRORCONCEALMENTTYPE conceal;
1139         memset(&conceal,0,sizeof(conceal));
1140         conceal.nSize=sizeof(conceal);
1141         conceal.nVersion.nVersion=OMX_VERSION;
1142         conceal.bStartWithValidFrame=OMX_FALSE;
1143
1144         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamBrcmVideoDecodeErrorConcealment,&conceal);
1145         if (error!=OMX_ErrorNone){
1146                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_IndexParamBrcmVideoDecodeErrorConcealment failed %x", error);
1147                 clock_mutex.Unlock();
1148                 DeAllocateCodecsOMX();
1149                 return 0;
1150         }
1151
1152         if (dodeint) {
1153                 error = OMX_GetHandle(&omx_vid_deint, L_VPE_OMX_VIDEO_DEINTERLACE, NULL,
1154                                 &callbacks);
1155                 if (error != OMX_ErrorNone) {
1156                         Log::getInstance()->log("Video", Log::DEBUG,
1157                                         "Init OMX video deinterlacer failed %x", error);
1158                         clock_mutex.Unlock();
1159                         DeAllocateCodecsOMX();
1160                         return 0;
1161                 }
1162
1163                 error = OMX_GetParameter(omx_vid_deint, OMX_IndexParamImageInit,
1164                                 &p_param);
1165                 if (error != OMX_ErrorNone) {
1166                         Log::getInstance()->log("Video", Log::DEBUG,
1167                                         "Init OMX video deinterlacer OMX_GetParameter failed %x",
1168                                         error);
1169                         clock_mutex.Unlock();
1170                         DeAllocateCodecsOMX();
1171                         return 0;
1172                 }
1173                 omx_deint_input_port = p_param.nStartPortNumber;
1174                 omx_deint_output_port = p_param.nStartPortNumber + 1;
1175
1176                 if (!DisablePort(omx_vid_deint, omx_deint_input_port, true)
1177                                 || !DisablePort(omx_vid_deint, omx_deint_output_port, true)) {
1178                         Log::getInstance()->log("Video", Log::DEBUG,
1179                                         "Disable Ports OMX video deint failed");
1180                         clock_mutex.Unlock();
1181                         DeAllocateCodecsOMX();
1182                         return 0;
1183                 }
1184
1185         }
1186
1187
1188         error=OMX_GetHandle(&omx_vid_sched,L_VPE_OMX_VIDEO_SCHED,NULL,&callbacks);
1189         if (error!=OMX_ErrorNone){
1190                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video scheduler failed %x", error);
1191                 clock_mutex.Unlock();
1192                 DeAllocateCodecsOMX();
1193                 return 0;
1194         }
1195
1196
1197
1198         error=OMX_GetParameter(omx_vid_sched,OMX_IndexParamVideoInit,&p_param);
1199         if (error!=OMX_ErrorNone){
1200                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video scheduler OMX_GetParameter failed %x", error);
1201                 clock_mutex.Unlock();
1202                 DeAllocateCodecsOMX();
1203                 return 0;
1204         }
1205         omx_shed_input_port=p_param.nStartPortNumber;
1206         omx_shed_output_port=p_param.nStartPortNumber+1;
1207
1208
1209         error=OMX_GetParameter(omx_vid_sched,OMX_IndexParamOtherInit,&p_param);
1210         if (error!=OMX_ErrorNone){
1211                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video scheduler OMX_GetParameter failed %x", error);
1212                 clock_mutex.Unlock();
1213                 DeAllocateCodecsOMX();
1214                 return 0;
1215         }
1216         omx_shed_clock_port=p_param.nStartPortNumber;
1217         Log::getInstance()->log("Video", Log::DEBUG, "scheduler ports %d %d %d ",omx_shed_input_port,omx_shed_output_port,omx_shed_clock_port);
1218
1219
1220         if (!DisablePort(omx_vid_sched,omx_shed_input_port,true) || !DisablePort(omx_vid_sched,omx_shed_output_port,true)
1221                         || !DisablePort(omx_vid_sched,omx_shed_clock_port,true)) {
1222                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX video shed failed");
1223                 clock_mutex.Unlock();
1224                 DeAllocateCodecsOMX();
1225                 return 0;
1226         }
1227
1228
1229         error=OMX_GetHandle(&omx_vid_rend,L_VPE_OMX_VIDEO_REND,NULL,&callbacks);
1230         if (error!=OMX_ErrorNone){
1231                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video rend failed %x", error);
1232                 clock_mutex.Unlock();
1233                 DeAllocateCodecsOMX();
1234                 return 0;
1235         }
1236
1237         error=OMX_GetParameter(omx_vid_rend,OMX_IndexParamVideoInit,&p_param);
1238         if (error!=OMX_ErrorNone){
1239                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX video rend OMX_GetParameter failed %x", error);
1240                 clock_mutex.Unlock();
1241                 DeAllocateCodecsOMX();
1242                 return 0;
1243         }
1244         omx_rend_input_port=p_param.nStartPortNumber;
1245         //omx_rend_output_port=p_param.nStartPortNumber+1;
1246
1247
1248         if (!DisablePort(omx_vid_rend,omx_rend_input_port,true) /*|| !DisablePort(omx_vid_rend,omx_rend_output_port)*/
1249                                 ) {
1250                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Ports OMX video rend failed");
1251                 clock_mutex.Unlock();
1252                 DeAllocateCodecsOMX();
1253                 return 0;
1254         }
1255
1256         //Setuo chain
1257
1258
1259
1260         error=OMX_SetupTunnel(omx_clock,omx_clock_output_port,omx_vid_sched,omx_shed_clock_port);
1261         if (error!=OMX_ErrorNone){
1262                 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);
1263                 clock_mutex.Unlock();
1264                 DeAllocateCodecsOMX();
1265                 return 0;
1266         }
1267
1268         if (!EnablePort(omx_clock,omx_clock_output_port,false) || !EnablePort(omx_vid_sched,omx_shed_clock_port,false)
1269                                         ) {
1270                 Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX clock shed failed");
1271                 clock_mutex.Unlock();
1272                 DeAllocateCodecsOMX();
1273                 return 0;
1274         }
1275
1276
1277
1278         if (!ChangeComponentState(omx_vid_sched,OMX_StateIdle)) {
1279                 Log::getInstance()->log("Video", Log::DEBUG, "vid_sched idle ChangeComponentState");
1280                 clock_mutex.Unlock();
1281                 DeAllocateCodecsOMX();
1282                 return 0;
1283         }
1284
1285
1286
1287
1288         if ( !CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_clock_port)) {
1289                 clock_mutex.Unlock();
1290                 DeAllocateCodecsOMX();
1291                 return 0;
1292         }
1293
1294
1295
1296
1297
1298         if ( !CommandFinished(omx_clock,OMX_CommandPortEnable,omx_clock_output_port)) {
1299                 clock_mutex.Unlock();
1300                 DeAllocateCodecsOMX();
1301                 return 0;
1302         }
1303
1304
1305
1306 /*      error=OMX_SendCommand(omx_vid_dec,OMX_CommandStateSet,OMX_StateIdle,0);
1307         if (error!=OMX_ErrorNone){
1308                 Log::getInstance()->log("Video", Log::DEBUG, "vid_dec Send Command to OMX State Idle %x", error);
1309                 return 0;
1310         }*/
1311
1312         OMX_VIDEO_PARAM_PORTFORMATTYPE ft_type;
1313         memset(&ft_type,0,sizeof(ft_type));
1314         ft_type.nSize=sizeof(ft_type);
1315         ft_type.nVersion.nVersion=OMX_VERSION;
1316
1317         ft_type.nPortIndex=omx_codec_input_port;
1318         if (h264) {
1319                 ft_type.eCompressionFormat=OMX_VIDEO_CodingAVC;
1320         } else {
1321                 ft_type.eCompressionFormat=OMX_VIDEO_CodingMPEG2;
1322         }
1323
1324
1325
1326     ft_type.xFramerate=0*(1<<16);//25*(1<<16);//demux->getFrameRate()*(1<<16);
1327     Log::getInstance()->log("Video", Log::DEBUG, "Framerate: %d",demux->getFrameRate());
1328         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamVideoPortFormat,&ft_type);
1329         if (error!=OMX_ErrorNone){
1330                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexParamVideoPortFormat failed %x", error);
1331                 clock_mutex.Unlock();
1332                 DeAllocateCodecsOMX();
1333                 return 0;
1334         }
1335
1336
1337         if (!ChangeComponentState(omx_vid_dec,OMX_StateIdle)) {
1338                 Log::getInstance()->log("Video", Log::DEBUG, "vid_dec ChangeComponentState");
1339                 clock_mutex.Unlock();
1340                 DeAllocateCodecsOMX();
1341                 return 0;
1342         }
1343
1344         OMX_CONFIG_BUFFERSTALLTYPE stall_conf;
1345         memset(&stall_conf,0,sizeof(stall_conf));
1346         stall_conf.nSize=sizeof(stall_conf);
1347         stall_conf.nVersion.nVersion=OMX_VERSION;
1348         stall_conf.nPortIndex=omx_codec_output_port;
1349         stall_conf.nDelay=1500*1000;
1350         error=OMX_SetConfig(omx_vid_dec,OMX_IndexConfigBufferStall,&stall_conf);
1351         if (error!=OMX_ErrorNone){
1352                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigBufferStall failed %x", error);
1353                 clock_mutex.Unlock();
1354                 DeAllocateCodecsOMX();
1355                 return 0;
1356         }
1357         omx_vid_stalled = false;
1358
1359         OMX_CONFIG_REQUESTCALLBACKTYPE req_callback;
1360         memset(&req_callback,0,sizeof(req_callback));
1361         req_callback.nSize=sizeof(req_callback);
1362         req_callback.nVersion.nVersion=OMX_VERSION;
1363         req_callback.nPortIndex=omx_codec_output_port;
1364         req_callback.nIndex=OMX_IndexConfigBufferStall;
1365         req_callback.bEnable=OMX_TRUE;
1366         error=OMX_SetConfig(omx_vid_dec,OMX_IndexConfigRequestCallback,&req_callback);
1367         if (error!=OMX_ErrorNone){
1368                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigRequestCallback  failed %x", error);
1369                 clock_mutex.Unlock();
1370                 DeAllocateCodecsOMX();
1371                 return 0;
1372         }
1373
1374
1375
1376         if (!PrepareInputBufsOMX()) {
1377                 clock_mutex.Unlock();
1378                 DeAllocateCodecsOMX();
1379                 return 0;
1380         }
1381
1382         if (!dodeint) {
1383                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,omx_vid_sched,omx_shed_input_port);
1384                 if (error!=OMX_ErrorNone){
1385                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel dec to sched failed %x", error);
1386                         clock_mutex.Unlock();
1387                         DeAllocateCodecsOMX();
1388                         return 0;
1389                 }
1390
1391
1392
1393                 if (!EnablePort(omx_vid_dec,omx_codec_output_port,false) || !EnablePort(omx_vid_sched,omx_shed_input_port,false)
1394                 ) {
1395                         Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX codec shed failed");
1396                         clock_mutex.Unlock();
1397                         DeAllocateCodecsOMX();
1398                         return 0;
1399                 }
1400
1401                 if ( !CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_output_port) || !CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_input_port)) {
1402                         clock_mutex.Unlock();
1403                         DeAllocateCodecsOMX();
1404                         return 0;
1405                 }
1406
1407         } else {
1408
1409                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,omx_vid_deint,omx_deint_input_port);
1410                 if (error!=OMX_ErrorNone){
1411                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel dec to deint failed %x", error);
1412                         clock_mutex.Unlock();
1413                         DeAllocateCodecsOMX();
1414                         return 0;
1415                 }
1416
1417
1418
1419                 if (!EnablePort(omx_vid_dec,omx_codec_output_port,false) || !EnablePort(omx_vid_deint,omx_deint_input_port,false)
1420                 ) {
1421                         Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX codec deint failed");
1422                         clock_mutex.Unlock();
1423                         DeAllocateCodecsOMX();
1424                         return 0;
1425                 }
1426
1427                 if ( !CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_output_port) || !CommandFinished(omx_vid_deint,OMX_CommandPortEnable,omx_deint_input_port)) {
1428                         clock_mutex.Unlock();
1429                         DeAllocateCodecsOMX();
1430                         return 0;
1431                 }
1432
1433                 if (!ChangeComponentState(omx_vid_deint,OMX_StateIdle)) {
1434                         Log::getInstance()->log("Video", Log::DEBUG, "vid_deint ChangeComponentState");
1435                         clock_mutex.Unlock();
1436                         DeAllocateCodecsOMX();
1437                         return 0;
1438                 }
1439
1440                 OMX_CONFIG_IMAGEFILTERPARAMSTYPE imagefilter;
1441                 memset(&imagefilter,0,sizeof(imagefilter));
1442                 imagefilter.nSize=sizeof(imagefilter);
1443                 imagefilter.nVersion.nVersion=OMX_VERSION;
1444
1445                 imagefilter.nPortIndex=omx_deint_output_port;
1446                 imagefilter.nNumParams=4;
1447                 imagefilter.nParams[0]=3;//???
1448                 imagefilter.nParams[1]=0;//default frame interval
1449                 imagefilter.nParams[2]=0;// frame rate
1450                 if (demux->getHorizontalSize() <= 720){
1451                         imagefilter.nParams[3] = 1;//use qpus
1452                 }
1453                 else 
1454                 {
1455                         imagefilter.nParams[3] = 0;//use qpus
1456                 }
1457
1458                 switch (deinterlace) {
1459                 case 1:
1460                         imagefilter.eImageFilter=OMX_ImageFilterDeInterlaceLineDouble; break;
1461                 case 2:
1462                         imagefilter.eImageFilter=OMX_ImageFilterDeInterlaceAdvanced; break;
1463                 case 3:
1464                         imagefilter.eImageFilter=OMX_ImageFilterFilm; break;
1465                 case 4:
1466                         imagefilter.eImageFilter = OMX_ImageFilterDeInterlaceFast; break;
1467                 }
1468
1469
1470                 error=OMX_SetConfig(omx_vid_deint,OMX_IndexConfigCommonImageFilterParameters,&imagefilter);
1471                 if (error!=OMX_ErrorNone){
1472                         Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigCommonImageFilterParameters failed %x", error);
1473                         clock_mutex.Unlock();
1474                         DeAllocateCodecsOMX();
1475                         return 0;
1476                 }
1477
1478
1479                 error=OMX_SetupTunnel(omx_vid_deint,omx_deint_output_port,omx_vid_sched,omx_shed_input_port);
1480                 if (error!=OMX_ErrorNone){
1481                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel deint to sched failed %x", error);
1482                         clock_mutex.Unlock();
1483                         DeAllocateCodecsOMX();
1484                         return 0;
1485                 }
1486
1487                 if (!EnablePort(omx_vid_deint,omx_deint_output_port,false) || !EnablePort(omx_vid_sched,omx_shed_input_port,false)
1488                 ) {
1489                         Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX deint shed failed");
1490                         clock_mutex.Unlock();
1491                         DeAllocateCodecsOMX();
1492                         return 0;
1493                 }
1494
1495                 if ( !CommandFinished(omx_vid_deint,OMX_CommandPortEnable,omx_deint_output_port) || !CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_input_port)) {
1496                         clock_mutex.Unlock();
1497                         DeAllocateCodecsOMX();
1498                         return 0;
1499                 }
1500
1501         }
1502
1503         if (!ChangeComponentState(omx_vid_dec,OMX_StateExecuting)) {
1504                 Log::getInstance()->log("Video", Log::DEBUG, "omx_vid_dec ChangeComponentState Execute");
1505                 clock_mutex.Unlock();
1506                 DeAllocateCodecsOMX();
1507                 return 0;
1508         }
1509
1510         error=OMX_SetupTunnel(omx_vid_sched,omx_shed_output_port,omx_vid_rend,omx_rend_input_port);
1511         if (error!=OMX_ErrorNone){
1512                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel  sched to rend failed %x", error);
1513                 clock_mutex.Unlock();
1514                 DeAllocateCodecsOMX();
1515                 return 0;
1516         }
1517
1518         if (!EnablePort(omx_vid_sched,omx_shed_output_port,false) || !EnablePort(omx_vid_rend,omx_rend_input_port,false)
1519                                                         ) {
1520                 Log::getInstance()->log("Video", Log::DEBUG, "Enable Ports OMX  shed rend failed");
1521                 clock_mutex.Unlock();
1522                 DeAllocateCodecsOMX();
1523                 return 0;
1524         }
1525
1526         if (!CommandFinished(omx_vid_sched,OMX_CommandPortEnable,omx_shed_output_port)
1527                                         || !CommandFinished(omx_vid_rend,OMX_CommandPortEnable,omx_rend_input_port)) {
1528                 clock_mutex.Unlock();
1529                 DeAllocateCodecsOMX();
1530                 return 0;
1531         }
1532
1533         if (!ChangeComponentState(omx_vid_rend,OMX_StateIdle)) {
1534                 Log::getInstance()->log("Video", Log::DEBUG, "vid_rend ChangeComponentState");
1535                 clock_mutex.Unlock();
1536                 DeAllocateCodecsOMX();
1537                 return 0;
1538         }
1539
1540         if (dodeint) {
1541                 if (!ChangeComponentState(omx_vid_deint,OMX_StateExecuting)) {
1542                         Log::getInstance()->log("Video", Log::DEBUG, "vid_vid_deint ChangeComponentState");
1543                         clock_mutex.Unlock();
1544                         DeAllocateCodecsOMX();
1545                         return 0;
1546                 }
1547                 DisablePort(omx_vid_deint,omx_deint_output_port,false);
1548                 DisablePort(omx_vid_deint,omx_deint_input_port,false);
1549         }
1550
1551         if (!ChangeComponentState(omx_vid_sched,OMX_StateExecuting)) {
1552                 Log::getInstance()->log("Video", Log::DEBUG, "omx_vid_sched ChangeComponentState Execute");
1553                 clock_mutex.Unlock();
1554                 DeAllocateCodecsOMX();
1555                 return 0;
1556         }
1557
1558         if (!ChangeComponentState(omx_vid_rend,OMX_StateExecuting)) {
1559                 Log::getInstance()->log("Video", Log::DEBUG, "omx_vid_rend ChangeComponentState Execute");
1560                 clock_mutex.Unlock();
1561                 DeAllocateCodecsOMX();
1562                 return 0;
1563         }
1564
1565         //raspbi specifif
1566         /*OMX_CONFIG_DISPLAYREGIONTYPE dispconf;
1567         memset(&dispconf,0,sizeof(dispconf));
1568         dispconf.nSize=sizeof(dispconf);
1569         dispconf.nVersion.nVersion=OMX_VERSION;
1570
1571         dispconf.nPortIndex=omx_rend_input_port;
1572
1573         dispconf.set=OMX_DISPLAY_SET_LAYER ;
1574         dispconf.layer=1;
1575         error=OMX_SetConfig(omx_vid_rend,OMX_IndexConfigDisplayRegion,&dispconf);
1576         if (error!=OMX_ErrorNone){
1577                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigDisplayRegion failed %x", error);
1578                 clock_mutex.Unlock();
1579                 DeAllocateCodecsOMX();
1580                 return 0;
1581         }*/
1582
1583 /*      dispconf.set=OMX_DISPLAY_SET_FULLSCREEN ;
1584         dispconf.fullscreen=OMX_FALSE;
1585         error=OMX_SetParameter(omx_vid_rend,OMX_IndexConfigDisplayRegion,&dispconf);
1586         if (error!=OMX_ErrorNone){
1587                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigDisplayRegion failed %x", error);
1588                 clock_mutex.Unlock();
1589                 DeAllocateCodecsOMX();
1590                 return 0;
1591         }
1592
1593         dispconf.set=OMX_DISPLAY_SET_DEST_RECT;
1594         dispconf.dest_rect.x_offset=100;
1595         dispconf.dest_rect.y_offset=100;
1596         dispconf.dest_rect.width=640;
1597         dispconf.dest_rect.height=480;
1598         error=OMX_SetParameter(omx_vid_rend,OMX_IndexConfigDisplayRegion,&dispconf);
1599         if (error!=OMX_ErrorNone){
1600                 Log::getInstance()->log("Video", Log::DEBUG, "Init OMX_IndexConfigDisplayRegion failed %x", error);
1601                 clock_mutex.Unlock();
1602                 DeAllocateCodecsOMX();
1603                 return 0;
1604         }*/
1605
1606
1607         //playbacktimeoffset=-GetCurrentSystemTime();
1608
1609         iframemode=false;
1610         omx_running=true;
1611         clock_mutex.Unlock();
1612         clockUnpause();
1613         updateMode();
1614
1615         setClockExecutingandRunning();
1616
1617
1618
1619
1620
1621         return 1;
1622 }
1623
1624 int VideoOMX::idleClock()
1625 {
1626         //OMX_ERRORTYPE error;
1627         OMX_STATETYPE temp_state;
1628         clock_mutex.Lock();
1629         OMX_GetState(omx_clock,&temp_state);
1630
1631         if (temp_state!=OMX_StateIdle) {
1632                 if (!ChangeComponentState(omx_clock,OMX_StateIdle)) {
1633                         Log::getInstance()->log("Video", Log::DEBUG, "omx_clock ChangeComponentState Idle failed");
1634                         clock_mutex.Unlock();
1635                         return 0;
1636                 }
1637         }
1638         clock_mutex.Unlock();
1639         return 1;
1640 }
1641
1642 int VideoOMX::setClockExecutingandRunning()
1643 {
1644         OMX_ERRORTYPE error;
1645         OMX_STATETYPE temp_state;
1646         clock_mutex.Lock();
1647         OMX_GetState(omx_clock,&temp_state);
1648
1649         if (temp_state!=OMX_StateExecuting) {
1650                 if (!ChangeComponentState(omx_clock,OMX_StateExecuting)) {
1651                         Log::getInstance()->log("Video", Log::DEBUG, "omx_clock ChangeComponentState Execute failed");
1652                         clock_mutex.Unlock();
1653                         DeAllocateCodecsOMX();
1654                         return 0;
1655                 }
1656         }
1657
1658         OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
1659         memset(&clock_conf,0,sizeof(clock_conf));
1660         clock_conf.nSize=sizeof(clock_conf);
1661         clock_conf.nVersion.nVersion=OMX_VERSION;
1662         clock_conf.eState=OMX_TIME_ClockStateRunning;
1663         error=OMX_SetConfig(omx_clock,OMX_IndexConfigTimeClockState,&clock_conf);
1664         if (error!=OMX_ErrorNone) {
1665                 Log::getInstance()->log("Video", Log::DEBUG, "Clock IndexConfigTimeClockState failed %x", error);
1666                 clock_mutex.Unlock();
1667                 DeAllocateCodecsOMX();
1668                 return 0;
1669         }
1670         clock_mutex.Unlock();
1671         return 1;
1672
1673 }
1674
1675
1676 int VideoOMX::ChangeComponentState(OMX_HANDLETYPE handle,OMX_STATETYPE type,bool wait) //needs to be called with locked mutex
1677 {
1678         OMX_ERRORTYPE error;
1679         error=OMX_SendCommand(handle,OMX_CommandStateSet,type,0);
1680         if (error!=OMX_ErrorNone){
1681                 Log::getInstance()->log("Video", Log::DEBUG, "handle %x Send Command to OMX State %x %x",handle,type, error);
1682                 return 0;
1683         }
1684
1685         if (wait) {
1686                 if (!CommandFinished(handle,OMX_CommandStateSet,type)) {
1687                         return 0;
1688                 }
1689         }
1690
1691         return 1;
1692 }
1693
1694
1695 int VideoOMX::EnablePort(OMX_HANDLETYPE handle,OMX_U32 port,bool wait) //needs to be called with locked mutex
1696 {
1697         OMX_ERRORTYPE error;
1698         bool skip=false;
1699
1700         OMX_PARAM_PORTDEFINITIONTYPE pdt;
1701         memset(&pdt,0,sizeof(pdt));
1702         pdt.nSize=sizeof(pdt);
1703         pdt.nVersion.nVersion=OMX_VERSION;
1704         pdt.nPortIndex=port;
1705         error=OMX_GetParameter(handle,OMX_IndexParamPortDefinition, &pdt);
1706         if (error==OMX_ErrorNone) {
1707                 if(pdt.bEnabled==OMX_TRUE) {
1708                         skip=true; //already disabled;
1709                 }
1710
1711         }
1712
1713         if (!skip) {
1714                 error=OMX_SendCommand(handle,OMX_CommandPortEnable,port,0);
1715                 if (error!=OMX_ErrorNone){
1716                         Log::getInstance()->log("Video", Log::DEBUG, "handle %x Send Command to enable port %x %x",handle,port, error);
1717                         return 0;
1718                 }
1719
1720                 if (!wait) return 1;
1721                 if (!CommandFinished(handle,OMX_CommandPortEnable,port)) {
1722                         return 0;
1723                 }
1724
1725         }
1726         return 1;
1727 }
1728
1729
1730 int VideoOMX::DisablePort(OMX_HANDLETYPE handle,OMX_U32 port,bool wait) //needs to be called with locked mutex
1731 {
1732         OMX_ERRORTYPE error;
1733         bool skip=false;
1734
1735         OMX_PARAM_PORTDEFINITIONTYPE pdt;
1736         memset(&pdt,0,sizeof(pdt));
1737         pdt.nSize=sizeof(pdt);
1738         pdt.nVersion.nVersion=OMX_VERSION;
1739         pdt.nPortIndex=port;
1740         error=OMX_GetParameter(handle,OMX_IndexParamPortDefinition, &pdt);
1741         if (error==OMX_ErrorNone) {
1742                 if(pdt.bEnabled==OMX_FALSE) {
1743                         skip=true; //already disabled;
1744                 }
1745
1746         }
1747
1748
1749         if (!skip) {
1750                 error=OMX_SendCommand(handle,OMX_CommandPortDisable,port,0);
1751                 if (error!=OMX_ErrorNone){
1752                         Log::getInstance()->log("Video", Log::DEBUG, "handle %x Send Command to disable port %x %x",handle,port, error);
1753                         return 0;
1754                 }
1755
1756                 if (!wait) return 1;
1757                 if (!CommandFinished(handle,OMX_CommandPortDisable,port)) {
1758                         return 0;
1759                 }
1760         }
1761
1762         return 1;
1763 }
1764
1765 int VideoOMX::WaitForEvent(OMX_HANDLETYPE handle,OMX_U32 event, int wait) //needs to be called with locked mutex
1766 {
1767         int i=0;
1768         int iend=(wait/5+1);
1769         while (i<iend) {
1770                 omx_event_mutex.Lock();
1771                 std::list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1772                 while (itty!=omx_events.end()) {
1773
1774                         VPE_OMX_EVENT current=*itty;
1775                         if (current.handle==handle) { //this is ours
1776                                 if (current.event_type==OMX_EventError) {
1777                                         omx_events.erase(itty);
1778                                         omx_event_mutex.Unlock();
1779                                         Log::getInstance()->log("Video", Log::DEBUG, "WaitForEvent Finished on Error");
1780                                         return 0;
1781
1782                                 } else if (current.event_type==event) {
1783                                         omx_events.erase(itty);
1784                                         omx_event_mutex.Unlock();
1785                                         Log::getInstance()->log("Video", Log::DEBUG, "WaitForEvent Finished Completed");
1786                                         return 1;
1787                                 }
1788                         }
1789                         itty++;
1790
1791                 }
1792                 omx_event_mutex.Unlock();
1793                 omx_event_ready_signal.waitForSignalTimed(10);
1794                 //MILLISLEEP(2);
1795                 i++;
1796
1797         }
1798         Log::getInstance()->log("Video", Log::DEBUG, "WaitForEvent waited too long %x %x",handle,event);
1799         return 0;
1800
1801 }
1802
1803 int VideoOMX::clearEvents()
1804 {
1805         omx_event_mutex.Lock();
1806         omx_events.clear();
1807         omx_event_mutex.Unlock();
1808
1809         return 1;
1810 }
1811
1812 int VideoOMX::clearEventsForComponent(OMX_HANDLETYPE handle)
1813 {
1814         omx_event_mutex.Lock();
1815         std::list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1816         while (itty!=omx_events.end()) {
1817                 VPE_OMX_EVENT current=*itty;
1818                 if (current.handle==handle) { //this is ours
1819                         itty=omx_events.erase(itty);
1820                         continue;
1821                 }
1822                 itty++;
1823
1824         }
1825         omx_event_mutex.Unlock();
1826         return 1;
1827 }
1828
1829 void VideoOMX::checkForStalledBuffers()
1830 {
1831         //Log::getInstance()->log("Video", Log::DEBUG, "Check stalled");
1832         clock_mutex.Lock();
1833         omx_event_mutex.Lock();
1834         std::list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1835         while (itty!=omx_events.end()) {
1836                 VPE_OMX_EVENT current=*itty;
1837                 if (current.event_type==OMX_EventParamOrConfigChanged && current.data1==omx_codec_output_port
1838                                 && current.handle==omx_vid_dec && current.data2==OMX_IndexConfigBufferStall) {
1839                         OMX_ERRORTYPE error;
1840                         OMX_CONFIG_BUFFERSTALLTYPE stall_conf;
1841                         memset(&stall_conf,0,sizeof(stall_conf));
1842                         stall_conf.nSize=sizeof(stall_conf);
1843                         stall_conf.nVersion.nVersion=OMX_VERSION;
1844                         stall_conf.nPortIndex=omx_codec_output_port;
1845                         stall_conf.nDelay=200000;
1846
1847                         error=OMX_GetConfig(omx_vid_dec,OMX_IndexConfigBufferStall,&stall_conf);
1848                         if (error!=OMX_ErrorNone){
1849                                         Log::getInstance()->log("Video", Log::DEBUG, "Get OMX_IndexConfigBufferStall failed %x", error);
1850                                         clock_mutex.Unlock();
1851                                         omx_event_mutex.Unlock();
1852                                         return ;
1853                                 }
1854                         if (stall_conf.bStalled==OMX_TRUE) {
1855                                 omx_vid_stalled=true;
1856                                 Log::getInstance()->log("Video", Log::DEBUG, "Video decoder stalled! %d", stall_conf.nDelay);
1857                         } else {
1858                                 omx_vid_stalled=false;
1859                                 Log::getInstance()->log("Video", Log::DEBUG, "Video decoder unstalled! %d",stall_conf.nDelay);
1860                         }
1861                         omx_events.erase(itty);
1862                         break;
1863                 }
1864                 itty++;
1865         }
1866         omx_event_mutex.Unlock();
1867         clock_mutex.Unlock();
1868 }
1869
1870
1871
1872
1873 int VideoOMX::CommandFinished(OMX_HANDLETYPE handle,OMX_U32 command,OMX_U32 data2) //needs to be called with locked mutex
1874 {
1875         int i=0;
1876         while (i<200/*1000*/) {
1877                 omx_event_mutex.Lock();
1878                 std::list<VPE_OMX_EVENT>::iterator itty=omx_events.begin();
1879                 while (itty!=omx_events.end()) {
1880
1881                         VPE_OMX_EVENT current=*itty;
1882                         if (current.handle==handle) { //this is ours
1883                                 if (current.event_type==OMX_EventError) {
1884                                         omx_events.erase(itty);
1885                                         omx_event_mutex.Unlock();
1886                                         Log::getInstance()->log("Video", Log::DEBUG, "Command Finished on Error %x",current.data1);
1887                                         return 0;
1888
1889                                 } else if (current.event_type==OMX_EventCmdComplete && current.data1==command && current.data2==data2) {
1890                                         omx_events.erase(itty);
1891                                         omx_event_mutex.Unlock();
1892                                         //Log::getInstance()->log("Video", Log::DEBUG, "Command Finished Completed");
1893                                         return 1;
1894                                 }
1895                         }
1896                         itty++;
1897
1898                 }
1899                 omx_event_mutex.Unlock();
1900                 omx_event_ready_signal.waitForSignalTimed(10);
1901                 //MILLISLEEP(2);
1902                 i++;
1903
1904         }
1905         Log::getInstance()->log("Video", Log::DEBUG, "CommandFinished waited too long %x %x %x",handle,command, data2);
1906         return 0;
1907
1908 }
1909
1910
1911
1912 int VideoOMX::PrepareInputBufsOMX() //needs to be called with locked mutex
1913 {
1914         OMX_ERRORTYPE error;
1915         OMX_PARAM_PORTDEFINITIONTYPE port_def_type;
1916         memset(&port_def_type,0,sizeof(port_def_type));
1917         port_def_type.nSize=sizeof(port_def_type);
1918         port_def_type.nVersion.nVersion=OMX_VERSION;
1919         port_def_type.nPortIndex=omx_codec_input_port;
1920
1921         error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
1922
1923         if (error!=OMX_ErrorNone){
1924                         Log::getInstance()->log("Video", Log::DEBUG, "Get OMX OMX_IndexParamPortDefinition failed %x", error);
1925         }
1926 /*      Log::getInstance()->log("Video", Log::DEBUG, "Port para %d %d %d %d %d %d %d", port_def_type.nBufferCountActual,
1927                         port_def_type.nBufferCountMin,port_def_type.nBufferSize,port_def_type.bEnabled,port_def_type.bPopulated,
1928                         port_def_type.bBuffersContiguous,port_def_type.nBufferAlignment);*/
1929
1930         port_def_type.nBufferCountActual=100;
1931         port_def_type.nBufferSize=max(port_def_type.nBufferSize,150000); // for transcoder important
1932
1933         error=OMX_SetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
1934
1935         if (error!=OMX_ErrorNone){
1936                         Log::getInstance()->log("Video", Log::DEBUG, "Set OMX OMX_IndexParamPortDefinition failed %x", error);
1937         }
1938
1939
1940         error=OMX_SendCommand(omx_vid_dec,OMX_CommandPortEnable,omx_codec_input_port,0);
1941         if (error!=OMX_ErrorNone){
1942                 Log::getInstance()->log("Video", Log::DEBUG, "Prepare Input bufs Send Command to enable port %x", error);
1943                 return 0;
1944         }
1945
1946         input_bufs_omx_mutex.Lock();
1947         for (unsigned int i=0; i< port_def_type.nBufferCountActual;i++) {
1948
1949         //      unsigned char* new_buffer_data=(unsigned char*)malloc(port_def_type.nbufferSize);
1950                 OMX_BUFFERHEADERTYPE *buf_head=NULL;
1951         /*      error=OMX_Usebuffer(omx_vid_dec,&buf_head,omx_codec_input_port,NULL,port_def_type.nbufferSize,new_buffer_data);
1952                 if (error!=OMX_ErrorNone){
1953                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_Usebuffer failed %x", error);
1954                         input_bufs_omx_mutex.Unlock();
1955                         return 0;
1956                 }*/
1957                 error=OMX_AllocateBuffer(omx_vid_dec,&buf_head,omx_codec_input_port,NULL,port_def_type.nBufferSize);
1958                 if (error!=OMX_ErrorNone){
1959                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_AllocateBuffer failed %x", error);
1960                                 input_bufs_omx_mutex.Unlock();
1961                         return 0;
1962                 }
1963                 input_bufs_omx_all.push_back(buf_head);
1964                 input_bufs_omx_free.push_back(buf_head);
1965         }
1966         omx_first_frame=true;
1967
1968         firstsynched=false;
1969         cur_input_buf_omx=NULL;
1970         input_bufs_omx_mutex.Unlock();
1971
1972
1973         Log::getInstance()->log("Video", Log::DEBUG, "PrepareInputBufsOMX mark3");
1974         if (!CommandFinished(omx_vid_dec,OMX_CommandPortEnable,omx_codec_input_port)) {
1975                 return 0;
1976         }
1977         Log::getInstance()->log("Video", Log::DEBUG, "PrepareInputBufsOMX mark4");
1978
1979         return 1;
1980 }
1981
1982 int VideoOMX::DestroyInputBufsOMX() //need s to be called with locked mutex
1983 {
1984         OMX_ERRORTYPE error;
1985
1986         cur_input_buf_omx=NULL;
1987         input_bufs_omx_mutex.Lock();
1988         for (UINT i=0; i< input_bufs_omx_all.size();i++) {
1989         //      free(input_bufs_omx_all[i]->pBuffer);
1990         //      input_bufs_omx_all[i]->pBuffer=NULL;
1991                 error=OMX_FreeBuffer(omx_vid_dec,omx_codec_input_port,input_bufs_omx_all[i]);
1992                 if (error!=OMX_ErrorNone){
1993                         Log::getInstance()->log("Video", Log::DEBUG, "Use OMX_FreeBuffer failed %x", error);
1994                         input_bufs_omx_mutex.Unlock();
1995                         return 0;
1996                 }
1997
1998         }
1999         input_bufs_omx_all.clear();
2000         input_bufs_omx_free.clear();
2001         input_bufs_omx_mutex.Unlock();
2002
2003         return 1;
2004 }
2005
2006
2007
2008 int VideoOMX::FlushRenderingPipe()
2009 {
2010         OMX_ERRORTYPE error;
2011
2012         if (!dodeint) {
2013
2014                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
2015                                 omx_codec_output_port, NULL);
2016                 if (error != OMX_ErrorNone) {
2017                         Log::getInstance()->log("Video", Log::DEBUG,
2018                                         "OMX_Flush codec out 1 failed %x", error);
2019
2020                 }
2021
2022                 error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
2023                                 omx_shed_input_port, NULL);
2024                 if (error != OMX_ErrorNone) {
2025                         Log::getInstance()->log("Video", Log::DEBUG,
2026                                         "OMX_Flush shed in 2 failed %x", error);
2027
2028                 }
2029
2030                 if (!CommandFinished(omx_vid_dec, OMX_CommandFlush,
2031                                 omx_codec_output_port)) {
2032                         Log::getInstance()->log("Video", Log::DEBUG,
2033                                         "flush cmd codec  3 failed");
2034                 }
2035
2036                 if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
2037                                 omx_shed_input_port)) {
2038                         Log::getInstance()->log("Video", Log::DEBUG,
2039                                         "flush cmd  shed 4 failed");
2040                 }
2041         } else {
2042                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
2043                                 omx_codec_output_port, NULL);
2044                 if (error != OMX_ErrorNone) {
2045                         Log::getInstance()->log("Video", Log::DEBUG,
2046                                         "OMX_Flush codec out 5 failed %x", error);
2047
2048                 }
2049
2050                 error = OMX_SendCommand(omx_vid_deint, OMX_CommandFlush,
2051                                 omx_deint_input_port, NULL);
2052                 if (error != OMX_ErrorNone) {
2053                         Log::getInstance()->log("Video", Log::DEBUG,
2054                                         "OMX_Flush deint in 6 failed %x", error);
2055
2056                 }
2057
2058                 if (!CommandFinished(omx_vid_dec, OMX_CommandFlush,
2059                                 omx_codec_output_port)) {
2060                         Log::getInstance()->log("Video", Log::DEBUG,
2061                                         "flush cmd codec  7 failed");
2062                 }
2063
2064                 if (!CommandFinished(omx_vid_deint, OMX_CommandFlush,
2065                                 omx_deint_input_port)) {
2066                         Log::getInstance()->log("Video", Log::DEBUG,
2067                                         "flush cmd  deint 8 failed");
2068                 }
2069
2070                 //m
2071                 error = OMX_SendCommand(omx_vid_deint, OMX_CommandFlush,
2072                                 omx_deint_output_port, NULL);
2073                 if (error != OMX_ErrorNone) {
2074                         Log::getInstance()->log("Video", Log::DEBUG,
2075                                         "OMX_Flush deint out 9 failed %x", error);
2076
2077                 }
2078
2079                 error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
2080                                 omx_shed_input_port, NULL);
2081                 if (error != OMX_ErrorNone) {
2082                         Log::getInstance()->log("Video", Log::DEBUG,
2083                                         "OMX_Flush shed in 10 failed %x", error);
2084
2085                 }
2086
2087                 if (!CommandFinished(omx_vid_deint, OMX_CommandFlush,
2088                                 omx_deint_output_port)) {
2089                         Log::getInstance()->log("Video", Log::DEBUG,
2090                                         "flush cmd deint 11 failed");
2091                 }
2092
2093                 if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
2094                                 omx_shed_input_port)) {
2095                         Log::getInstance()->log("Video", Log::DEBUG,
2096                                         "flush cmd  shed 12 failed");
2097                 }
2098
2099         }
2100
2101
2102
2103
2104         error = OMX_SendCommand(omx_vid_rend, OMX_CommandFlush,
2105                         omx_rend_input_port, NULL);
2106         if (error != OMX_ErrorNone) {
2107                 Log::getInstance()->log("Video", Log::DEBUG,
2108                                 "OMX_Flush rend in failed %x", error);
2109
2110         }
2111
2112         error = OMX_SendCommand(omx_vid_sched, OMX_CommandFlush,
2113                         omx_shed_output_port, NULL);
2114         if (error != OMX_ErrorNone) {
2115                 Log::getInstance()->log("Video", Log::DEBUG,
2116                                 "OMX_Flush shed out failed %x", error);
2117
2118         }
2119
2120
2121
2122         if (!CommandFinished(omx_vid_rend, OMX_CommandFlush,
2123                         omx_rend_input_port)) {
2124                 Log::getInstance()->log("Video", Log::DEBUG,
2125                                 "flush cmd shed rend failed");
2126         }
2127
2128         if (!CommandFinished(omx_vid_sched, OMX_CommandFlush,
2129                         omx_shed_output_port)) {
2130                 Log::getInstance()->log("Video", Log::DEBUG,
2131                                 "flush cmd shed rend failed");
2132         }
2133
2134         return 1;
2135 }
2136
2137
2138 int VideoOMX::DeAllocateCodecsOMX()
2139 {
2140         OMX_ERRORTYPE error;
2141         omx_running=false;
2142           Log::getInstance()->log("Video", Log::DEBUG, "enter deallocatecodecsomx");
2143
2144    if (cur_input_buf_omx) {
2145                 cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_EOS;
2146                 error=ProtOMXEmptyThisBuffer(omx_vid_dec,cur_input_buf_omx);
2147                 if (error!=OMX_ErrorNone) {
2148                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_EmptyThisBuffer failed %x", error);
2149                 }
2150
2151                 cur_input_buf_omx=NULL;//write out old data
2152         }
2153    clock_mutex.Lock();
2154    clearEvents();
2155         if (omx_vid_dec) {
2156                 // first stop the omx elements
2157                 if (!ChangeComponentState(omx_vid_dec,OMX_StateIdle)) {
2158                         Log::getInstance()->log("Video", Log::DEBUG, "vid_dec ChangeComponentState");
2159
2160                 }
2161                 clock_mutex.Unlock();
2162
2163                 idleClock();
2164                 clock_mutex.Lock();
2165
2166                 if (dodeint) {
2167                         if (!ChangeComponentState(omx_vid_deint, OMX_StateIdle)) {
2168                                 Log::getInstance()->log("Video", Log::DEBUG,
2169                                                 "vid_deint ChangeComponentState");
2170
2171                         }
2172                 }
2173
2174
2175                 if (!ChangeComponentState(omx_vid_sched,OMX_StateIdle)) {
2176                         Log::getInstance()->log("Video", Log::DEBUG, "vid_shed ChangeComponentState");
2177
2178                 }
2179
2180                 if (!ChangeComponentState(omx_vid_rend,OMX_StateIdle)) {
2181                         Log::getInstance()->log("Video", Log::DEBUG, "vid_rend ChangeComponentState");
2182
2183                 }
2184
2185
2186
2187         // TODO proper deinit sequence
2188                 // first flush all buffers
2189                 FlushRenderingPipe();
2190
2191
2192
2193
2194
2195                 error=OMX_SendCommand(omx_clock,OMX_CommandFlush, omx_clock_output_port, NULL);
2196                 if (error!=OMX_ErrorNone){
2197                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Flush clock out failed %x", error);
2198
2199                 }
2200
2201                 error=OMX_SendCommand(omx_vid_sched,OMX_CommandFlush, omx_shed_clock_port, NULL);
2202                 if (error!=OMX_ErrorNone){
2203                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Flush shed clock failed %x", error);
2204
2205                 }
2206
2207                 if (!CommandFinished(omx_clock,OMX_CommandFlush,omx_clock_output_port) ||
2208                         !CommandFinished(omx_vid_sched,OMX_CommandFlush,omx_shed_clock_port)) {
2209                                 Log::getInstance()->log("Video", Log::DEBUG, "flush cmd clock shed failed");
2210                 }
2211
2212
2213
2214
2215                 error = OMX_SendCommand(omx_vid_dec, OMX_CommandFlush,
2216                                 omx_codec_input_port, NULL);
2217                 if (error != OMX_ErrorNone) {
2218                         Log::getInstance()->log("Video", Log::DEBUG,
2219                                         "OMX_Flush codec out failed %x", error);
2220
2221                 }
2222
2223
2224
2225
2226                 DestroyInputBufsOMX();
2227
2228                 //todo flushing
2229                 if (!DisablePort(omx_vid_sched,omx_shed_output_port,true)) {
2230                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 2 ");
2231                 }
2232                 if (!DisablePort(omx_vid_rend,omx_rend_input_port,true)) {
2233                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 1");
2234                 }
2235
2236
2237
2238
2239                 if (!DisablePort(omx_vid_dec,omx_codec_output_port,true)) {
2240                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 6");
2241                 }
2242
2243
2244
2245                 if (!DisablePort(omx_vid_dec,omx_codec_input_port,true)) {
2246                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 7");
2247                 }
2248
2249                 if (dodeint) {
2250                         if (!DisablePort(omx_vid_deint,omx_deint_output_port,true)) {
2251                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 6a");
2252                         }
2253
2254
2255
2256                         if (!DisablePort(omx_vid_deint,omx_deint_input_port,true)) {
2257                                 Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 7a");
2258                         }
2259                 }
2260
2261
2262
2263                 if (!DisablePort(omx_vid_sched,omx_shed_input_port,true)) {
2264                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 3");
2265                 }
2266
2267                 if (!DisablePort(omx_vid_sched,omx_shed_clock_port,true)) {
2268                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 4");
2269                 }
2270
2271                 if (!DisablePort(omx_clock,omx_clock_output_port,true)) {
2272                         Log::getInstance()->log("Video", Log::DEBUG, "Disable Tunnel Port failed 5");
2273                 }
2274
2275
2276
2277
2278                 error=OMX_SetupTunnel(omx_vid_dec,omx_codec_output_port,NULL,0);
2279                 if (error!=OMX_ErrorNone) {
2280                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2281
2282                 }
2283
2284                 if (dodeint) {
2285                         error=OMX_SetupTunnel(omx_vid_deint,omx_deint_input_port,NULL,0);
2286                         if (error!=OMX_ErrorNone) {
2287                                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2288                         }
2289
2290
2291                         error=OMX_SetupTunnel(omx_vid_deint,omx_deint_output_port,NULL,0);
2292                         if (error!=OMX_ErrorNone) {
2293                                 Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2294                         }
2295                 }
2296
2297                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_input_port,NULL,0);
2298                 if (error!=OMX_ErrorNone) {
2299                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2300
2301                 }
2302
2303
2304                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_output_port,NULL,0);
2305                 if (error!=OMX_ErrorNone) {
2306                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2307
2308                 }
2309
2310                 error=OMX_SetupTunnel(omx_vid_rend,omx_rend_input_port,NULL,0);
2311                 if (error!=OMX_ErrorNone) {
2312                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2313
2314                 }
2315
2316
2317                 error=OMX_SetupTunnel(omx_clock,omx_clock_output_port,NULL,0);
2318                 if (error!=OMX_ErrorNone) {
2319                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2320
2321                 }
2322
2323                 error=OMX_SetupTunnel(omx_vid_sched,omx_shed_clock_port,NULL,0);
2324                 if (error!=OMX_ErrorNone) {
2325                         Log::getInstance()->log("Video", Log::DEBUG, "OMX_Setup tunnel teardown failed %x", error);
2326
2327                 }
2328
2329
2330
2331
2332                 error=OMX_FreeHandle(omx_vid_dec);
2333                 error=OMX_FreeHandle(omx_vid_sched);
2334                 error=OMX_FreeHandle(omx_vid_rend);
2335                 if (dodeint) error=OMX_FreeHandle(omx_vid_deint);
2336                 omx_vid_dec=NULL;
2337                 clock_mutex.Unlock();
2338                 destroyClock();
2339                 if (error!=OMX_ErrorNone) {
2340                         Log::getInstance()->log("Video", Log::DEBUG, "FreeHandle failed %d", error);
2341                 }
2342         } else  clock_mutex.Unlock();
2343           Log::getInstance()->log("Video", Log::DEBUG, "leave deallocate codecs OMX");
2344
2345         return 1;
2346 }
2347
2348
2349 void VideoOMX::destroyClock()
2350 {
2351         clock_mutex.Lock();
2352         if (clock_references>0) {
2353                 clock_references--;
2354                 if (clock_references==0) {
2355                         OMX_ERRORTYPE error;
2356                         Log::getInstance()->log("Video", Log::DEBUG, "destroy omx clock");
2357                         error=OMX_FreeHandle(omx_clock);
2358                         if (error!=OMX_ErrorNone) {
2359                                 Log::getInstance()->log("Video", Log::DEBUG, "FreeHandle failed %d", error);
2360                         }
2361
2362                 }
2363         }
2364         clock_mutex.Unlock();
2365
2366 }
2367
2368 int VideoOMX::stop()
2369 {
2370   if (!initted) return 0;
2371   iframemode=false;
2372
2373   //Check if libav mode
2374   DeAllocateCodecsOMX();
2375
2376
2377
2378
2379 //  if (ioctl(fdVideo, AV_SET_VID_STOP, 0) != 0) return 0;
2380   return 1;
2381 }
2382
2383 int VideoOMX::reset()
2384 {
2385   if (!initted) return 0;
2386
2387   iframemode=false;
2388   DeAllocateCodecsOMX();
2389 //  if (ioctl(fdVideo, AV_SET_VID_RESET, 0x11) != 0) return 0;
2390   return 1;
2391 }
2392
2393 int VideoOMX::pause()
2394 {
2395   if (!initted) return 0;
2396   Log::getInstance()->log("Video", Log::DEBUG, "enter pause");
2397  // clockPause();
2398   // ignore it audio handles this
2399   return 1;
2400 }
2401
2402 int VideoOMX::unPause() // FIXME get rid - same as play!! Not here!
2403 {
2404   if (!initted) return 0;
2405   Log::getInstance()->log("Video", Log::DEBUG, "enter unpause");
2406
2407   //clockUnpause();
2408   //ignore it audio handles this
2409
2410   return 1;
2411 }
2412
2413 int VideoOMX::fastForward()
2414 {
2415   if (!initted) return 0;
2416
2417 //  if (ioctl(fdVideo, AV_SET_VID_libavWD, 1) != 0) return 0;
2418   return 1;
2419 }
2420
2421 int VideoOMX::unFastForward()
2422 {
2423   if (!initted) return 0;
2424
2425 //  if (ioctl(fdVideo, AV_SET_VID_RESET, 0x11) != 0) return 0; // don't need this.
2426
2427  //// if (ioctl(fdVideo, AV_SET_VID_PLAY, 0) != 0) return 0;
2428   return 1;
2429 }
2430
2431 int VideoOMX::attachFrameBuffer()
2432 {
2433   if (!initted) return 0;
2434
2435 //  if (ioctl(fdVideo, AV_SET_VID_FB, 0) != 0) return 0;
2436   return 1;
2437 }
2438
2439 int VideoOMX::blank(void)
2440 {
2441 //  if (ioctl(fdVideo, AV_SET_VID_FB, 1) != 0) return 0;
2442 //  if (ioctl(fdVideo, AV_SET_VID_FB, 0) != 0) return 0;
2443   return 1;
2444 }
2445
2446 ULLONG VideoOMX::getCurrentTimestamp() {
2447         if (iframemode)
2448                 return 0;
2449         long long ncur_clock_time = cur_clock_time;
2450         if (omx_running) {
2451                 int oldcancelstate;
2452                 int oldcanceltype;
2453                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2454                 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2455                 clock_mutex.Lock();
2456                 OMX_ERRORTYPE error;
2457                 OMX_TIME_CONFIG_CLOCKSTATETYPE clock_conf;
2458                 memset(&clock_conf, 0, sizeof(clock_conf));
2459                 clock_conf.nSize = sizeof(clock_conf);
2460                 clock_conf.nVersion.nVersion = OMX_VERSION;
2461                 error= OMX_GetConfig(omx_clock, OMX_IndexConfigTimeClockState,
2462                                 &clock_conf);
2463                 if (error != OMX_ErrorNone) {
2464                         Log::getInstance()->log("Video", Log::DEBUG,"getCurrentTimestamp IndexConfigTimeClockState failed %x",error);
2465                 }
2466
2467                 if (clock_conf.eState == OMX_TIME_ClockStateRunning) {
2468
2469                         OMX_TIME_CONFIG_TIMESTAMPTYPE cur_time_stamp;
2470                         memset(&cur_time_stamp, 0, sizeof(cur_time_stamp));
2471                         cur_time_stamp.nSize = sizeof(cur_time_stamp);
2472                         cur_time_stamp.nVersion.nVersion = OMX_VERSION;
2473                         cur_time_stamp.nPortIndex = omx_clock_output_port;
2474                         error = OMX_GetConfig(omx_clock, OMX_IndexConfigTimeCurrentMediaTime,
2475                                         &cur_time_stamp);
2476                         if (error != OMX_ErrorNone) {
2477                                 Log::getInstance()->log("Video",Log::DEBUG,"getCurrentTimestamp OMX_IndexConfigTimeCurrentMediaTime failed %x",error);
2478                         } else {
2479                                 long long temp = cur_time_stamp.nTimestamp.nLowPart
2480                                                 | ((long long) cur_time_stamp.nTimestamp.nHighPart << 32);
2481                                 ncur_clock_time = cur_clock_time = temp * 10LL;
2482                         }
2483                 }
2484                 clock_mutex.Unlock();
2485                 pthread_setcancelstate(oldcancelstate, NULL);
2486                 pthread_setcanceltype(oldcanceltype, NULL);
2487         }
2488
2489         //ncur_clock_time -= startoffset;
2490         ncur_clock_time -= lastreftimeOMX;
2491         long long result = lastreftimePTS;
2492         if (lastreftimePTS==0) return 0; // invalid time
2493         result += (long long) (ncur_clock_time / 10000LL * 90LL);
2494         if (result < 0)
2495                 result = (1LL << 33) - result;
2496         //Log::getInstance()->log("Video", Log::DEBUG,"getCurrentTimestamp %lld %lld %lld %lld %lld %lld",ncur_clock_time,cur_clock_time,lastreftimeOMX,lastreftimePTS,result,startoffset);
2497
2498         return result;
2499
2500 }
2501
2502 // to be removed
2503 /*
2504 ULONG VideoOMX::timecodeToFrameNumber(ULLONG timecode)
2505 {
2506   if (format == PAL) return (ULONG)(((double)timecode / (double)90000) * (double)25);
2507   else               return (ULONG)(((double)timecode / (double)90000) * (double)30);
2508 }
2509
2510 */
2511 #ifdef DEV
2512 int VideoOMX::test()
2513 {
2514   return 0;
2515
2516 //  ULLONG stc = 0;
2517 //  return ioctl(fdVideo, AV_SET_VID_STC, &stc);
2518 /*
2519  // reset();
2520   return 1;
2521 */
2522 }
2523
2524 int VideoOMX::test2()
2525 {
2526   return 0;
2527 }
2528 #endif
2529
2530
2531
2532 long long VideoOMX::SetStartOffset(long long curreftime, bool *rsync)
2533 {
2534   *rsync=false;
2535   if (offsetnotset) {
2536     startoffset=curreftime;//offset is set for audio
2537     offsetnotset=false;
2538     offsetvideonotset=false;
2539   } else {
2540     if (offsetvideonotset) {
2541       offsetvideonotset=false;
2542       *rsync=true;
2543     } else {
2544       if ( (curreftime-lastrefvideotime)>10000000LL
2545         || (curreftime-lastrefvideotime)<-10000000LL) {//if pts jumps to big resync
2546         startoffset+=curreftime-lastrefvideotime;
2547         lastrefaudiotime+=curreftime-lastrefvideotime;
2548         //*rsync=true;
2549         offsetaudionotset=true;
2550
2551       }
2552     }
2553
2554   }
2555
2556   lastrefvideotime=curreftime;
2557
2558   return startoffset;
2559
2560 }
2561
2562 long long VideoOMX::SetStartAudioOffset(long long curreftime, bool *rsync)
2563 {
2564   *rsync=false;
2565   if (offsetnotset) {
2566     startoffset=curreftime;
2567     offsetnotset=false;
2568     offsetaudionotset=false;
2569   }else {
2570     if (offsetaudionotset) {
2571       offsetaudionotset=false;
2572       *rsync=true;
2573     } else {
2574       if ( (curreftime-lastrefaudiotime)>10000000LL
2575         || (curreftime-lastrefaudiotime)<-10000000LL) {//if pts jumps to big resync
2576         startoffset+=curreftime-lastrefaudiotime;
2577         lastrefvideotime+=curreftime-lastrefaudiotime;
2578         //*rsync=true;
2579         offsetvideonotset=true;
2580
2581       }
2582     }
2583
2584   }
2585   lastrefaudiotime=curreftime;
2586   return startoffset;
2587
2588 }
2589
2590 void VideoOMX::ResetTimeOffsets() {
2591   offsetnotset=true; //called from demuxer
2592   offsetvideonotset=true;
2593   offsetaudionotset=true;
2594   startoffset=0;
2595   lastrefaudiotime=0;
2596   lastrefvideotime=0;
2597   lastreftimeOMX=0;
2598   lastreftimePTS=0;
2599 }
2600
2601
2602 void VideoOMX::FirstFrameFix()
2603 {
2604         int oldcancelstate;
2605         int oldcanceltype;
2606         Demuxer* demux=Demuxer::getInstance();
2607         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2608         pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2609         clock_mutex.Lock();
2610         if (WaitForEvent(omx_vid_dec,OMX_EventPortSettingsChanged,0)){
2611                 WaitForEvent(omx_vid_deint,OMX_EventPortSettingsChanged,0); //clear old messages
2612                 OMX_ERRORTYPE error;
2613                 OMX_PARAM_PORTDEFINITIONTYPE port_def_type;
2614                 memset(&port_def_type,0,sizeof(port_def_type));
2615                 port_def_type.nSize=sizeof(port_def_type);
2616                 port_def_type.nVersion.nVersion=OMX_VERSION;
2617                 port_def_type.nPortIndex=omx_codec_output_port;
2618
2619                 error=OMX_GetParameter(omx_vid_dec,OMX_IndexParamPortDefinition, &port_def_type);
2620                 if (error != OMX_ErrorNone) {
2621                         Log::getInstance()->log("Video", Log::DEBUG,
2622                                         "OMX_IndexParamPortDefinition fix failed %x", error);
2623                         clock_mutex.Unlock();
2624                         return;
2625                 }
2626
2627
2628                 Log::getInstance()->log("Video", Log::DEBUG,
2629                                                         "Deinit first frame fix %d %d %d %d %d %d %d %d",port_def_type.format.video.nFrameWidth , demux->getHorizontalSize(),
2630                                                         port_def_type.format.video.nFrameHeight , demux->getVerticalSize(),port_def_type.format.video.nStride,
2631                                                         port_def_type.format.video.nSliceHeight, port_def_type.format.video.xFramerate,
2632                                                          port_def_type.format.video.bFlagErrorConcealment );
2633                 Log::getInstance()->log("Video", Log::DEBUG,
2634                                                                         "Deinit first frame fix2 %d  %d",
2635                                                                         port_def_type.format.video.eCompressionFormat ,
2636                                                                         port_def_type.format.video.eColorFormat );
2637                 first_frame=false;
2638
2639                 // we cause the video_decode to determine the interlacing properties
2640                 OMX_CONFIG_INTERLACETYPE il;
2641                 memset(&il,0,sizeof(il));
2642                 il.nSize=sizeof(il);
2643                 il.nVersion.nVersion=OMX_VERSION;
2644                 il.nPortIndex=omx_codec_output_port;
2645                 error=OMX_GetConfig(omx_vid_dec,OMX_IndexConfigCommonInterlace, &il);
2646                 if (error != OMX_ErrorNone) {
2647                         Log::getInstance()->log("Video", Log::DEBUG,
2648                                         "OMX_IndexConfigCommonInterlace fix failed %x", error);
2649                 }
2650
2651
2652                 DisablePort(omx_vid_dec,omx_codec_output_port,true);
2653                 DisablePort(omx_vid_sched,omx_shed_input_port,true);
2654                 if (dodeint) {
2655
2656                         DisablePort(omx_vid_deint,omx_deint_input_port,true);
2657                         // This is a dirty hack
2658                         DisablePort(omx_vid_deint,omx_deint_output_port,true);
2659
2660
2661                         port_def_type.nPortIndex=omx_deint_output_port;
2662                         error = OMX_SetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2663                                         &port_def_type);
2664                         if (error != OMX_ErrorNone) {
2665                                 Log::getInstance()->log("Video", Log::DEBUG,
2666                                                 "Set OMX_IndexParamPortDefinition1 failed %x", error);
2667                                 clock_mutex.Unlock();
2668                                 pthread_setcancelstate(oldcancelstate, NULL);
2669                                 pthread_setcanceltype(oldcanceltype, NULL);
2670                                 return;
2671                         }
2672                         // dirty hack end
2673
2674
2675                         port_def_type.nPortIndex=omx_deint_input_port;
2676                         error = OMX_SetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2677                                         &port_def_type);
2678                         if (error != OMX_ErrorNone) {
2679                                 Log::getInstance()->log("Video", Log::DEBUG,
2680                                                 "Set OMX_IndexParamPortDefinition1 failed %x", error);
2681                                 clock_mutex.Unlock();
2682                                 pthread_setcancelstate(oldcancelstate, NULL);
2683                                 pthread_setcanceltype(oldcanceltype, NULL);
2684                                 return;
2685                         }
2686                 //      WaitForEvent(omx_vid_dec,OMX_EventPortSettingsChanged);
2687
2688                         Log::getInstance()->log("Video", Log::DEBUG,
2689                                                                         "Marker");
2690                         EnablePort(omx_vid_deint,omx_deint_input_port,true);
2691                         WaitForEvent(omx_vid_deint,OMX_EventPortSettingsChanged);
2692                         port_def_type.nPortIndex=omx_deint_output_port;
2693                         error = OMX_GetParameter(omx_vid_deint, OMX_IndexParamPortDefinition,
2694                                         &port_def_type);
2695                         if (error != OMX_ErrorNone) {
2696                                 Log::getInstance()->log("Video", Log::DEBUG,
2697                                                 "Get OMX_IndexParamPortDefinition2 failed %x", error);
2698                                 clock_mutex.Unlock();
2699                                 pthread_setcancelstate(oldcancelstate, NULL);
2700                                 pthread_setcanceltype(oldcanceltype, NULL);
2701                                 return;
2702                         }
2703                         Log::getInstance()->log("Video", Log::DEBUG,
2704                                         "Deinit first frame fix3 %d %d %d %d %d %d %d ",port_def_type.format.image.nFrameWidth , demux->getHorizontalSize(),
2705                                         port_def_type.format.image.nFrameHeight , demux->getVerticalSize(),port_def_type.format.image.nStride,
2706                                         port_def_type.format.image.nSliceHeight, /*port_def_type.format.image.xFramerate,*/
2707                                         port_def_type.format.image.bFlagErrorConcealment );
2708                         Log::getInstance()->log("Video", Log::DEBUG,
2709                                         "Deinit first frame fix4 %d  %d",
2710                                         port_def_type.format.image.eCompressionFormat ,
2711                                         port_def_type.format.image.eColorFormat );
2712                         DisablePort(omx_vid_deint,omx_deint_output_port,true);
2713
2714                 }
2715                 port_def_type.nPortIndex=omx_shed_input_port;
2716                 error = OMX_SetParameter(omx_vid_sched, OMX_IndexParamPortDefinition,
2717                                         &port_def_type);
2718                 if (error != OMX_ErrorNone) {
2719                         Log::getInstance()->log("Video", Log::DEBUG,
2720                                         "Set OMX_IndexParamPortDefinition3 failed %x", error);
2721                         clock_mutex.Unlock();
2722                         pthread_setcancelstate(oldcancelstate, NULL);
2723                         pthread_setcanceltype(oldcanceltype, NULL);
2724                         return;
2725                 }
2726                 WaitForEvent(omx_vid_sched,OMX_EventPortSettingsChanged);
2727
2728
2729                 if (dodeint) {
2730                         EnablePort(omx_vid_deint,omx_deint_output_port,true);
2731                 }
2732                 EnablePort(omx_vid_dec,omx_codec_output_port,true);
2733                 EnablePort(omx_vid_sched,omx_shed_input_port,true);
2734         }
2735         clock_mutex.Unlock();
2736         pthread_setcancelstate(oldcancelstate, NULL);
2737         pthread_setcanceltype(oldcanceltype, NULL);
2738
2739
2740
2741 }
2742
2743
2744 void VideoOMX::PutBufferToPres(OMX_BUFFERHEADERTYPE* buffer)
2745 {
2746
2747         OMX_ERRORTYPE error = ProtOMXEmptyThisBuffer(omx_vid_dec, buffer);
2748         if (error != OMX_ErrorNone) {
2749                 Log::getInstance()->log("Video", Log::DEBUG,
2750                                 "OMX_EmptyThisBuffer failed %x", error);
2751         }
2752         if (first_frame) FirstFrameFix();
2753
2754 }
2755
2756 OMX_ERRORTYPE VideoOMX::ProtOMXEmptyThisBuffer(OMX_HANDLETYPE handle, OMX_BUFFERHEADERTYPE* buffer)
2757 {
2758         // protect the call to empty this buffer
2759         int oldcancelstate;
2760         int oldcanceltype;
2761 /*      long long temp =buffer->nTimeStamp.nLowPart
2762                                                         | ((long long) buffer->nTimeStamp.nHighPart << 32);*/
2763
2764         //pthread_testcancel();
2765         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2766         pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2767         clock_mutex.Lock();
2768 // Diagnosis code
2769 /*      OMX_ERRORTYPE error;
2770         OMX_TIME_CONFIG_TIMESTAMPTYPE timestamp;
2771         memset(&timestamp, 0, sizeof(timestamp));
2772         timestamp.nSize = sizeof(timestamp);
2773         timestamp.nVersion.nVersion = OMX_VERSION;
2774         timestamp.nPortIndex =omx_clock_output_port;
2775
2776         error = OMX_GetConfig(omx_clock, OMX_IndexConfigTimeCurrentMediaTime,
2777                         &timestamp);
2778
2779         if (error != OMX_ErrorNone) {
2780                 Log::getInstance()->log("Audio", Log::DEBUG,
2781                                 "Init OMX_IndexConfigAudioRenderingLatencyfailed %x %d", error,
2782                                 omx_rend_input_port);
2783         }
2784         long long temp2 =timestamp.nTimestamp.nLowPart
2785                                                                 | ((long long) timestamp.nTimestamp.nHighPart << 32);
2786
2787
2788         Log::getInstance()->log("Video", Log::NOTICE, "OMXETB %x %lld %lld %x",handle,temp,temp2,buffer->nFlags);*/
2789         OMX_ERRORTYPE ret_val;
2790         ret_val=OMX_EmptyThisBuffer(handle,buffer);
2791         clock_mutex.Unlock();
2792         pthread_setcancelstate(oldcancelstate, NULL);
2793         pthread_setcanceltype(oldcanceltype, NULL);
2794         //pthread_testcancel();
2795         return ret_val;
2796 }
2797
2798 bool VideoOMX::detectIFrame(const UCHAR *buffer,unsigned int length)
2799 {
2800         const UCHAR* curbuf=buffer;
2801         const UCHAR* curbufend=buffer+length;
2802         unsigned int detector=0xFFFFFFFF;
2803         bool gotaud=false; // have seen access unit delimiter
2804
2805         while (curbuf!=curbufend) {
2806                 detector<<=8;
2807                 detector|=*curbuf;
2808                 if (h264) {
2809                         if (detector==0x00000109) {
2810                                 gotaud=true;
2811                                 detector=0xFFFFFFFF;
2812                         } else if (gotaud &&detector==0x00000001) {
2813                                 curbuf++;
2814                                 if (curbuf!=curbufend) {
2815                                         unsigned char picttype=(*curbuf)& 0x1F;
2816                                         return picttype==0x07;
2817                                 }
2818                         }
2819                 } else {
2820                         if (detector==0x00000100) {
2821                                 curbuf++;
2822                                 if (curbuf==curbufend) return false;
2823                                 curbuf++;
2824                                 if (curbuf==curbufend) return false;
2825                                 unsigned char picttype=((*curbuf) >> 3) & 0x07;
2826                                 return picttype==1;
2827                         }
2828                 }
2829                 curbuf++;
2830         }
2831
2832         return false; // no frame found
2833 }
2834
2835
2836
2837 bool VideoOMX::DrainTargetBufferFull()
2838 {
2839         //Check, if we have OMX output buffers
2840         bool full;
2841         input_bufs_omx_mutex.Lock();
2842         full=(input_bufs_omx_free.size()==0);
2843         input_bufs_omx_mutex.Unlock();
2844         checkForStalledBuffers(); // check if the decoder has a problem
2845         if (full && omx_vid_stalled && !omx_first_frame) {
2846                 omx_vid_stalled=false;
2847                 Log::getInstance()->log("Video", Log::DEBUG, "Decoder is stalled, do a reset!");
2848
2849                 int oldcancelstate;
2850                 int oldcanceltype;
2851                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
2852                 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
2853
2854                 clock_mutex.Lock();
2855                 FlushRenderingPipe();
2856                 omx_first_frame=true;
2857                 clock_mutex.Unlock();
2858
2859                 pthread_setcancelstate(oldcancelstate, NULL);
2860                 pthread_setcanceltype(oldcanceltype, NULL);
2861         }
2862         return full;
2863
2864 }
2865
2866 void VideoOMX::PrepareMediaSample(const MediaPacketList& mplist,UINT samplepos)
2867 {
2868
2869         mediapackets.clear();
2870         std::list<MediaPacket>::const_iterator begin=mplist.begin();
2871         std::list<MediaPacket>::const_iterator itty=mplist.begin();
2872         advance(itty,min(mplist.size(),10));
2873         mediapackets.insert(mediapackets.begin(),begin,itty);//front
2874
2875 }
2876
2877 UINT VideoOMX::DeliverMediaSample(UCHAR* buffer, UINT *samplepos)
2878 {
2879         int consumed=0;
2880         while (consumed < (int)mediapackets.size()) {
2881             DeliverMediaPacket(mediapackets[consumed], buffer, samplepos);
2882             if (*samplepos == mediapackets[consumed].length) {
2883                 *samplepos = 0;
2884                 consumed++;
2885                 //return 1;
2886             } else return consumed;
2887         }
2888         return consumed;
2889 }
2890
2891 UINT VideoOMX::DeliverMediaPacket(MediaPacket packet,
2892                 const UCHAR* buffer,
2893                 UINT *samplepos)
2894 {
2895         if (packet.type == MPTYPE_VIDEO_H264)
2896         {
2897                 h264=true;
2898         }
2899         else
2900         {
2901                 h264=false;
2902         }
2903
2904
2905         //Later add fail back code for libav
2906 /*      if (!videoon) {
2907                 *samplepos+=packet.length;
2908                 return packet.length;
2909         }*/
2910
2911
2912         if (!omx_running) return 0; // if we are not runnig do not do this
2913
2914         if (isClockPaused()) return 0; //Block if we pause
2915
2916 //      Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 1");
2917         //Log::getInstance()->log("Video", Log::DEBUG, "DeliverMediaPacketOMX time %lld",packet.presentation_time);
2918
2919
2920         /*First Check, if we have an video sample*/
2921         if (iframemode) {
2922                 //samplepos=0;
2923                 MILLISLEEP(10);
2924                 return 0; //Not in iframe mode!
2925         }
2926
2927         UINT headerstrip=0;
2928         if (packet.disconti) {
2929                 firstsynched=false;
2930                 if (cur_input_buf_omx) {
2931                         PutBufferToPres(cur_input_buf_omx);
2932                         cur_input_buf_omx=NULL;
2933                 }
2934         }
2935         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 2");
2936         /*Inspect PES-Header */
2937
2938 //      OMX_STATETYPE temp_state;
2939 //      OMX_GetState(omx_vid_dec,&temp_state);
2940
2941         if (*samplepos==0) {//stripheader
2942                 headerstrip=buffer[packet.pos_buffer+8]+9/*is this right*/;
2943         //      if (h264) Log::getInstance()->log("Video", Log::DEBUG, "PES info %x %x %x %x",
2944         //                      buffer[packet.pos_buffer+0],buffer[packet.pos_buffer+1],buffer[packet.pos_buffer+2],buffer[packet.pos_buffer+3]);
2945                 *samplepos+=headerstrip;
2946                 if (headerstrip>=packet.length) {
2947                      *samplepos=packet.length;// Packet is obviously damaged
2948                      return packet.length;//skip it!
2949                 }
2950                 if ( packet.synched ) {
2951                         if (!firstsynched) {
2952                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 2a");
2953                           // check if this is an I frame, the decoder does not like non I frames at startup!
2954                           if (!detectIFrame(buffer,packet.length)) {
2955                                   *samplepos=packet.length;//if we have not processed at least one
2956                                   //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 3");
2957                                   return packet.length;//synched packet ignore it!
2958                           }
2959                         }
2960                         if (cur_input_buf_omx) {
2961                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 4a");
2962                                 cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_ENDOFFRAME;
2963                                 PutBufferToPres(cur_input_buf_omx);
2964                                 cur_input_buf_omx=NULL;//write out old data
2965
2966                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 4b");
2967
2968                         }
2969                         firstsynched=true;
2970                 } else {
2971                         if (!firstsynched) {//
2972                                 *samplepos=packet.length;//if we have not processed at least one
2973                                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 5");
2974                                 return packet.length;//synched packet ignore it!
2975                         }
2976                 }
2977         }
2978         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 6");
2979         if (!cur_input_buf_omx) {
2980                 input_bufs_omx_mutex.Lock();
2981                 if (input_bufs_omx_free.size()==0) {
2982                         input_bufs_omx_mutex.Unlock();
2983                         //Log::getInstance()->log("Video", Log::DEBUG, "Deliver MediaPacket no free sample");
2984                         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 7");
2985                         return 0; // we do not have a free media sample
2986
2987                 }
2988                 cur_input_buf_omx=input_bufs_omx_free.front();
2989                 cur_input_buf_omx->nFilledLen=0;
2990                 cur_input_buf_omx->nOffset=0;
2991                 cur_input_buf_omx->nTimeStamp=intToOMXTicks(0);
2992                 input_bufs_omx_free.pop_front();
2993                 input_bufs_omx_mutex.Unlock();
2994         }
2995
2996
2997
2998
2999         if (cur_input_buf_omx->nFilledLen==0) {//will only be changed on first packet
3000                 if (packet.synched) {
3001                 //      Log::getInstance()->log("Video", Log::DEBUG, "packet synched marker");
3002
3003                         //lastreftimePTS=packet.pts;
3004                    if (omx_first_frame) { // TODO time
3005                            cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_STARTTIME;
3006                            Log::getInstance()->log("Video", Log::DEBUG, "Starttime");
3007                            omx_first_frame=false;
3008                    } else {
3009                            cur_input_buf_omx->nFlags=0;
3010                            //cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_TIME_UNKNOWN;
3011                    }
3012                    lastreftimeOMX=packet.presentation_time;
3013                   // Log::getInstance()->log("Video", Log::DEBUG, "Time code %lld pts %lld", lastreftimeOMX,packet.pts);
3014                    lastreftimePTS=packet.pts;
3015                    cur_input_buf_omx->nTimeStamp=intToOMXTicks(lastreftimeOMX/10LL); // the clock component is faulty;
3016                 }
3017                 else
3018                 {
3019                         cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_TIME_UNKNOWN;
3020                         cur_input_buf_omx->nTimeStamp=intToOMXTicks(0);
3021                         //Log::getInstance()->log("Video", Log::DEBUG, "packet unsynched marker");
3022                 }
3023                 if (packet.disconti) cur_input_buf_omx->nFlags|=OMX_BUFFERFLAG_DISCONTINUITY;
3024
3025
3026
3027         }
3028         unsigned int haveToCopy=packet.length-*samplepos;
3029         //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 8");
3030
3031         while (haveToCopy> (cur_input_buf_omx->nAllocLen-cur_input_buf_omx->nFilledLen)) {
3032                 //Log::getInstance()->log("Video", Log::DEBUG, "Big buffer %d %d %d",packet.length,cur_input_buf_omx->nAllocLen,cur_input_buf_omx->nFilledLen);
3033                 unsigned int cancopy=cur_input_buf_omx->nAllocLen-cur_input_buf_omx->nFilledLen;
3034                 memcpy(cur_input_buf_omx->pBuffer+cur_input_buf_omx->nFilledLen,buffer+packet.pos_buffer+*samplepos,cancopy);
3035                 haveToCopy-=cancopy;
3036                 cur_input_buf_omx->nFilledLen+=cancopy;
3037                 *samplepos+=cancopy;
3038                 // push old buffer out
3039                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 9");
3040
3041                 PutBufferToPres(cur_input_buf_omx);
3042                 cur_input_buf_omx=NULL;
3043                 // get5 new buffer
3044                 input_bufs_omx_mutex.Lock();
3045                 if (input_bufs_omx_free.size()==0) {
3046                         input_bufs_omx_mutex.Unlock();
3047                 //      Log::getInstance()->log("Video", Log::DEBUG, "Deliver MediaPacket no free sample2");
3048                         return *samplepos; // we do not have a free media sample
3049                 }
3050                 cur_input_buf_omx=input_bufs_omx_free.front();
3051                 cur_input_buf_omx->nFilledLen=0;
3052                 cur_input_buf_omx->nOffset=0;
3053                 cur_input_buf_omx->nFlags=OMX_BUFFERFLAG_TIME_UNKNOWN;
3054                 cur_input_buf_omx->nTimeStamp=intToOMXTicks(0);
3055                 input_bufs_omx_free.pop_front();
3056                 input_bufs_omx_mutex.Unlock();
3057                 //Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 10");
3058
3059         }
3060         memcpy(cur_input_buf_omx->pBuffer+cur_input_buf_omx->nFilledLen,
3061                         buffer+packet.pos_buffer+*samplepos,haveToCopy);
3062         cur_input_buf_omx->nFilledLen+=haveToCopy;
3063
3064 //      Log::getInstance()->log("Video", Log::DEBUG, "DMP mark 11");
3065
3066         *samplepos+=haveToCopy;
3067
3068         return *samplepos;
3069
3070 }
3071
3072
3073
3074
3075 bool VideoOMX::displayIFrame(const UCHAR* buffer, UINT length) {
3076         if (!omx_running) return false;
3077         if (!iframemode)
3078                 EnterIframePlayback();
3079
3080         //int haveToCopy = length;
3081
3082         if (!cur_input_buf_omx) {
3083                 input_bufs_omx_mutex.Lock();
3084                 if (input_bufs_omx_free.size() == 0) {
3085                         input_bufs_omx_mutex.Unlock();
3086                 //      Log::getInstance()->log("Video", Log::DEBUG,
3087                         //              "Deliver MediaPacket no free sample");
3088                         return false; // we do not have a free media sample
3089
3090                 }
3091                 cur_input_buf_omx = input_bufs_omx_free.front();
3092                 cur_input_buf_omx->nFilledLen = 0;
3093                 cur_input_buf_omx->nOffset = 0;
3094                 cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3095                 input_bufs_omx_free.pop_front();
3096                 input_bufs_omx_mutex.Unlock();
3097         }
3098
3099         int read_pos = 0;
3100         unsigned int pattern, packet_length;
3101         unsigned int headerstrip = 0;
3102         bool first = true;
3103         if (length < 4){
3104                 return false;
3105         }
3106         //Now we strip the pes header
3107         pattern = (buffer[0] << 16) | (buffer[1] << 8) | (buffer[2]);
3108         while ((read_pos + 7) <= (int)length) {
3109                 pattern = ((pattern << 8) & 0xFFFFFFFF) | buffer[read_pos + 3];
3110                 if (pattern < 0x000001E0 || pattern > 0x000001EF) {
3111                         read_pos++;
3112                         continue;
3113                 } else {
3114                         headerstrip = buffer[read_pos + 8] + 9/*is this right*/;
3115                         packet_length = ((buffer[read_pos + 4] << 8)
3116                                         | (buffer[read_pos + 5])) + 6;
3117                         if (read_pos + packet_length > length)
3118                                 read_pos = length;
3119                         else {
3120                                 if ((headerstrip < packet_length)
3121                                                 && (cur_input_buf_omx->nFilledLen + packet_length
3122                                                                 - headerstrip) > cur_input_buf_omx->nAllocLen) {
3123                                         if (first) {
3124                                                 cur_input_buf_omx->nFlags = OMX_BUFFERFLAG_STARTTIME;
3125
3126                                         } else {
3127                                                 cur_input_buf_omx->nFlags
3128                                                                 |= OMX_BUFFERFLAG_TIME_UNKNOWN;
3129
3130                                         }
3131                                         cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3132                                         PutBufferToPres(cur_input_buf_omx);
3133                                         cur_input_buf_omx = NULL;
3134
3135                                         if (!cur_input_buf_omx) {
3136                                                 int count = 0;
3137                                                 while (count < 100 && omx_running && iframemode) {
3138                                                         count++;
3139
3140                                                         input_bufs_omx_mutex.Lock();
3141                                                         if (input_bufs_omx_free.size() == 0) {
3142                                                                 input_bufs_omx_mutex.Unlock();
3143                                         //                      Log::getInstance()->log("Video", Log::DEBUG,
3144                                                 //                              "Ifrane no free sample");
3145                                                                 MILLISLEEP(5);
3146                                                                 if (!omx_running) return false;
3147                                                                 continue;
3148                                                         }
3149                                                         cur_input_buf_omx = input_bufs_omx_free.front();
3150                                                         cur_input_buf_omx->nFilledLen = 0;
3151                                                         cur_input_buf_omx->nOffset = 0;
3152                                                         cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3153                                                         cur_input_buf_omx->nFlags|= OMX_BUFFERFLAG_TIME_UNKNOWN;
3154                                                         input_bufs_omx_free.pop_front();
3155                                                         input_bufs_omx_mutex.Unlock();
3156                                                         break;
3157                                                 }
3158                                                 if (!cur_input_buf_omx)
3159                                                         return false;
3160                                         }
3161
3162                                 }
3163                                 if (packet_length > headerstrip) {
3164                                         memcpy(
3165                                                         cur_input_buf_omx->pBuffer
3166                                                                         + cur_input_buf_omx->nFilledLen,
3167                                                         buffer + read_pos + headerstrip,
3168                                                         packet_length - headerstrip);
3169                                         cur_input_buf_omx->nFilledLen += packet_length
3170                                                         - headerstrip;
3171                                 }
3172                                 read_pos += packet_length;
3173
3174                                 pattern = (buffer[read_pos] << 16)
3175                                                 | (buffer[read_pos + 1] << 8) | (buffer[read_pos + 2]);
3176                         }
3177                 }
3178         }
3179
3180         if (first) {
3181                 cur_input_buf_omx->nFlags = OMX_BUFFERFLAG_STARTTIME;
3182
3183         } else {
3184                 cur_input_buf_omx->nFlags |= OMX_BUFFERFLAG_TIME_UNKNOWN;
3185
3186         }
3187         cur_input_buf_omx->nTimeStamp = intToOMXTicks(0);
3188
3189         PutBufferToPres(cur_input_buf_omx);
3190         cur_input_buf_omx = NULL;
3191
3192
3193         MILLISLEEP(40); //Block a bit
3194         return true;
3195 }
3196
3197 int VideoOMX::EnterIframePlayback()
3198 {
3199         Log::getInstance()->log("Video", Log::DEBUG,
3200                                                 "EnterIframePlayback");
3201         if (cur_input_buf_omx) {
3202                 PutBufferToPres(cur_input_buf_omx);
3203                 cur_input_buf_omx = NULL;
3204         }
3205         Log::getInstance()->log("Video", Log::DEBUG,
3206                                                         "EnterIframePlayback 2");
3207         ((AudioOMX*)Audio::getInstance())->DeAllocateCodecsOMX();
3208         DeAllocateCodecsOMX();
3209         AllocateCodecsOMX();
3210         Log::getInstance()->log("Video", Log::DEBUG,
3211                                                         "leave IframePlayback");
3212
3213         iframemode=true;
3214
3215         return 1;
3216 }
3217