def __init__(self): AGService.__init__(self) self.capabilities = [Capability(Capability.PRODUCER, Capability.VIDEO)] if IsWindows(): vic = "smash-5.2.exe" else: vic = "smash-5.2" self.executable = os.path.join(os.getcwd(), vic) self.sysConf = SystemConfig.instance() # Set configuration parameters # note: the datatype of the port parameter changes when a resource is set! self.streamname = TextParameter("streamname", "Video") self.port = TextParameter("port", "") self.encoding = OptionSetParameter("encoding", "h261", VideoProducerService.encodings) self.standard = OptionSetParameter("standard", "NTSC", VideoProducerService.standards) self.bandwidth = RangeParameter("bandwidth", 800, 0, 3072) self.framerate = RangeParameter("framerate", 24, 1, 30) self.quality = RangeParameter("quality", 75, 1, 100) self.configuration.append(self.streamname) self.configuration.append(self.port) self.configuration.append(self.encoding) self.configuration.append(self.standard) self.configuration.append(self.bandwidth) self.configuration.append(self.framerate) self.configuration.append(self.quality) self.profile = None
def _ping(self, host): ''' Invoke system ping command to host @param host: machine to ping @type host: string @return: average time for ping command @rtype: string ''' if IsOSX() or IsLinux() or IsFreeBSD(): # osx and linux ping command have the # same output format # time out after 10 sec if IsOSX() or IsFreeBSD(): cmd = 'ping -o -t 1 %s' % (host) else: cmd = 'ping -c 1 -w 1 %s' % (host) ret = self._execCmd(cmd) if ret.find('unknown host') > -1: self.log.info("Ping: Host %s not found" % (host)) raise Exception, "Ping: Host %s not found" % (host) if ret.find('100%') > -1: self.log.info("Ping: Host %s timed out" % (host)) raise Exception, "Ping: Host %s timed out" % (host) # Find average round trip time i = ret.find('time') ret = ret[i:] ret = ret.split('=')[1] ret = ret.split()[0] val = float(ret) / 1000 if IsWindows(): cmd = 'ping -n 1 %s' % (host) ret = self._execCmd(cmd) if ret.find('could not find') > -1: self.log.info("Ping: Host %s not found" % (host)) raise Exception, "Ping: Host %s not found" % (host) # windows times out automatically if ret.find('timed out') > -1: self.log.info("Ping: Host %s timed out" % (host)) raise Exception, "Ping: Host %s timed out" % (host) # Find average round trip time a = ret.find('Average') ret = ret[a:] val = ret.split('=')[1] val = filter(lambda x: x.isdigit(), val) val = float(val) return val
def SetIcon(app): icon = None if IsWindows() or IsLinux() or IsFreeBSD(): icon = icons.getAGIconIcon() app.SetIcon(icon) elif IsOSX(): icon = icons.getAGIcon128Icon() t = wx.TaskBarIcon() t.SetIcon(icon, "VenueClient")
def __SetRightScroll(self): ''' Scrolls to right position in text output field ''' if IsWindows(): # Added due to wx.Python bug. The wx.TextCtrl doesn't # scroll properly when the wx.TE_AUTO_URL flag is set. self.textCtrl.ScrollLines(-1)
def ForceStop(self): """ Forcefully stop the service """ if IsWindows(): # windows : do nothing special to force stop; it's forced anyway AGService.Stop(self) elif IsLinux() or IsOSX() or IsFreeBSD(): # linux : kill, instead of terminating self.started = 0 self.processManager.KillAllProcesses()
def RunPython(self,cmd,args): if IsOSX(): command=sys.executable elif IsWindows(): command="pythonw"; else: command="python"; print "Run: %s"%(cmd); print "args: ", print args; self.processManager.StartProcess(command,[cmd]+args);
def __init__(self): Application.__init__(self) # Register .agpkg mime type if not IsWindows(): agpmFile = os.path.join(AGTkConfig.instance().GetBinDir(), "agpm3.py") agpmCmd = agpmFile + " --gui --package %f" MimeConfig.instance().RegisterMimeType( "application/x-ag3-pkg", ".agpkg3", "agpkg file", "Access Grid Package", [("agpm3.py", agpmCmd, "open")]) # Register .vv3d if not IsWindows(): vcFile = os.path.join(AGTkConfig.instance().GetBinDir(), "GoToVenue3.py") vcCmd = vcFile + " --file %f" MimeConfig.instance().RegisterMimeType( "application/x-ag-venueclient", ".vv3d", "AG Virtual Venues File", "Access Grid Virtual Venue Description", [("GoToVenue.py", vcCmd, "Open")])
def __SetRTPDefaults(self, profile): """ Set values used by rat for identification Note: OpenMash sets rtpName/rtpEmail in ~/.mash/prefs """ if profile == None: self.log.exception("Invalid profile (None)") raise Exception, "Can't set RTP Defaults without a valid profile." if IsLinux(): try: rtpDefaultsFile = os.path.join(os.environ["HOME"], ".RTPdefaults") rtpDefaultsText = "*rtpName: %s\n*rtpEmail: %s\n*rtpLoc: %s\n*rtpPhone: \ %s\n*rtpNote: %s\n" rtpDefaultsFH = open(rtpDefaultsFile, "w") rtpDefaultsFH.write( rtpDefaultsText % (profile.name, profile.email, profile.location, profile.phoneNumber, profile.publicId)) rtpDefaultsFH.close() except: self.log.exception("Error writing RTP defaults file: %s", rtpDefaultsFile) elif IsWindows(): try: # # Set RTP defaults according to the profile # k = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, r"Software\Mbone Applications\common") # Vic reads these values (with '*') _winreg.SetValueEx(k, "*rtpName", 0, _winreg.REG_SZ, profile.name) _winreg.SetValueEx(k, "*rtpEmail", 0, _winreg.REG_SZ, profile.email) _winreg.SetValueEx(k, "*rtpPhone", 0, _winreg.REG_SZ, profile.phoneNumber) _winreg.SetValueEx(k, "*rtpLoc", 0, _winreg.REG_SZ, profile.location) _winreg.SetValueEx(k, "*rtpNote", 0, _winreg.REG_SZ, str(profile.publicId)) _winreg.CloseKey(k) except: self.log.exception("Error writing RTP defaults to registry") else: self.log.error("No support for platform: %s", sys.platform)
def RunPythonDebug(self,cmd,args): if IsOSX(): pass; #command="/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal"; elif IsWindows(): command="start"; else: command="python"; if IsOSX(): command2=sys.executable elif IsWindows(): command2="pythonw"; else: command2=""; print "DEBUG: %s"%(cmd); print "args: ", print args; if command2: self.processManager.StartProcess(command,[command2,cmd]+args); else: self.processManager.StartProcess(command,[cmd]+args);
def __init__(self, parent): wx.Dialog.__init__(self, parent, -1, "Bug Report") self.text = wx.StaticText( self, -1, "Please, enter a description of the problem you are experiencing. You may \nreceive periodic mailings from us with information on this problem. If you \ndo not wish to be contacted, please leave the 'E-mail' field blank.", style=wx.ALIGN_LEFT) self.commentBox = wx.TextCtrl(self, -1, "", size=wx.Size(300, 100), style=wx.TE_MULTILINE, validator=TextValidator()) self.line = wx.StaticLine(self, -1) # I have to add this due to a wxPython bug. A wx.TextCtrl that # has wx.TE_MULTILINE flag set ignores focus of next child. If # I don't have tmp, the email text ctrl will never get focus # when you use the TAB key. -- if IsWindows(): temp = wx.BitmapButton(self, -1, wx.EmptyBitmap(1, 1), size=wx.Size(1, 1)) # -- self.commentText = wx.StaticText(self, -1, "Comment:") self.emailText = wx.StaticText(self, -1, "E-mail:") self.emailBox = wx.TextCtrl(self, -1, "") self.infoText = wx.StaticText( self, -1, "For more information on bugs, visit http://bugzilla.mcs.anl.gov/AccessGrid " ) self.okButton = wx.Button(self, wx.ID_OK, "Ok") self.cancelButton = wx.Button(self, wx.ID_CANCEL, "Cancel") self.Centre() self.Layout()
def __init__(self,vncserverexe,displayID,geometry="1024x768",depth=24): # Initialize the vncserver executable self.vncserverexe = vncserverexe # Initialize the contact string, construct it from the hostname and the # display ID hostname=Toolkit.CmdlineApplication.instance().GetHostname() if IsWindows(): self.contactString="%s"%(hostname,) elif IsOSX(): self.contactString="%s"%(hostname,) elif IsLinux() or IsFreeBSD(): self.contactString="%s%s"%(hostname,displayID) self.displayID=displayID # Initialize internal representation of the desired geometry self.geometry={} (tmpWidth,tmpHeight)=geometry.split('x') self.geometry["Width"]=eval(tmpWidth) self.geometry["Height"]=eval(tmpHeight) # And depth self.depth=depth # Initialize other random bits, mostly path/file names self.guid=str(GUID()) self.passwdFilename = None # Initialize the password file. self.genPassword() self.processManager = ProcessManager() self.running = 0
def __init__( self, appUrl, clientProfile ): self.appUrl = appUrl self.appProxy=SharedApplicationIW(self.appUrl) print( "Application URL: %s" %(self.appUrl) ) #print( "Application URL Valid? " + self.appProxy.isValid( ) ) # Join the application # ** NEW METHOD ** (self.publicId, self.privateId) = self.appProxy.Join(clientProfile) # ** OLD METHOD ** #self.privateId=self.appProxy.Join(ClientProfile('./profile')) # # Retrieve the channel id # (self.channelId, address, port ) = self.appProxy.GetDataChannel(self.privateId) # # Subscribe to the event channel # #self.eventClient = EventClient.EventClient(eventServiceLocation, self.channelId) #self.eventClient.start() #self.eventClient.Send(Events.ConnectEvent(self.channelId)) # # Register the 'view' event callback # # The callback function is invoked with one argument, the data from the call. #self.eventClient.RegisterCallback("view", self.ViewCallback ) # Get the connection state and print it self.vncContact = self.appProxy.GetData(self.privateId, "VNC_Contact"); self.vncGeometry = self.appProxy.GetData(self.privateId, "VNC_Geometry"); self.vncDepth = self.appProxy.GetData(self.privateId, "VNC_Depth"); # Read password from app object encoded_pwd = self.appProxy.GetData(self.privateId, "VNC_Pwd") print "VNC Server at %s (%s, %s-bits):"%(self.vncContact,self.vncGeometry,self.vncDepth); self.passwdFilename=os.path.join(UserConfig.instance().GetTempDir(), ("passwd-" + str(GUID()) + ".vnc")) # Write password to file so it can be passed to vnc. pwd_file = file(self.passwdFilename, 'wb') pwd_file.write(base64.decodestring(encoded_pwd)) pwd_file.close() # Change to the location of the application before running, since helper executables are located here. print "Running from directory", os.getcwd() execString = "" if IsWindows(): width=eval(self.vncGeometry.split('x')[0]); if width >= 5120: execString='vncviewer -shared -scale 1/4 -passwd %s %s'%(self.passwdFilename,self.vncContact) elif width >= 4096: execString='vncviewer -shared -scale 1/3 -passwd %s %s'%(self.passwdFilename,self.vncContact) elif width >= 3072: execString='vncviewer -shared -scale 1/2 -passwd %s %s'%(self.passwdFilename,self.vncContact) else: execString='vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact) elif IsLinux(): if os.path.exists("/usr/local/bin/vncviewer") or os.path.exists("/usr/bin/vncviewer"): execString='vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact) else: execString='chmod +x ./vncviewer; ./vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact) elif IsFreeBSD(): if os.path.exists("/usr/local/bin/vncviewer") or os.path.exists("/usr/X11R6/bin/vncviewer"): execString='vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact) else: execString='chmod +x ./vncviewer; ./vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact) elif IsOSX(): vncviewer='/Applications/Chicken\ of\ the\ VNC.app/Contents/MacOS/Chicken\ of\ the\ VNC' execString='%s --PasswordFile %s %s' % (vncviewer,self.passwdFilename,self.vncContact) else: raise Exception("Unsupported platform") print "About the execute: %s"%(execString) log.info("Starting vnc client: %s", execString) os.system(execString); os.unlink(self.passwdFilename);
def __init__( self ): AGService.__init__( self ) self.thepath = os.getcwd() self.capabilities = [ Capability( Capability.CONSUMER, Capability.VIDEO, "H261", 90000, self.id), Capability( Capability.PRODUCER, Capability.VIDEO, "H261", 90000, self.id)] if IsWindows(): vic = "vic.exe" else: vic = "vic" self.executable = os.path.join(os.getcwd(),vic) if not os.path.isfile(self.executable): self.executable = vic self.sysConf = SystemConfig.instance() self.profile = None self.windowGeometry = None self.startPriority = '7' self.startPriorityOption.value = self.startPriority self.id = str(GUID()) # Set configuration parameters # note: the datatype of the port parameter changes when a resource is set! self.streamname = TextParameter( "Stream Name", "" ) self.port = TextParameter( "port", "" ) self.encoding = OptionSetParameter( "Encoding", "h261", VideoService.encodingOptions ) if IsWindows(): standard = "PAL" else: standard = "NTSC" self.standard = OptionSetParameter( "Standard", standard, VideoService.standardOptions ) self.tiles = OptionSetParameter( "Thumbnail Columns", "4", VideoService.tileOptions ) self.bandwidth = RangeParameter( "Bandwidth", 800, 0, 3072 ) self.framerate = RangeParameter( "Frame Rate", 24, 1, 30 ) self.quality = RangeParameter( "Quality", 75, 1, 100 ) self.transmitOnStart = OptionSetParameter( "Transmit on Startup", "On", VideoService.onOffOptions ) self.muteSources = OptionSetParameter( "Mute Sources", "Off", VideoService.onOffOptions ) self.positionWindow = OptionSetParameter( 'Position Window', 'Justify Left', ['Off', 'Justify Left', 'Justify Right']) self.configuration.append( self.streamname ) self.configuration.append( self.port ) self.configuration.append( self.encoding ) self.configuration.append( self.standard ) self.configuration.append( self.tiles ) self.configuration.append( self.bandwidth ) self.configuration.append( self.framerate ) self.configuration.append (self.quality ) self.configuration.append (self.transmitOnStart ) self.configuration.append (self.muteSources ) self.configuration.append (self.positionWindow ) if IsWindows(): try: import win32api # get number of processors systemInfo = win32api.GetSystemInfo() numprocs = systemInfo[5] self.allProcsMask = 2**numprocs-1 self.procOptions = ['All'] for i in range(numprocs): self.procOptions.append(str(i+1)) self.processorUsage = OptionSetParameter( "Processor usage", self.procOptions[0], self.procOptions ) self.configuration.append( self.processorUsage ) except: self.log.exception('Error initializing processor usage options') self.__GetResources()
def start(self): log.debug('vncServer.start') if self.isRunning(): raise VNCServerException("Start attempted while already running") try: if IsWindows(): # Convert the password to hex for windows command line password = '' for ch in self.password: password += '%x' % (ord(ch),) args = [ 'Password='******'AlwaysShared=1', ] log.info("starting vnc server: %s %s" % (self.vncserverexe,args)) p = self.processManager.StartProcess(self.vncserverexe,args) log.debug(" pid = %s" % (p,)) elif IsOSX(): self.writePasswordFile() args = [ '-rfbauth', self.passwdFilename, '-alwaysshared', ] log.info("starting vnc server: %s %s" % (self.vncserverexe,args)) p = self.processManager.StartProcess(self.vncserverexe,args) log.debug(" pid = %s" % (p,)) elif IsLinux() or IsFreeBSD(): # Add entry in the xauthority file similar to the way # vncserver does. cookie = commands.getoutput("/usr/bin/mcookie") hostname = commands.getoutput("uname -n") command = "xauth add %s%s . %s" % (hostname, self.displayID, cookie) os.system(command) command = "xauth add %s/unix%s . %s" %(hostname, self.displayID, cookie) os.system(command) self.writePasswordFile() args = [ self.displayID, '-geometry', '%dx%d' % (self.geometry['Width'],self.geometry['Height']), '-depth', self.depth, '-rfbauth', self.passwdFilename, '-alwaysshared' ] log.info("starting vnc server: %s %s" % (self.vncserverexe,args)) p = self.processManager.StartProcess(self.vncserverexe,args) log.debug(" pid = %s" % (p,)) # Wait, then run xstartup time.sleep(2) # set paths to find config files venuevnc_path = os.path.join(os.environ["HOME"], ".venuevnc") xstartup = os.path.join(venuevnc_path, "xstartup") # if xstartup file does not exist, create one. if not os.path.exists(xstartup): log.info("Creating xstartup file") if not os.path.exists(venuevnc_path): os.mkdir(venuevnc_path) f = file(xstartup, "w+") # default is the same as tight vnc's default, but use mwm # instead of twm if it is available windowmanager = "twm" if os.path.exists("/usr/X11R6/bin/mwm") or os.path.exists("/usr/bin/mwm"): windowmanager = "mwm -xrm 'Mwm*usePager: false' -xrm 'Mwm*edgeScrollX:0' -xrm 'Mwm*edgeScrollY:0' " defaultStartup= "#!/bin/sh\n\n" + \ "#xrdb $HOME/.Xresources\n" + \ "xsetroot -solid grey\n" + \ "xterm -geometry 80x24+10+10 -ls -title \"VenueVNC Desktop\" &\n" + \ windowmanager + " &\n" f.write(defaultStartup) f.close() os.chmod(xstartup,0755) else: log.info("Using existing xstartup file") os.environ["DISPLAY"] = self.displayID if os.path.exists(xstartup): log.info("Running x startup script %s" % ( xstartup,)) self.processManager.StartProcess(xstartup,[]) else: log.info("Running MWM") self.processManager.StartProcess('mwm',[]) self.running = 1 except: log.exception("Failed to start vncServer") raise
def __init__(self): AGService.__init__(self) self.thepath = os.getcwd() if IsWindows(): vic = "vic.exe" else: vic = "vic" self.executable = os.path.join(os.getcwd(), vic) if not os.path.isfile(self.executable): self.executable = vic proc = subprocess.Popen([self.executable, '-Q'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.deviceDOM = xml.dom.minidom.parse(proc.stdout) self.encodingOptions = [] self.capabilities = [] codecs = self.deviceDOM.getElementsByTagName("codec") for codec in codecs: if codec.childNodes[0].nodeType == xml.dom.minidom.Node.TEXT_NODE: if codec.childNodes[0].data in ['h263', 'h263+', 'raw', 'pvh']: continue self.encodingOptions.append(codec.childNodes[0].data) self.capabilities.append( Capability(Capability.CONSUMER, Capability.VIDEO, codec.childNodes[0].data.upper(), 90000, self.id)) self.capabilities.append( Capability(Capability.PRODUCER, Capability.VIDEO, codec.childNodes[0].data.upper(), 90000, self.id)) self.sysConf = SystemConfig.instance() self.profile = None self.windowGeometry = None self.startPriority = '7' self.startPriorityOption.value = self.startPriority self.id = str(GUID()) self.resolution = None # Set configuration parameters # note: the datatype of the port, standard and inputsize parameters change when a resource is set! self.streamname = TextParameter("Stream Name", "") self.port = TextParameter("port", "") self.encoding = OptionSetParameter("Encoding", "mpeg4", self.encodingOptions) self.standard = TextParameter("standard", "") self.tiles = OptionSetParameter("Thumbnail Columns", "4", VideoServiceH264.tileOptions) self.bandwidth = RangeParameter("Bandwidth", 2500, 0, 10240) self.framerate = RangeParameter("Frame Rate", 24, 1, 30) self.quality = RangeParameter("Quality", 75, 1, 100) self.transmitOnStart = OptionSetParameter( "Transmit on Startup", "On", VideoServiceH264.onOffOptions) self.muteSources = OptionSetParameter("Mute Sources", "Off", VideoServiceH264.onOffOptions) self.inputsize = TextParameter("inputsize", "") self.positionWindow = OptionSetParameter( 'Position Window', 'Justify Left', ['Off', 'Justify Left', 'Justify Right']) self.encodingDeinterlacer = OptionSetParameter( "Encoding Deinterlacer", "Off", VideoServiceH264.onOffOptions) self.configuration.append(self.streamname) self.configuration.append(self.port) self.configuration.append(self.encoding) self.configuration.append(self.standard) self.configuration.append(self.tiles) self.configuration.append(self.bandwidth) self.configuration.append(self.framerate) self.configuration.append(self.quality) self.configuration.append(self.transmitOnStart) self.configuration.append(self.muteSources) self.configuration.append(self.inputsize) self.configuration.append(self.positionWindow) self.configuration.append(self.encodingDeinterlacer) if IsWindows(): try: import win32api # get number of processors systemInfo = win32api.GetSystemInfo() numprocs = systemInfo[5] self.allProcsMask = 2**numprocs - 1 self.procOptions = ['All'] for i in range(numprocs): self.procOptions.append(str(i + 1)) self.processorUsage = OptionSetParameter( "Processor usage", self.procOptions[0], self.procOptions) self.configuration.append(self.processorUsage) except: self.log.exception( 'Error initializing processor usage options') self.__GetResources() self.deviceDOM.unlink()
def SetResource(self, resource): """ Set the resource used by this service """ self.log.info("VideoServiceH264.SetResource : %s" % resource.name) for r in self.resources: if r[0].strip() == resource.name: self.resource = r # Find the config element that refers to "port" try: index = self.configuration.index(self.port) found = 1 except ValueError: found = 0 # Create the port parameter as an option set parameter, now # that we have multiple possible values for "port" # If self.port is valid, keep it instead of setting the default value. if ((isinstance(self.port, TextParameter) or isinstance(self.port, ValueParameter)) and self.port.value != "" and self.port.value in self.resource[1]): self.port = OptionSetParameter("Port", self.port.value, self.resource[1]) else: self.port = OptionSetParameter("Port", self.resource[1][0], self.resource[1]) self.log.info('port = %s', self.port.value) # Replace or append the "port" element if found: self.configuration[index] = self.port else: self.configuration.append(self.port) # Find the config element that refers to "standard" try: index = self.configuration.index(self.standard) found = 1 except ValueError: found = 0 # Create the standard parameter as an option set parameter, now # that we have multiple possible values for "standard" # If self.standard is valid, keep it instead of setting the default value. if ((isinstance(self.standard, TextParameter) or isinstance(self.standard, ValueParameter)) and self.standard.value != "" and self.standard.value in self.resource[2]): self.standard = OptionSetParameter("Standard", self.standard.value, self.resource[2]) else: if (IsWindows() and "PAL" in self.resource[2]): self.standard = OptionSetParameter("Standard", "PAL", self.resource[2]) else: self.standard = OptionSetParameter("Standard", self.resource[2][0], self.resource[2]) self.log.info('standard = %s', self.standard.value) # Replace or append the "standard" element if found: self.configuration[index] = self.standard else: self.configuration.append(self.standard) # Find the config element that refers to "inputsize" try: index = self.configuration.index(self.inputsize) found = 1 except ValueError: found = 0 # Create the inputsize parameter as an option set parameter, now # that we have multiple possible values for "inputsize" # If self.inputsize is valid, keep it instead of setting the default value. if ((isinstance(self.inputsize, TextParameter) or isinstance(self.inputsize, ValueParameter)) and self.inputsize.value != "" and self.inputsize.value in self.resource[3]): self.inputsize = OptionSetParameter("Capture Size", self.inputsize.value, self.resource[3]) else: if ("Medium" in self.resource[3]): self.inputsize = OptionSetParameter("Capture Size", "Medium", self.resource[3]) else: self.inputsize = OptionSetParameter("Capture Size", self.resource[3][0], self.resource[3]) self.log.info('inputsize = %s', self.inputsize.value) # Replace or append the "inputsize" element if found: self.configuration[index] = self.inputsize else: self.configuration.append(self.inputsize) if len(self.resource[4]) > 0: # Find the config element that refers to "resolution" try: index = self.configuration.index(self.resolution) found = 1 except ValueError: found = 0 except AttributeError: found = 0 # Create the resolution parameter as an option set parameter, now # that we have multiple possible values for "resolution" # If self.resolution is valid, keep it instead of setting the default value. if ((isinstance(self.resolution, TextParameter) or isinstance(self.resolution, ValueParameter)) and self.resolution.value != "" and self.resolution.value in self.resource[4]): self.resolution = OptionSetParameter( "Large Size/Scaler Resolution", self.resolution.value, self.resource[4]) else: self.resolution = OptionSetParameter( "Large Size/Scaler Resolution", self.resource[4][0], self.resource[4]) self.log.info('resolution = %s', self.resolution.value) # Replace or append the "resolution" element if found: self.configuration[index] = self.resolution else: self.configuration.append(self.resolution) # If the stream name has not been set, set it to the resource name if not self.streamname.value: self.streamname.value = resource.name
def __init__( self ): AGService.__init__( self ) if IsWindows(): vic = "vic.exe" else: vic = "vic" self.executable = os.path.join(os.getcwd(),vic) if not os.path.isfile(self.executable): self.executable = vic proc = subprocess.Popen([self.executable, '-Q'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) deviceDOM = xml.dom.minidom.parse(proc.stdout) self.capabilities = [] codecs = deviceDOM.getElementsByTagName("codec") for codec in codecs: if codec.childNodes[0].nodeType == xml.dom.minidom.Node.TEXT_NODE: if codec.childNodes[0].data in ['h263', 'h263+', 'raw', 'pvh']: continue self.capabilities.append(Capability( Capability.CONSUMER, Capability.VIDEO, codec.childNodes[0].data.upper(), 90000, self.id)) deviceDOM.unlink() self.sysConf = SystemConfig.instance() self.profile = None self.windowGeometry = None self.startPriority = '7' self.startPriorityOption.value = self.startPriority # Set configuration parameters self.tiles = OptionSetParameter( "Thumbnail Columns", "4", VideoConsumerServiceH264.tileOptions ) self.positionWindow = OptionSetParameter( 'Position Window', 'Justify Left', ['Off', 'Justify Left', 'Justify Right']) self.configuration.append( self.tiles ) self.configuration.append( self.positionWindow) if IsWindows(): try: import win32api # get number of processors systemInfo = win32api.GetSystemInfo() numprocs = systemInfo[5] self.allProcsMask = 2**numprocs-1 self.procOptions = ['All'] for i in range(numprocs): self.procOptions.append(str(i+1)) self.processorUsage = OptionSetParameter( "Processor usage", self.procOptions[0], self.procOptions ) self.configuration.append( self.processorUsage ) except: self.log.exception('Error initializing processor usage options')
def Start( self ): """Start service""" try: # Set processor affinity (windows only) if IsWindows(): try: if self.processorUsage.value == 'All': self.log.info('Setting processor affinity to all processors') SystemConfig.instance().SetProcessorAffinity(self.allProcsMask) else: val = 2**(int(self.processorUsage.value)-1) self.log.info('Ssetting processor affinity : use processor %s', self.processorUsage.value) SystemConfig.instance().SetProcessorAffinity(int(self.processorUsage.value)) except: self.log.exception("Exception setting processor affinity") # Enable firewall self.sysConf.AppFirewallConfig(self.executable, 1) # Start the service; in this case, store command line args # in a list and let the superclass _Start the service options = [] if self.streamDescription.name and \ len(self.streamDescription.name.strip()) > 0: options.append( "-C" ) options.append( self.streamDescription.name ) if self.streamDescription.encryptionFlag != 0: options.append( "-K" ) options.append( self.streamDescription.encryptionKey ) # Check whether the network location has a "type" # attribute Note: this condition is only to maintain # compatibility between older venue servers creating # network locations without this attribute and newer # services relying on the attribute; it should be removed # when the incompatibility is gone if self.streamDescription.location.__dict__.has_key("type"): if self.streamDescription.location.type == MulticastNetworkLocation.TYPE: options.append( "-t" ) options.append( '%d' % ( self.streamDescription.location.ttl ) ) # Set name and email on command line, in case rtp defaults # haven't been written (to avoid vic prompting for # name/email) name=email="Participant" if self.profile: name = self.profile.name email = self.profile.email options.append('-XrtpName=%s' % (name,)) options.append('-XrtpEmail=%s' % (email,)) # Set some tk resources to customize vic # - this is a consumer, so disable device selection in vic options.append('-XrecvOnly=1') # - set drop time to something reasonable options.append('-XsiteDropTime=5') if not self.positionWindow.value == 'Off': # - set vic window geometry try: if not self.windowGeometry: h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y) w_sys = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X) try: w = GetScreenWidth(w_sys,h) except ValueError: self.log.debug('Error computing screen width; using system screen width %d', w_sys) w = w_sys window_width = w-300 window_height = 300 window_x = 300 window_y = h-375 border_w = wx.SystemSettings_GetMetric(wx.SYS_FRAMESIZE_X) if border_w > 0: window_width -= 4*border_w window_x += 2*border_w self.windowGeometry = (window_width,window_height,window_x,window_y) if self.positionWindow.value == 'Justify Left': options.append('-Xgeometry=%dx%d+%d+%d' % self.windowGeometry) else: options.append('-Xgeometry=%dx%d-%d+%d' % self.windowGeometry) except: self.log.exception('Error calculating window placement') # - set number of columns of thumbnails to display options.append('-Xtile=%s' % self.tiles.value) # Add address/port options (these must occur last; don't # add options beyond here) options.append( '%s/%d' % (self.streamDescription.location.host, self.streamDescription.location.port)) # Create a socket, send some data out, and listen for incoming data try: host = self.streamDescription.location.host port = self.streamDescription.location.port timeout = 1 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if IsOSX(): s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) s.bind(('', port)) s.sendto('qwe',(host,port)) fdList = [] while not fdList: fdList = select.select([s.fileno()],[],[],timeout) s.close() s = None except: self.log.warn("Failed attempt to open firewall by sending data out on video port; continuing anyway") if s: s.close() s = None self.log.info("Starting VideoConsumerServiceH264") self.log.info(" executable = %s" % self.executable) self.log.info(" options = %s" % options) self._Start( options ) except: self.log.exception("Exception in VideoConsumerServiceH264.Start") raise Exception("Failed to start service")
def Start(self): """Start service""" try: # Set processor affinity (windows only) if IsWindows(): try: if self.processorUsage.value == 'All': self.log.info( 'Setting processor affinity to all processors') SystemConfig.instance().SetProcessorAffinity( self.allProcsMask) else: val = 2**(int(self.processorUsage.value) - 1) self.log.info( 'Ssetting processor affinity : use processor %s', self.processorUsage.value) SystemConfig.instance().SetProcessorAffinity( int(self.processorUsage.value)) except: self.log.exception("Exception setting processor affinity") # Enable firewall self.sysConf.AppFirewallConfig(self.executable, 1) # Resolve assigned resource to a device understood by vic if self.resource == "None": vicDevice = "None" else: vicDevice = self.resource[0] vicDevice = vicDevice.replace("[", "\[") vicDevice = vicDevice.replace("]", "\]") if IsWindows(): try: self.MapWinDevice(self.resource[0]) except: self.log.exception("Exception mapping device") # # Write vic startup file # startupfile = os.path.join(UserConfig.instance().GetTempDir(), 'VideoProducerService_%s.vic' % self.id) f = open(startupfile, "w") if self.port.value == '': portstr = "None" else: portstr = self.port.value name = email = "Participant" if self.profile: name = self.profile.name email = self.profile.email else: # Error case name = email = Toolkit.GetDefaultSubject().GetCN() self.log.error("Starting service without profile set") f.write(vicstartup % ( self.bandwidth.value, self.framerate.value, self.quality.value, self.encoding.value, self.standard.value, vicDevice, "%s(%s)" % (name, self.streamname.value), email, email, portstr, portstr)) f.close() # Open permissions on vic startupfile os.chmod(startupfile, 0777) # Replace double backslashes in the startupfile name with single # forward slashes (vic will crash otherwise) if IsWindows(): startupfile = startupfile.replace("\\", "/") # # Start the service; in this case, store command line args in a list and let # the superclass _Start the service options = [] options.append("-u") options.append(startupfile) options.append("-C") options.append(str(self.streamname.value)) if IsOSX(): options.append("-X") options.append("transmitOnStartup=1") if self.streamDescription.encryptionFlag != 0: options.append("-K") options.append(self.streamDescription.encryptionKey) if self.profile: options.append("-X") options.append("site=%s" % self.profile.publicId) options.append('-X') options.append('noMulticastBind=true') # Check whether the network location has a "type" attribute # Note: this condition is only to maintain compatibility between # older venue servers creating network locations without this attribute # and newer services relying on the attribute; it should be removed # when the incompatibility is gone if self.streamDescription.location.__dict__.has_key("type"): # use TTL from multicast locations only if self.streamDescription.location.type == MulticastNetworkLocation.TYPE: options.append("-t") options.append('%d' % (self.streamDescription.location.ttl)) options.append('%s/%d' % (self.streamDescription.location.host, self.streamDescription.location.port)) self.log.info("Starting VideoProducerService") self.log.info(" executable = %s" % self.executable) self.log.info(" options = %s" % options) self._Start(options) #os.remove(startupfile) except: self.log.exception("Exception in VideoProducerService.Start") raise Exception("Failed to start service")
def Start(self): """Start service""" try: # Enable firewall self.sysConf.AppFirewallConfig(self.executable, 1) # Resolve assigned resource to a device understood by vic print "self.resource = ", type(self.resource), self.resource print "res = ", self.resource.resource if self.resource == "None": vicDevice = "None" else: vicDevice = self.resource.resource if IsLinux() and vicDevice.startswith('/dev/video'): # Translate vic device name to a name understood # by openmash (linux only) vicDeviceNum = vicDevice[-1] vicDevice = 'VideoCapture/V4l' + vicDeviceNum vicDevice = vicDevice.replace("[", "\[") vicDevice = vicDevice.replace("]", "\]") if IsWindows(): try: self.MapWinDevice(self.resource.resource) except: self.log.exception("Exception mapping device") # # Write vic startup file # startupfile = os.path.join( UserConfig.instance().GetTempDir(), 'VideoProducerService_%d.vic' % (os.getpid())) if self.port.value == '': portstr = "None" else: portstr = self.port.value name = email = "Participant" if self.profile: name = self.profile.name email = self.profile.email else: # Error case name = email = Toolkit.GetDefaultSubject().GetCN() self.log.error("Starting service without profile set") # Replace double backslashes in the startupfile name with single # forward slashes (vic will crash otherwise) if IsWindows(): startupfile = startupfile.replace("\\", "/") # # Start the service; in this case, store command line args in a list and let # the superclass _Start the service options = [] options.append("headlessVideo.mash") #options.append( "-u" ) #options.append( startupfile ) #options.append( "-C" ) #options.append( '"' + self.streamname.value + '"' ) if self.streamDescription.encryptionFlag != 0: options.append("-K") options.append(self.streamDescription.encryptionKey) # Check whether the network location has a "type" attribute # Note: this condition is only to maintain compatibility between # older venue servers creating network locations without this attribute # and newer services relying on the attribute; it should be removed # when the incompatibility is gone if self.streamDescription.location.__dict__.has_key("type"): # use TTL from multicast locations only if self.streamDescription.location.type == MulticastNetworkLocation.TYPE: options.append("-t") options.append('%d' % (self.streamDescription.location.ttl)) options.append('-F') options.append(self.framerate.value) options.append('-bps') options.append(self.bandwidth.value) options.append('-q') options.append(self.quality.value) options.append('-f') options.append(self.encoding.value) #options.append(' '); options.append(self.standard.value) #options.append('-D'); options.append(vicDevice) options.append('-D') options.append('VideoCapture/Test') options.append('-p') options.append('blue_passion') #options.append('-p'); options.append(portstr) options.append('-name') options.append("%s(%s)" % (name, self.streamname.value)) options.append('-email') options.append(email) options.append('-omft') options.append(self.standard.value) # Address/port is last option options.append('%s/%d' % (self.streamDescription.location.host, self.streamDescription.location.port)) self.log.info("Starting VideoProducerService") self.log.info(" executable = %s" % self.executable) self.log.info(" options = %s" % options) self._Start(options) #os.remove(startupfile) except: self.log.exception("Exception in VideoProducerService.Start") raise Exception("Failed to start service")
#----------------------------------------------------------------------------- # Name: Config.py # Purpose: Configuration objects for applications using the toolkit. # there are config objects for various sub-parts of the system. # Created: 2003/05/06 # RCS-ID: $Id: Config.py,v 1.6 2006-05-10 01:30:04 willing Exp $ # Copyright: (c) 2002 # Licence: See COPYING.TXT #----------------------------------------------------------------------------- """ """ __revision__ = "$Id: Config.py,v 1.6 2006-05-10 01:30:04 willing Exp $" import sys from AccessGrid.Platform import IsWindows, IsLinux, IsOSX, IsFreeBSD if IsWindows(): from AccessGrid.Platform.win32.Config import * elif IsLinux() or IsOSX() or IsFreeBSD(): from AccessGrid.Platform.unix.Config import * else: print "No support for Platform %s" % sys.platform
def StartExecutable(self): if not self.commandline: log.exception("Commandline is None.") return if len(self.commandline) == 0: log.exception("Commandline is empty.") return if not self.__venueClient or not self.__venueClientController: log.exception("Plugin has not been attached to a venue client.") return namedVars = dict() namedVars['python'] = sys.executable namedVars['pluginName'] = self.name namedVars['pluginDesc'] = self.description # This is NOT on every description type, so we're not using it yet # namedVars['appMimeType'] = objDesc.mimeType namedVars['localFilePath'] = self.directory namedVars['venueUrl'] = self.__venueClient.GetVenue() namedVars['venueClientUrl'] = self.__venueClient.GetWebServiceUrl() namedVars['connectionId'] = self.__venueClient.GetConnectionId() # We're doing some icky munging to make our lives easier # We're only doing this for a single occurance of a windows # environment variable prog = re.compile("\%[a-zA-Z0-9\_]*\%") result = prog.match(self.commandline) if result != None: subStr = result.group() realCommand = self.commandline.replace( subStr, "DORKYREPLACEMENT") % namedVars realCommand = realCommand.replace("DORKYREPLACEMENT", subStr) else: try: realCommand = self.commandline % namedVars except: import pprint log.exception( "Command failed, probably misconfigured. \ Tried to run, %s with named arguments %s", self.commandline, pprint.pformat(namedVars)) return if IsWindows(): #shell = os.environ['ComSpec'] #realCommand = "%s %s %s" % (shell, "/c", realCommand) log.info("StartCmd starting command: %s", realCommand) cmd = realCommand argList = [] else: log.info("StartCmd starting command: %s", realCommand) aList = realCommand.split(' ') cmd = aList[0] argList = aList[1:] olddir = os.getcwd() try: os.chdir(self.directory) except OSError, e: log.exception("Failed to change directory to %s." % self.directory) return
def Start(self): """ Start service """ try: # Set processor affinity (windows only) if IsWindows(): try: if self.processorUsage.value == 'All': self.log.info( 'Setting processor affinity to all processors') SystemConfig.instance().SetProcessorAffinity( self.allProcsMask) else: val = 2**(int(self.processorUsage.value) - 1) self.log.info( 'Ssetting processor affinity : use processor %s', self.processorUsage.value) SystemConfig.instance().SetProcessorAffinity( int(self.processorUsage.value)) except: self.log.exception("Exception setting processor affinity") # Enable firewall self.sysConf.AppFirewallConfig(self.executable, 1) # Resolve assigned resource to a device understood by vic if self.resource == "None": vicDevice = "None" else: vicDevice = self.resource[0] vicDevice = vicDevice.replace("[", "\[") vicDevice = vicDevice.replace("]", "\]") if IsWindows(): try: self.MapWinDevice(self.resource[0]) except: self.log.exception("Exception mapping device") # # Write vic startup file # startupfile = os.path.join(UserConfig.instance().GetTempDir(), 'VideoServiceH264_%s.vic' % self.id) f = open(startupfile, "w") if self.port.value == '': portstr = "None" else: portstr = self.port.value if self.standard.value == '': standardstr = "None" else: standardstr = self.standard.value if self.muteSources.value == "On": # streams are muted, so disable autoplace disableAutoplace = "true" else: # streams are not muted, so don't disable autoplace # (flags should not be negative!) disableAutoplace = "false" if self.inputsize.value == "Small": inputsize = 4 elif self.inputsize.value == "Large" and self.encoding.value != "h261": inputsize = 1 else: inputsize = 2 if self.resolution != None: resolution = self.resolution.value else: resolution = "none" name = email = "Participant" if self.profile: name = self.profile.name email = self.profile.email else: # Error case name = email = Toolkit.GetDefaultSubject().GetCN() self.log.error("Starting service without profile set") f.write( vicstartup % (disableAutoplace, OnOff(self.muteSources.value), self.bandwidth.value, self.framerate.value, self.quality.value, self.encoding.value, standardstr, vicDevice, "%s(%s)" % (name, self.streamname.value), email, OnOff(self.encodingDeinterlacer.value), resolution, email, OnOff( self.transmitOnStart.value), portstr, portstr, inputsize)) f.close() # Open permissions on vic startupfile os.chmod(startupfile, 0777) # Replace double backslashes in the startupfile name with single # forward slashes (vic will crash otherwise) if IsWindows(): startupfile = startupfile.replace("\\", "/") # # Start the service; in this case, store command line args in a list and let # the superclass _Start the service options = [] options.append("-u") options.append(startupfile) options.append("-C") options.append(str(self.streamDescription.name)) if IsOSX(): if self.transmitOnStart.value: options.append("-X") options.append("transmitOnStartup=1") if self.streamDescription.encryptionFlag != 0: options.append("-K") options.append(self.streamDescription.encryptionKey) # Set drop time to something reasonable options.append('-XsiteDropTime=5') if not self.positionWindow.value == 'Off': # - set vic window geometry try: if not self.windowGeometry: h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y) w_sys = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X) try: w = GetScreenWidth(w_sys, h) except ValueError: self.log.debug( 'Error computing screen width; using system screen width %d', w_sys) w = w_sys window_width = w - 300 window_height = 300 window_x = 300 window_y = h - 375 border_w = wx.SystemSettings_GetMetric( wx.SYS_FRAMESIZE_X) if border_w > 0: window_width -= 4 * border_w window_x += 2 * border_w self.windowGeometry = (window_width, window_height, window_x, window_y) if self.positionWindow.value == 'Justify Left': options.append('-Xgeometry=%dx%d+%d+%d' % self.windowGeometry) else: options.append('-Xgeometry=%dx%d-%d+%d' % self.windowGeometry) except: self.log.exception('Error calculating window placement') if self.profile: options.append("-X") options.append("site=%s" % self.profile.publicId) # Set number of columns to use for thumbnail display options.append("-Xtile=%s" % self.tiles.value) # Check whether the network location has a "type" attribute # Note: this condition is only to maintain compatibility between # older venue servers creating network locations without this attribute # and newer services relying on the attribute; it should be removed # when the incompatibility is gone if self.streamDescription.location.__dict__.has_key("type"): # use TTL from multicast locations only if self.streamDescription.location.type == MulticastNetworkLocation.TYPE: options.append("-t") options.append('%d' % (self.streamDescription.location.ttl)) options.append('%s/%d' % (self.streamDescription.location.host, self.streamDescription.location.port)) self.log.info("Starting VideoServiceH264") self.log.info(" executable = %s" % self.executable) self.log.info(" options = %s" % options) os.chdir(self.thepath) self._Start(options) #os.remove(startupfile) except: self.log.exception("Exception in VideoServiceH264.Start") raise Exception("Failed to start service")
def __init__(self): AGService.__init__(self) self.capabilities = [ Capability(Capability.PRODUCER, Capability.VIDEO, "H261", 90000, self.id) ] if IsWindows(): vic = "vic.exe" else: vic = "vic" self.executable = os.path.join(os.getcwd(), vic) if not os.path.isfile(self.executable): self.executable = vic self.sysConf = SystemConfig.instance() self.startPriority = '5' self.startPriorityOption.value = self.startPriority self.id = str(GUID()) # Set configuration parameters # note: the datatype of the port parameter changes when a resource is set! self.streamname = TextParameter("Stream Name", "") self.port = TextParameter("Port", "") self.encoding = OptionSetParameter("Encoding", "h261", VideoProducerService.encodings) if IsWindows(): standard = "PAL" else: standard = "NTSC" self.standard = OptionSetParameter("Standard", standard, VideoProducerService.standards) self.bandwidth = RangeParameter("Bandwidth", 800, 0, 3072) self.framerate = RangeParameter("Frame Rate", 24, 1, 30) self.quality = RangeParameter("Quality", 75, 1, 100) self.configuration.append(self.streamname) self.configuration.append(self.port) self.configuration.append(self.encoding) self.configuration.append(self.standard) self.configuration.append(self.bandwidth) self.configuration.append(self.framerate) self.configuration.append(self.quality) if IsWindows(): try: import win32api # get number of processors systemInfo = win32api.GetSystemInfo() numprocs = systemInfo[5] self.allProcsMask = 2**numprocs - 1 self.procOptions = ['All'] for i in range(numprocs): self.procOptions.append(str(i + 1)) self.processorUsage = OptionSetParameter( "Processor usage", self.procOptions[0], self.procOptions) self.configuration.append(self.processorUsage) except: self.log.exception( 'Error initializing processor usage options') self.profile = None self.resource = '' self.__GetResources()