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