def get_currently_streaming_computers(ws): # First request a list of scenes scenes = ws.call(requests.GetSceneList()) current_scene = scenes.getCurrentScene() scenes = scenes.getScenes() logger.info("Finding out currently streaming computers") # Then organize them by name scenes = {scene['name']: scene for scene in scenes} streaming_computers = [] def handle_scene(scene): for source in scene['sources']: type = source['type'] if type == 'ffmpeg_source': name = source['name'] if name.startswith(source_prefix): index = int(name[len(source_prefix):]) streaming_computers.append(index) elif type == 'scene': handle_scene(scenes[source['name']]) handle_scene(scenes[current_scene]) return streaming_computers
def list_scenes(unused_addr, args): scenes = ws.call(requests.GetSceneList()) count = 0 for s in scenes.getScenes(): name = s['name'] print("{0}: '{1}".format(count, name)) count += 1
def GetScenes(self): scenes = client.call(requests.GetSceneList()) scene_list = [] for i in scenes.getScenes(): name = i['name'] scene_list.append(name) return scene_list
def getScenes(self): ret = self.ws.call(requests.GetCurrentScene()) #print("current scene : ",ret.getName()) ret = self.ws.call(requests.GetSceneList()) self.data = ret.datain self.scenes = self.data["scenes"] self.keyScenes = getKeyScenes(self.scenes) return
def getCurrentScenes(): scenes = ws.call(requests.GetSceneList()) for s in scenes.getScenes(): name = s['name'] # print(ws.call(requests.GetSourcesList()),"\n") # Get The list of available sources in each scene in OBS ScenesNames.append(name) # Add every scene to a list of scenes printScenes(ScenesNames) return scenes
def scenes(self, hide_utils=True, hide_games=True): scenes = [] for scene in self.ws.call(requests.GetSceneList()).getScenes(): if hide_utils and scene["name"].endswith("[util]"): continue if hide_games and scene["name"].endswith("[game]"): continue scenes.append(scene) return scenes
async def obs_scenelist_command(ctx): if not ctx.author.is_mod: return if dat.obsConnected: scenes = dat.ws.call(obsrequests.GetSceneList()) if scenes.status: print("[Scenes]") for s in scenes.getScenes(): print(s["name"])
def set_scene(ws, args): if len(args) == 1: response = ws.call(requests.GetSceneList()) for scene in response.getScenes(): if scene['name'] == args[0]: ws.call(requests.SetCurrentScene(args[0])) exit(0) print("Secne({}) not Found!".format(args)) exit(1)
def get_obs_scenes(self): # type: () -> List[str] """ Retrieves all created scene names from OBS Studio """ if not self.connected: self.connect() if self.connected: scenes = self.ws.call(obsrequest.GetSceneList()) scene_names = [scene["name"] for scene in scenes.datain["scenes"] ] # type: List[str] return scene_names return []
def GetSources(self,Scene): scenes = client.call(requests.GetSceneList()) for i in scenes.getScenes(): if i['name'] == Scene: sources = i['sources'] source_list = [" "] for j in sources: name = j['name'] source_list.append(name) return source_list
def ToggleSource(client,Action): Scene = Action["Scene"] Source = Action["Source"] scenes = client.call(requests.GetSceneList()) for i in scenes.getScenes(): if i['name'] == Scene: sources = i['sources'] for j in sources: if j['name'] == Source: CurrentState = j['render'] client.call(requests.SetSourceRender(Source,not CurrentState,Scene))
def __update_scenes(ws_client: obswebsocket.obsws) -> List: # returns the list of sources in the current scene global scenes try: scenelist = ws_client.call(requests.GetSceneList()) scenes = {s['name']: s['sources'] for s in scenelist.getScenes()} current = scenelist.getCurrentScene() return scenes[current] except: sys.exit()
def getscenelist(self): try: scenes = self.ws.call(requests.GetSceneList()) sceneListLong.clear() sceneListShort.clear() #logging.debug(scenes) for each in scenes.getScenes(): #logging.debug(each['name']) sceneListLong.append(each) sceneListShort.append(each["name"]) except: logging.debug("unable to get scenes")
def OBS_Lista_Escenas(): falcon_logger.info("Lista Escenas") ws = obsws(host, port, password) lista=[] try: ws.connect() except: return 1,"Error de Conexion - ¿OBS Parado?)", lista scenes = ws.call(requests.GetSceneList()) for s in scenes.getScenes(): falcon_logger.info(s['name']) lista.append(s['name']) ws.disconnect() return 0,"OK",lista
def obs_connect(): global obs_connected try: print("Connecting to OBS\n") ws.connect() obs_connected = True except: print("ERROR : could not connect to OBS. Is OBS running?\n") return scenes = ws.call(requests.GetSceneList()) for s in scenes.getScenes(): name = s['name'] # print(ws.call(requests.GetSourcesList()),"\n") # Get The list of available sources in each scene in OBS ScenesNames.append(name) # Add every scene to a list of scenes print("\n CURRENT SCENES IN OBS", ScenesNames)
def init_scenes(self): self.logger.debug("init_scenes start") res = self.ws.call(requests.GetSceneList()) self.logger.debug("Got %d scenes, current scene name is '%s'", len(res.getScenes()), res.getCurrentScene()) scene_names = [x['name'] for x in res.getScenes()] cur_scene_index = scene_names.index(res.getCurrentScene()) cur_scene = [ x for x in res.getScenes() if x['name'] == res.getCurrentScene() ][0] self.scenes.insert(END, *scene_names) self.scenes.selection_set(cur_scene_index) self.logger.debug("Current scene has %d sources", len(cur_scene['sources'])) self.fill_sources(cur_scene['sources']) self.logger.debug("init_scenes end")
def read_scenes(): global CurrentScene global SceneNames SceneNames = [] try: print("---------------------- SCENES ----------------------") scenes = ws.call(requests.GetSceneList()) CurrentScene = scenes.getCurrentScene() print("Current Scene: '{0}'".format(CurrentScene)) print() for s in scenes.getScenes(): name = s['name'] print("Scene {0}: '{1}'".format(len(SceneNames), name)) SceneNames.append(name) # Add every scene to a list of scenes except: pass
def update_scenes(self, *args): if len(args) > 0: self.scenes = [ s['name'] for s in args[0].getScenes() if not s['name'].lower().startswith('overlay:') ] else: self.scenes = [ s['name'] for s in self.client.call(requests.GetSceneList()).getScenes() if not s['name'].lower().startswith('overlay:') ] for idx in range(0, 8): try: name = self.scenes[idx] except IndexError: name = '' self._send_osc('/scene_label_{}'.format(idx), name) self.update_mute_status()
def change_scene(self, amount): """ Jump to the next / previous scene. The web socket will only give us the current scene name and an orderd list of scenes; we therefore need to work out the index of the current scene and then the name of the desired scene to jump to. """ if self.connection.call( requests.GetStudioModeStatus()).getStudioMode() == False: print('Studio mode must be on for scene switching') return scenes = self.connection.call(requests.GetSceneList()).getScenes() current_scene = self.connection.call( requests.GetPreviewScene()).getName() current_scene_index = [ i for i, s in enumerate(scenes) if s['name'] == current_scene ][0] new_scene_index = (current_scene_index + amount) % len(scenes) new_scene = scenes[new_scene_index]['name'] self.connection.call(requests.SetPreviewScene(new_scene))
def init(rows): global obs_scenes global last_scene global last_preset last_scene = "none" last_preset = [-1, -1, -1] obs_scenes = obs_ws.call(requests.GetSceneList()) for s in obs_scenes.getScenes(): print(s['name']) global slide_target for row in rows: nRowsToAdd = int(row['Slide']) - 1 - len(slide_target) while nRowsToAdd > 0: new_row = slide_target[len(slide_target) - 1].copy() slide_target.append(new_row) nRowsToAdd = nRowsToAdd - 1 new_row = {} new_row['desc'] = row['Description'] new_row['scene'] = row['Scene'] new_row['cams'] = [ my_int(row['Cam1']), my_int(row['Cam2']), my_int(row['Cam3']) ] new_row['mics'] = [ 0, my_int(row['Lectern']), my_int(row['Vocal']), my_int(row['Ac Guit']), my_int(row['KeyBd']), my_int(row['Cong']), my_int(row['Media L']), my_int(row['Media R']), my_int(row['Stream L']), my_int(row['Stream R']), my_int(row['Pr Ely']), my_int(row['Pr Ed']) ] slide_target.append(new_row) # fill out defaults that extend down mics = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for row in slide_target: new_mics = row['mics'].copy() for i in range(0, 12): if new_mics[i] < 0: new_mics[i] = mics[i] row['mics'] = new_mics mics = new_mics # fill out defaults that extend up cams = [1, 1, 1] for ix in range(len(slide_target) - 1, 0, -1): row = slide_target[ix] new_cams = row['cams'].copy() for i in range(0, 3): if new_cams[i] < 0: new_cams[i] = cams[i] row['cams'] = new_cams cams = new_cams slide = 1 for row in slide_target: print(slide, row) slide = slide + 1
def ListScenes(self): try: return self.ws.call( requests.GetSceneList()).__dict__["datain"]["scenes"] except Exception as e: print(e)
def get_scenes(self): logging.info("OBS command: get all scenes.") self.scenes = self.ws_call(requests.GetSceneList())
def main(resource_dir, password, show_debug_window): with open(dirname(realpath(__file__)) + "/settings.json") as settings_file: application_settings = json.load(settings_file) print("Running with settings:", application_settings) monitor_to_capture = application_settings["monitor_to_capture"] default_scene_name = application_settings["default_scene_name"] target_scene_name = application_settings["target_scene_name"] num_features_to_detect = application_settings["num_features_to_detect"] num_good_matches_required = application_settings[ "num_good_matches_required"] if password: obs = obsws(host, port, password) else: obs = obsws(host, port) obs.connect() scenes = obs.call(requests.GetSceneList()) print("Detected scenes in OBS: " + str(scenes)) if show_debug_window: cv2.startWindowThread() cv2.namedWindow("obs-screen-recognition") with mss() as screen_capture: initial_frame_resolution = numpy.array( screen_capture.grab( screen_capture.monitors[monitor_to_capture])).shape[0:2] screen_size = str(initial_frame_resolution[0]) + "p" # E.g. 1440p print("Detected monitor resolution to be {}".format(screen_size)) if initial_frame_resolution not in VALID_RESOLUTIONS: print( VALID_RESOLUTIONS_ERROR_MESSAGE.format( resolution=initial_frame_resolution)) exit(1) image_directory = resource_dir + "/" + screen_size mask_file = resource_dir + "/mask-" + screen_size + ".png" image_files_to_search_for = [ cv2.cvtColor(cv2.imread(join(image_directory, f)), cv2.COLOR_BGR2GRAY) for f in listdir(image_directory) if isfile(join(image_directory, f)) ] image_mask = cv2.imread(mask_file, cv2.IMREAD_GRAYSCALE) feature_detector = cv2.ORB_create(nfeatures=num_features_to_detect, scoreType=cv2.ORB_FAST_SCORE, nlevels=1, fastThreshold=10) feature_matcher = cv2.BFMatcher(cv2.NORM_HAMMING) image_descriptors = [ feature_detector.detectAndCompute(image, None)[1] for image in image_files_to_search_for ] while True: try: tick_time, num_matches = execute_tick( screen_capture, monitor_to_capture, image_mask, image_descriptors, feature_detector, feature_matcher, num_good_matches_required, obs, default_scene_name, target_scene_name, show_debug_window) if tick_time: print( "Tick took {} seconds. Suggested OBS source delay: {}ms. Num good matches: {}" .format(tick_time, round(tick_time, 2) * 1000, num_matches)) except Exception as e: print(e)
def main(): host = "localhost" port = 4444 password = "******" ws = obsws(host, port, password) try: ws.connect() except Exception: pass else: scenes = ws.call(orequests.GetSceneList()).getScenes() scene_list = [] for thing in scenes: scene_list.append(thing['name']) j = JournalWatcher(directory="C:\\Users\\danho\\Saved Games\\Frontier Developments\\Elite Dangerous") mixer.init() music_queue = Queue.Queue() music_runner = MusicRunner(music_queue) music_runner.start() while True: for event in j.watch_latest_file(): d = json.loads(event) print json.dumps(d, indent=2) # Do we want any music for this event? If so, queue it up music_dir = d["event"] if d["event"] == "StartJump" and d["JumpType"] == "Hyperspace": music_dir += "\\Hyperspace" elif d["event"] == "SupercruiseExit" and d["BodyType"] == "Station": music_dir += "\\Station" try: music_selection = [os.path.join(music_dir, f) for f in os.listdir(music_dir) if os.path.isfile(os.path.join(music_dir, f))] except Exception: music_selection = [] dir_length = len(music_selection) if dir_length == 0: print("No music for event") else: music_queue.put(random.choice(music_selection)) print("Queueing up {}").format(music_selection) # Post events to API and let OBS show something try: post_event(d["event"], d) except Exception: pass else: time.sleep(2) if d["event"] in scene_list: try: ws.call(orequests.SetCurrentScene(d["event"])) except Exception: pass else: time.sleep(5) try: ws.call(orequests.SetCurrentScene("Game")) except Exception: pass
def show_scenes(ws, args): response = ws.call(requests.GetSceneList()) for s in response.getScenes(): print(s['name']) exit(0)
def main(resource_dir, show_debug_window): with open(dirname(realpath(__file__)) + "/settings.json") as settings_file: application_settings = json.load(settings_file) if application_settings["screen_format"] not in ["1440p", "1080p"]: println("Only 1440p or 1080p screen formats currently supported") exit(1) print("Running with settings:", application_settings) image_directory = resource_dir + "/" + application_settings["screen_format"] mask_file = resource_dir + "/mask-" + application_settings[ "screen_format"] + ".png" monitor_to_capture = application_settings["monitor_to_capture"] default_scene_name = application_settings["default_scene_name"] target_scene_name = application_settings["target_scene_name"] num_features_to_detect = application_settings["num_features_to_detect"] num_good_matches_required = application_settings[ "num_good_matches_required"] try: image_files_to_search_for = [ cv2.cvtColor(cv2.imread(join(image_directory, f)), cv2.COLOR_BGR2GRAY) for f in listdir(image_directory) if isfile(join(image_directory, f)) ] image_mask = cv2.imread(mask_file, cv2.IMREAD_GRAYSCALE) except Exception as e: print(e) obs = obsws(host, port) obs.connect() scenes = obs.call(requests.GetSceneList()) print("Detected scenes in OBS: " + str(scenes)) feature_detector = cv2.ORB_create(nfeatures=num_features_to_detect, scoreType=cv2.ORB_FAST_SCORE, nlevels=1, fastThreshold=10) image_descriptors = [ feature_detector.detectAndCompute(image, None)[1] for image in image_files_to_search_for ] feature_matcher = cv2.BFMatcher(cv2.NORM_HAMMING) if show_debug_window: cv2.startWindowThread() cv2.namedWindow("test") with mss() as screen_capture: while True: try: tick_time, num_matches = execute_tick( screen_capture, monitor_to_capture, image_mask, image_descriptors, feature_detector, feature_matcher, num_good_matches_required, obs, default_scene_name, target_scene_name, show_debug_window) if tick_time: print( "Tick took {} seconds. Suggested OBS source delay: {}ms. Num good matches: {}" .format(tick_time, round(tick_time, 2) * 1000, num_matches)) except Exception as e: print(e)
def activate(self, device): self.ws = obsws("localhost", 4444) #Connect to websockets plugin in OBS #Callback if OBS is shutting down def on_exit(message): self.ws.disconnect() #Callback if the scene changes def on_scene(message): if self.updateSceneButtons(device, message.getSceneName()): device.updateDisplay( ) #Only update if parts of the display actually changed self.updateLED(device) #Callback if the visibility of a source changes def on_visibility_changed(message): if self.updateStateButtons(device, message.getSceneName(), message.getItemName(), message.getItemVisible()): device.updateDisplay( ) #Only update if parts of the display actually changed self.updateLED(device) #Register callbacks to OBS self.ws.register(on_exit, events.Exiting) self.ws.register(on_scene, events.SwitchScenes) self.ws.register(on_visibility_changed, events.SceneItemVisibilityChanged) self.ws.connect() device.sendTextFor("title", "OBS", inverted=True) #Title ### Buttons 2 to 5 set different scenes (Moderation, Closeup, Slides and Video Mute) ### for scene in self.scenes: device.assignKey(KeyCode["SW" + str(scene["button"]) + "_PRESS"], []) device.assignKey(KeyCode["SW" + str(scene["button"]) + "_RELEASE"], []) device.registerCallback( self.getSetSceneCallback(scene["name"]), KeyCode["SW" + str(scene["button"]) + "_PRESS"]) ### Button 6: Order! def stopOrder(): self.ws.call( requests.SetSceneItemProperties("Order", visible=False)) def playOrder(): self.ws.call(requests.SetSceneItemProperties("Order", visible=True)) Timer(3, stopOrder).start() device.assignKey(KeyCode["SW6_PRESS"], []) device.assignKey(KeyCode["SW6_RELEASE"], []) device.registerCallback(playOrder, KeyCode["SW6_PRESS"]) device.sendIconFor(6, "icons/megaphone.png", centered=True) ### Buttons 7 to 9 toogle the visibility of items, some of which are present in multiple scenes (Mics, Picture-In-Picture cam, Video stream from phone) ### for state in self.states: device.assignKey(KeyCode["SW" + str(state["button"]) + "_PRESS"], []) device.assignKey(KeyCode["SW" + str(state["button"]) + "_RELEASE"], []) device.registerCallback( self.getToggleStateCallback(state), KeyCode["SW" + str(state["button"]) + "_PRESS"]) ### Get current state and initialize buttons accordingly ### current = self.ws.call(requests.GetSceneList()) for scene in current.getScenes(): for item in scene["sources"]: for state in self.states: if (scene["name"], item["name"]) in state["items"]: state["current"] = item["render"] #Call updateSceneButtons and updateStateButtons to initialize their images self.currentScene = None self.updateSceneButtons(device, current.getCurrentScene(), init=True) self.updateStateButtons(device, None, None, True, init=True) device.updateDisplay() self.updateLED(device)
def getSourcesListWhenRender(list): result = [] for element in list: if (current_scene in element["name"]): for value in element["sources"]: if (value[u'render']): result.append(value[u'name']) return result ws.connect() current_scene = scene get_scenes_list = ws.call(requests.GetSceneList()) scenes_list = get_scenes_list.datain sources_list = getSourcesList(scenes_list[u'scenes']) #sources_render = getSourcesListWhenRender(scenes_list[u'scenes']) for exception in exception_list: if exception in sources_list: sources_list.remove(exception) packets = [] #Préparation des packets for sources in sources_list: packet = { "request-type": "SetSceneItemProperties", "item": sources, "visible": False,
if filter > 60: # change to scene 2 ws.call(requests.SetCurrentScene(ScenesNames[1])) #sourceSwitch("screen1","Scene1",True) #sourceSwitch("screen2","Scene1",False) elif filter <= 59: ws.call( requests.SetCurrentScene(ScenesNames[0]) ) # COntrol sources by using sourceSwitch("source_Name","Scene_name", bool) #sourceSwitch("screen1","Scene1",False) print("\n [{0}] +" " + {1}".format(args[0], filter)) if __name__ == "__main__": try: scenes = ws.call(requests.GetSceneList()) for s in scenes.getScenes(): name = s['name'] print( ws.call(requests.GetSourcesList()), "\n") # Get The list of available sources in each scene in OBS ScenesNames.append(name) # Add every scene to a list of scenes print("\n CURRENT SCENES IN OBS", ScenesNames) ### OSC SETTINGS parser = argparse.ArgumentParser() parser.add_argument("--ip", default="127.0.0.1", help="The ip to listen on")
def test_connecta(): scenes = ws.call(requests.GetSceneList()) for s in scenes.getScenes(): name = s['name'] emit('getscenes', {'name': name})