├── .gitignore ├── LICENSE ├── README.md ├── atem_commands.py ├── atem_config.py ├── atem_packet.py ├── atem_server.py ├── client_manager.py ├── default_config.xml └── raw_commands.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Jon Knoll 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pyAtemSim 2 | ## ATEM Switcher Simulator in Python 3 | 4 | ## Current features: 5 | * Simulates an ATEM Television Studio HD but maybe more over time. 6 | * Supports the Blackmagic ATEM software (so you can try the software without hardware 7 | * Supports multiple simultaneous clients 8 | * Reads a configuration file from the ATEM software (partially implemented) 9 | 10 | ## Getting Started: 11 | * Download this repo 12 | * From command line type: python atem_server.py 13 | * Type atem_server.py --help for command line options 14 | 15 | ## Useful Links: 16 | ### Documentation: 17 | * https://www.skaarhoj.com/fileadmin/BMDPROTOCOL.html 18 | * https://docs.openswitcher.org/index.html 19 | * https://github.com/miyukki/node-atem/blob/master/specification.md 20 | * https://nrkno.github.io/tv-automation-atem-connection/index.html 21 | 22 | ### Debugging 23 | * wireshark-atem-dissector (updated): https://github.com/jonknoll/wireshark-atem-dissector 24 | * the original is here: https://github.com/peschuster/wireshark-atem-dissector 25 | 26 | ### Other Projects 27 | * Another ATEM Simulator (swift--mac only): https://github.com/Dev1an/Atem-Simulator 28 | * https://openswitcher.org/ 29 | * https://github.com/petersimonsson/libqatemcontrol 30 | * https://github.com/sxpert/PyATEM 31 | 32 | ### Open Source tally light solutions 33 | * Raspberry Pi based: https://designshift.ca/apps/atem-tally/ 34 | * Raspberry Pi based: https://techministry.blog/ 35 | * https://www.tbdproductions.com.au/software 36 | * Arduino based: http://kvitko.com/tally/ 37 | -------------------------------------------------------------------------------- /atem_commands.py: -------------------------------------------------------------------------------- 1 | # ATEM commands 2 | 3 | from os import truncate 4 | import struct 5 | import raw_commands 6 | from typing import List 7 | import atem_config 8 | from atem_config import DEVICE_VIDEO_SOURCES 9 | import datetime 10 | import time 11 | 12 | 13 | class ATEMCommand(object): 14 | def __init__(self, bytes=b''): 15 | self.bytes = bytes 16 | self.length = None 17 | self.code = type(self).__name__[-4:] 18 | self.full = "" 19 | self.time_to_send = 0 20 | 21 | def parse_cmd(self): 22 | """ 23 | Parse the command into useful variables 24 | """ 25 | pass 26 | 27 | def update_state(self): 28 | """ 29 | Updated the internal state of the switcher 30 | """ 31 | pass 32 | 33 | def to_bytes(self): 34 | """ 35 | Build the command into a byte stream 36 | """ 37 | pass 38 | 39 | def _build(self, content): 40 | """ 41 | Boilerplate bytes stream build stuff for commands 42 | """ 43 | if self.length != None: 44 | cmd_length = self.length 45 | else: 46 | cmd_length = len(content) + 8 47 | self.length = cmd_length 48 | cmd = struct.pack('!H 2x 4s', cmd_length, self.code.encode()) 49 | return cmd + content 50 | 51 | 52 | 53 | class Cmd__ver(ATEMCommand): 54 | def __init__(self, bytes=b''): 55 | super().__init__(bytes=bytes) 56 | self.full = "ProtocolVersion" 57 | self.major = 2 58 | self.minor = 30 59 | 60 | def to_bytes(self): 61 | content = struct.pack('!HH', self.major, self.minor) 62 | self.bytes = self._build(content) 63 | 64 | 65 | class Cmd__pin(ATEMCommand): 66 | def __init__(self, bytes=b''): 67 | super().__init__(bytes=bytes) 68 | self.full = "ProductId" 69 | self.product_name = "ATEM Television Studio HD" 70 | 71 | def to_bytes(self): 72 | content = struct.pack('!44s', self.product_name.encode()) 73 | self.bytes = self._build(content) 74 | 75 | 76 | class Cmd_InCm(ATEMCommand): 77 | def __init__(self, bytes=b''): 78 | super().__init__(bytes=bytes) 79 | self.length = 12 80 | self.raw_hex = b'\x01\x00\x00\x00' 81 | 82 | def to_bytes(self): 83 | self.bytes = self._build(self.raw_hex) 84 | 85 | 86 | ###################################################### 87 | # COMMANDS FROM CLIENT 88 | ###################################################### 89 | 90 | # Auto Transition from client 91 | class Cmd_DAut(ATEMCommand): 92 | def __init__(self, bytes=b''): 93 | super().__init__(bytes=bytes) 94 | self.me = None 95 | self.prog = None 96 | self.prev = None 97 | self.transition_pos = None 98 | self.transition_total_frames = None 99 | 100 | def parse_cmd(self): 101 | self.length = len(self.bytes) 102 | self.me = struct.unpack('!B', self.bytes[8:9]) 103 | self.me = self.me[0] 104 | 105 | def update_state(self): 106 | self.prog = atem_config.conf_db['MixEffectBlocks'][self.me]['Program']['input'] 107 | self.prev = atem_config.conf_db['MixEffectBlocks'][self.me]['Preview']['input'] 108 | self.transition_pos = int(atem_config.conf_db['MixEffectBlocks'][self.me]['TransitionStyle']['transitionPosition']) 109 | transition_style = atem_config.conf_db['MixEffectBlocks'][self.me]['TransitionStyle']['style'] 110 | if transition_style == "Dip": 111 | self.transition_total_frames = int(atem_config.conf_db['MixEffectBlocks'][self.me]['TransitionStyle']['DipParameters']['rate']) 112 | elif transition_style == "Wipe": 113 | self.transition_total_frames = int(atem_config.conf_db['MixEffectBlocks'][self.me]['TransitionStyle']['WipeParameters']['rate']) 114 | else: # default to mix parameters 115 | self.transition_total_frames = int(atem_config.conf_db['MixEffectBlocks'][self.me]['TransitionStyle']['MixParameters']['rate']) 116 | 117 | def update_prog_prev(self): 118 | atem_config.conf_db['MixEffectBlocks'][self.me]['Program']['input'] = self.prev 119 | atem_config.conf_db['MixEffectBlocks'][self.me]['Preview']['input'] = self.prog 120 | 121 | 122 | # Cut from client 123 | class Cmd_DCut(ATEMCommand): 124 | def __init__(self, bytes=b''): 125 | super().__init__(bytes=bytes) 126 | self.me = None 127 | 128 | def parse_cmd(self): 129 | self.length = len(self.bytes) 130 | self.me = struct.unpack('!B', self.bytes[8:9]) 131 | self.me = self.me[0] 132 | 133 | def update_state(self): 134 | prog_source = atem_config.conf_db['MixEffectBlocks'][self.me]['Program']['input'] 135 | prev_source = atem_config.conf_db['MixEffectBlocks'][self.me]['Preview']['input'] 136 | atem_config.conf_db['MixEffectBlocks'][self.me]['Program']['input'] = prev_source 137 | atem_config.conf_db['MixEffectBlocks'][self.me]['Preview']['input'] = prog_source 138 | #print(f"me{self.me}={atem_config.conf_db['MixEffectBlocks'][self.me]}") 139 | 140 | 141 | # Program Input from client (See also PrgI) 142 | class Cmd_CPgI(ATEMCommand): 143 | def __init__(self, bytes=b''): 144 | super().__init__(bytes=bytes) 145 | self.length = 12 146 | self.me = None 147 | self.video_source = None 148 | 149 | def parse_cmd(self): 150 | self.length = len(self.bytes) 151 | self.me, self.video_source = struct.unpack('!B x H', self.bytes[8:12]) 152 | 153 | def update_state(self): 154 | atem_config.conf_db['MixEffectBlocks'][self.me]['Program']['input'] = str(self.video_source) 155 | #print(f"me{self.me}={atem_config.conf_db['MixEffectBlocks'][self.me]}") 156 | 157 | 158 | # Preview Input from client, almost identical to Cmd_CPgI (See also PrvI) 159 | class Cmd_CPvI(ATEMCommand): 160 | def __init__(self, bytes=b''): 161 | super().__init__(bytes=bytes) 162 | self.length = 12 163 | self.me = None 164 | self.video_source = None 165 | 166 | def parse_cmd(self): 167 | self.length = len(self.bytes) 168 | self.me, self.video_source = struct.unpack('!B x H', self.bytes[8:12]) 169 | 170 | def update_state(self): 171 | atem_config.conf_db['MixEffectBlocks'][self.me]['Preview']['input'] = str(self.video_source) 172 | #print(f"me{self.me}={atem_config.conf_db['MixEffectBlocks'][self.me]}") 173 | 174 | 175 | 176 | 177 | ###################################################### 178 | # COMMANDS TO CLIENT 179 | ###################################################### 180 | 181 | # Time sent to client 182 | class Cmd_Time(ATEMCommand): 183 | def __init__(self, offset_sec=0): 184 | super().__init__(b'') 185 | self.length = 16 186 | self.offset_sec = offset_sec 187 | 188 | def to_bytes(self): 189 | video_mode = atem_config.conf_db['VideoMode']['videoMode'] 190 | if "5994" in video_mode: 191 | frame_rate = 59.94 192 | elif "2997" in video_mode: 193 | frame_rate = 29.97 194 | elif "2398" in video_mode: 195 | frame_rate = 23.98 196 | elif "50" in video_mode: 197 | frame_rate = 50 198 | elif "25" in video_mode: 199 | frame_rate = 25 200 | elif "24" in video_mode: 201 | frame_rate = 24 202 | t = datetime.datetime.now() + datetime.timedelta(seconds=int(self.offset_sec), microseconds=int((self.offset_sec % 1) * 1000000)) 203 | frame = int(t.microsecond / 1000000 * frame_rate) 204 | content = struct.pack('!4B 4x', t.hour, t.minute, t.second, frame) 205 | self.bytes = self._build(content) 206 | 207 | 208 | # Tally By Index sent to client 209 | class Cmd_TlIn(ATEMCommand): 210 | def __init__(self, me=0): 211 | super().__init__(b'') 212 | self.me = me 213 | self.program_source = int(atem_config.conf_db['MixEffectBlocks'][self.me]['Program']['input']) 214 | self.preview_source = int(atem_config.conf_db['MixEffectBlocks'][self.me]['Preview']['input']) 215 | self.transition_pos = int(atem_config.conf_db['MixEffectBlocks'][self.me]['TransitionStyle']['transitionPosition']) 216 | self.num_inputs = len(atem_config.conf_db['Settings']['Inputs']) 217 | 218 | def to_bytes(self): 219 | # Build content 220 | content = struct.pack('!H', self.num_inputs) 221 | for i in range(self.num_inputs): 222 | input_byte = 0x00 223 | if self.program_source <= self.num_inputs and self.program_source == i + 1: 224 | input_byte |= 0x01 225 | if self.preview_source <= self.num_inputs and self.preview_source == i + 1: 226 | input_byte |= 0x02 227 | # If in mid transition then the preview source is also the program source. 228 | # Transition range is 0-10000 229 | if self.transition_pos > 0 and self.transition_pos < 10000: 230 | input_byte |= 0x1 231 | content += struct.pack('!B', input_byte) 232 | # add the 2 unknown bytes 233 | content += struct.pack('!2x') 234 | self.bytes = self._build(content) 235 | 236 | 237 | # Tally By Source sent to client 238 | class Cmd_TlSr(ATEMCommand): 239 | def __init__(self, me=0): 240 | super().__init__(bytes=bytes) 241 | self.length = 84 242 | self.me = me 243 | self.program_source = int(atem_config.conf_db['MixEffectBlocks'][self.me]['Program']['input']) 244 | self.preview_source = int(atem_config.conf_db['MixEffectBlocks'][self.me]['Preview']['input']) 245 | self.transition_pos = int(atem_config.conf_db['MixEffectBlocks'][self.me]['TransitionStyle']['transitionPosition']) 246 | # the product determines how many sources there are 247 | product = atem_config.conf_db['product'] 248 | self.video_sources = DEVICE_VIDEO_SOURCES[product] 249 | self.num_sources = len(self.video_sources) 250 | 251 | def to_bytes(self): 252 | # Build content 253 | content = struct.pack('!H', self.num_sources) 254 | for i in range(self.num_sources): 255 | source_byte = 0x00 256 | if self.program_source == self.video_sources[i]: 257 | source_byte |= 0x01 258 | if self.preview_source == self.video_sources[i]: 259 | source_byte |= 0x02 260 | # If in mid transition then the preview source is also the program source. 261 | # Transition range is 0-10000 262 | if self.transition_pos > 0 and self.transition_pos < 10000: 263 | source_byte |= 0x1 264 | content += struct.pack('!HB', self.video_sources[i], source_byte) 265 | # add the 2 unknown bytes 266 | content += struct.pack('!2x') 267 | self.bytes = self._build(content) 268 | 269 | 270 | # Program Input to client (see also CPgI) 271 | class Cmd_PrgI(ATEMCommand): 272 | def __init__(self, me=0): 273 | super().__init__(bytes=bytes) 274 | self.me = me 275 | self.program_source = int(atem_config.conf_db['MixEffectBlocks'][self.me]['Program']['input']) 276 | 277 | def to_bytes(self): 278 | content = struct.pack('!B x H', self.me, self.program_source) 279 | self.bytes = self._build(content) 280 | 281 | 282 | # Preview Input to client, almost identical to Cmd_PrgI (see also CPvI) 283 | class Cmd_PrvI(ATEMCommand): 284 | def __init__(self, me=0): 285 | super().__init__(bytes=bytes) 286 | self.me = me 287 | self.preview_source = int(atem_config.conf_db['MixEffectBlocks'][self.me]['Preview']['input']) 288 | 289 | def to_bytes(self): 290 | content = struct.pack('!B x H 4x', self.me, self.preview_source) 291 | self.bytes = self._build(content) 292 | 293 | 294 | # Transition Position to client 295 | class Cmd_TrPs(ATEMCommand): 296 | def __init__(self, me=0, frames_remaining=None, total_frames=None): 297 | super().__init__(bytes=bytes) 298 | self.me = me 299 | self.total_frames = total_frames 300 | self.frames_remaining = frames_remaining 301 | if frames_remaining > 255: # maximum size of the byte that it's going into 302 | self.frames_remaining = 255 303 | self.transition_pos = int((self.frames_remaining/self.total_frames) * 10000) 304 | self.transition_pos = 10000 - self.transition_pos 305 | atem_config.conf_db['MixEffectBlocks'][self.me]['TransitionStyle']['transitionPosition'] = str(self.transition_pos) 306 | if self.frames_remaining == self.total_frames: 307 | self.in_transition = 0 308 | else: 309 | self.in_transition = 1 310 | 311 | def to_bytes(self): 312 | content = struct.pack('!BBB x H 2x', self.me, self.in_transition, self.frames_remaining, self.transition_pos) 313 | self.bytes = self._build(content) 314 | 315 | 316 | 317 | 318 | 319 | class Cmd_Unknown(ATEMCommand): 320 | def __init__(self, bytes, name=""): 321 | super().__init__(bytes=bytes) 322 | if name: 323 | self.code = name 324 | else: 325 | self.code = "UNKN" 326 | 327 | def parse_cmd(self): 328 | pass 329 | 330 | def to_bytes(self): 331 | self.length = len(self.bytes) 332 | 333 | 334 | class Cmd_Raw(ATEMCommand): 335 | def __init__(self, bytes): 336 | super().__init__(bytes=bytes) 337 | 338 | def to_bytes(self): 339 | self.length = len(self.bytes) 340 | 341 | 342 | class CommandCarrier(object): 343 | def __init__(self): 344 | # array of commands to be sent in a packet 345 | self.commands = [] 346 | # Can set to a future time (relative to monotonic clock) 347 | # if it's a transition command where multiple commands 348 | # have to be sent to update the state of the transition. 349 | # Leave as 0 to be sent right away (default). 350 | self.send_time = 0 351 | # Set if the client object who receives the response, 352 | # needs to send it to the client manager so it can be 353 | # sent out to the other clients as well. Normally this 354 | # is the case. There are just a few commands that are 355 | # for the requesting client only. 356 | self.multicast = True 357 | # Packet id to ack when this response command(s) is sent back. 358 | # This is more for the client to manage in the outbound_packet_list. 359 | self.ack_packet_id = 0 360 | 361 | 362 | def build_setup_commands_list(): 363 | raw_setup_commands = [ 364 | raw_commands.commands1, 365 | raw_commands.commands2, 366 | raw_commands.commands3, 367 | raw_commands.commands4, 368 | raw_commands.commands5, 369 | raw_commands.commands6, 370 | #raw_commands.commands7, 371 | #raw_commands.commands8, 372 | ] 373 | commands_list = [] 374 | for rsc in raw_setup_commands: 375 | cmd_bytes = raw_commands.getByteStream(rsc) 376 | cmd = Cmd_Raw(cmd_bytes) 377 | commands_list.append(cmd) 378 | return commands_list 379 | 380 | 381 | 382 | 383 | # get commands list by piecing together the name of the class from the command you want 384 | # and use: 385 | # classname = "Cmd" + command_name.decode() 386 | # if hasattr(atem_commands, classname): 387 | # TheClass = getattr(atem_commands, classname) 388 | #OR instance = getattr(atem_commands, classname)(class_params) 389 | # 390 | # This would be the manual way... 391 | commands_list = {'_ver' : Cmd__ver, 392 | '_pin' : Cmd__pin, 393 | 'DAut' : Cmd_DAut, 394 | 'DCut' : Cmd_DCut, 395 | 'CPgI' : Cmd_CPgI, 396 | 'CPvI' : Cmd_CPvI, 397 | 'InCm' : Cmd_InCm, 398 | } 399 | 400 | def build_current_state_command_list(): 401 | return_list = [] 402 | 403 | cmd = Cmd__ver() 404 | return_list.append(cmd) 405 | 406 | cmd = Cmd__pin() 407 | return_list.append(cmd) 408 | 409 | #...etc. 410 | return return_list 411 | 412 | def build_command_list_from_names(command_names: list): 413 | return_list = [] 414 | for cmd_name in commands_list: 415 | new_cmd = get_command_object(cmd_name) 416 | if new_cmd != None: 417 | return_list.append(new_cmd) 418 | return return_list 419 | 420 | 421 | def get_command_object(bytes=b'', cmd_name=""): 422 | cmd_class = commands_list.get(cmd_name) 423 | if cmd_class is not None: 424 | cmd_obj = cmd_class(bytes) 425 | else: 426 | cmd_obj = Cmd_Unknown(bytes, cmd_name) 427 | return cmd_obj 428 | 429 | 430 | def get_response(cmd_list:List[ATEMCommand]): 431 | """ 432 | Get the response command(s) for a list of commands 433 | from a client packet. Typically a client sends only one 434 | command at a time. 435 | 436 | Returns a list of CommandCarrier objects. 437 | The CommandCarrier object contains one or more response 438 | commands as well as metadata for the command. 439 | Typically there is only one CommandCarrier object returned, 440 | containing one set of response commands to send 441 | to the client(s). However, there may be more than one 442 | CommandCarrier object if the response requires more 443 | than one packet be sent a result of the command 444 | (eg. a transition like fade to black). 445 | If it is an unknown command then it returns an empty list. 446 | """ 447 | response_list = [] 448 | for cmd in cmd_list: 449 | if isinstance(cmd, Cmd_DAut): 450 | cmd.update_state() 451 | now = time.monotonic() 452 | time_offset_sec = 0 453 | frames_total = cmd.transition_total_frames 454 | frames_remaining = frames_total - 1 455 | print(f"ME: {cmd.me}, AUTO TRANSITION") 456 | # The transition position command object has to be created first so 457 | # the transition position gets updated in the conf_db. The tally 458 | # commands set two program sources based on whether the transition 459 | # position is > 0. 460 | trPs = Cmd_TrPs(cmd.me, frames_remaining, frames_total) 461 | # create response packet 462 | cc = CommandCarrier() 463 | cc.commands.append(Cmd_Time(time_offset_sec)) 464 | cc.commands.append(Cmd_TlIn(cmd.me)) 465 | cc.commands.append(Cmd_TlSr(cmd.me)) 466 | cc.commands.append(Cmd_PrvI(cmd.me)) 467 | cc.commands.append(trPs) 468 | response_list.append(cc) 469 | # create future packets 470 | 471 | while frames_remaining > 0: 472 | # Send an update every 200ms which is every 6 "frames". 473 | # The transition framerate seems to remain at 30fps. 474 | # This is way fewer than a real switcher but gets a similar result. 475 | frames_remaining -= 6 476 | if frames_remaining <= 0: 477 | frames_remaining = 0 478 | break 479 | cc = CommandCarrier() 480 | time_offset_sec += 0.200 # create another update packet every 1/5th of a second 481 | cc.send_time = now + time_offset_sec 482 | cc.commands.append(Cmd_Time(time_offset_sec)) 483 | cc.commands.append(Cmd_TrPs(cmd.me, frames_remaining, frames_total)) 484 | response_list.append(cc) 485 | 486 | # create last future packet 487 | transition_pos = int((frames_remaining/frames_total) * 10000) 488 | cmd.update_prog_prev() 489 | cc = CommandCarrier() 490 | cc.send_time = now + (frames_total / 30) 491 | cc.commands.append(Cmd_TrPs(cmd.me, frames_remaining, frames_total)) 492 | # create final trPs so the tallys show correctly based on the transition position 493 | final_trPs = Cmd_TrPs(cmd.me, frames_total, frames_total) 494 | cc.commands.append(Cmd_TlIn(cmd.me)) # Tally by Index 495 | cc.commands.append(Cmd_TlSr(cmd.me)) # Tally by Source 496 | cc.commands.append(Cmd_PrgI(cmd.me)) # Program Input (PrgI) 497 | cc.commands.append(Cmd_PrvI(cmd.me)) # Preivew Input (PrvI) 498 | cc.commands.append(final_trPs) 499 | response_list.append(cc) 500 | elif isinstance(cmd, Cmd_DCut): 501 | cmd.update_state() 502 | print(f"ME: {cmd.me}, CUT") 503 | cc = CommandCarrier() 504 | # Time 505 | cc.commands.append(Cmd_Time()) # Time 506 | cc.commands.append(Cmd_TlIn(cmd.me)) # Tally by Index 507 | cc.commands.append(Cmd_TlSr(cmd.me)) # Tally by Source 508 | cc.commands.append(Cmd_PrgI(cmd.me)) # Program Input (PrgI) 509 | cc.commands.append(Cmd_PrvI(cmd.me)) # Preivew Input (PrvI) 510 | response_list.append(cc) 511 | elif isinstance(cmd, Cmd_CPgI): 512 | cmd.update_state() 513 | print(f"ME: {cmd.me}, Program Source: {cmd.video_source}") 514 | cc = CommandCarrier() 515 | cc.commands.append(Cmd_Time()) # Time 516 | cc.commands.append(Cmd_TlIn(cmd.me)) # Tally by Index 517 | cc.commands.append(Cmd_TlSr(cmd.me)) # Tally by Source 518 | cc.commands.append(Cmd_PrgI(cmd.me)) # Program Input (PrgI) 519 | response_list.append(cc) 520 | elif isinstance(cmd, Cmd_CPvI): 521 | cmd.update_state() 522 | print(f"ME: {cmd.me}, Preview Source: {cmd.video_source}") 523 | cc = CommandCarrier() 524 | cc.commands.append(Cmd_Time()) # Time 525 | cc.commands.append(Cmd_TlIn(cmd.me)) # Tally by Index 526 | cc.commands.append(Cmd_TlSr(cmd.me)) # Tally by Source 527 | cc.commands.append(Cmd_PrvI(cmd.me)) # Preview Input (PrvI) 528 | response_list.append(cc) 529 | else: 530 | pass 531 | return response_list 532 | 533 | if __name__ == "__main__": 534 | # Quick test 535 | for cmd_name in commands_list: 536 | cmd_class = commands_list[cmd_name] 537 | cmd_obj = cmd_class(bytes) 538 | 539 | -------------------------------------------------------------------------------- /atem_config.py: -------------------------------------------------------------------------------- 1 | # Properties of the ATEM switcher 2 | # This should eventually be saved/restored to a file 3 | # Currently it gets populated with sane defaults 4 | 5 | import xml.etree.ElementTree as ET 6 | from collections import defaultdict 7 | from pprint import pprint 8 | 9 | conf_db = {} 10 | 11 | video_sources = { 12 | 0 : "Black", 13 | 1 : "Input 1", 14 | 2 : "Input 2", 15 | 3 : "Input 3", 16 | 4 : "Input 4", 17 | 5 : "Input 5", 18 | 6 : "Input 6", 19 | 7 : "Input 7", 20 | 8 : "Input 8", 21 | 9 : "Input 9", 22 | 10 : "Input 10", 23 | 11 : "Input 11", 24 | 12 : "Input 12", 25 | 13 : "Input 13", 26 | 14 : "Input 14", 27 | 15 : "Input 15", 28 | 16 : "Input 16", 29 | 17 : "Input 17", 30 | 18 : "Input 18", 31 | 19 : "Input 19", 32 | 20 : "Input 20", 33 | 1000 : "Color Bars", 34 | 2001 : "Color 1", 35 | 2002 : "Color 2", 36 | 3010 : "Media Player 1", 37 | 3011 : "Media Player 1 Key", 38 | 3020 : "Media Player 2", 39 | 3021 : "Media Player 2 Key", 40 | 4010 : "Key 1 Mask", 41 | 4020 : "Key 2 Mask", 42 | 4030 : "Key 3 Mask", 43 | 4040 : "Key 4 Mask", 44 | 5010 : "DSK 1 Mask", 45 | 5020 : "DSK 2 Mask", 46 | 6000 : "Super Source", 47 | 7001 : "Clean Feed 1", 48 | 7002 : "Clean Feed 2", 49 | 8001 : "Auxilary 1", 50 | 8002 : "Auxilary 2", 51 | 8003 : "Auxilary 3", 52 | 8004 : "Auxilary 4", 53 | 8005 : "Auxilary 5", 54 | 8006 : "Auxilary 6", 55 | 10010 : "ME 1 Prog", 56 | 10011 : "ME 1 Prev", 57 | 10020 : "ME 2 Prog", 58 | 10021 : "ME 2 Prev", 59 | } 60 | 61 | # Specific device sources (can't really be determined from the config file) 62 | # Match by config file 63 | DEVICE_VIDEO_SOURCES = { 64 | "ATEM Television Studio HD" : [0,1,2,3,4,5,6,7,8,1000,2001,2002,3010,3011,3020,3021,4010,5010,5020,10010,10011,7001,7002,8001] 65 | } 66 | 67 | audio_sources = { 68 | 1 : "Input 1", 69 | 2 : "Input 2", 70 | 3 : "Input 3", 71 | 4 : "Input 4", 72 | 5 : "Input 5", 73 | 6 : "Input 6", 74 | 7 : "Input 7", 75 | 8 : "Input 8", 76 | 9 : "Input 9", 77 | 10 : "Input 10", 78 | 11 : "Input 11", 79 | 12 : "Input 12", 80 | 13 : "Input 13", 81 | 14 : "Input 14", 82 | 15 : "Input 15", 83 | 16 : "Input 16", 84 | 17 : "Input 17", 85 | 18 : "Input 18", 86 | 19 : "Input 19", 87 | 20 : "Input 20", 88 | 1001 : "XLR", 89 | 1101 : "AES/EBU", 90 | 1201 : "RCA", 91 | 2001 : "MP1", 92 | 2002 : "MP2", 93 | } 94 | 95 | 96 | 97 | 98 | 99 | def config_init(config_file): 100 | global conf_db 101 | root = ET.parse(config_file).getroot() 102 | conf_db = etree_to_dict(root) 103 | conf_db = manipulate_sections(conf_db) 104 | return conf_db 105 | 106 | 107 | 108 | # Borrowed this nifty algorithm from here: 109 | # https://stackoverflow.com/questions/7684333/converting-xml-to-dictionary-using-elementtree 110 | 111 | def etree_to_dict(t): 112 | d = {t.tag: {} if t.attrib else None} 113 | children = list(t) 114 | 115 | if children: 116 | dd = defaultdict(list) 117 | for dc in map(etree_to_dict, children): 118 | for k, v in dc.items(): 119 | dd[k].append(v) 120 | d = {t.tag: {k: v[0] if len(v) == 1 else v 121 | for k, v in dd.items()}} 122 | 123 | if t.attrib: 124 | d[t.tag].update((k, v) 125 | for k, v in t.attrib.items()) 126 | 127 | if t.text: 128 | text = t.text.strip() 129 | if children or t.attrib: 130 | if text: 131 | d[t.tag]['#text'] = text 132 | else: 133 | d[t.tag] = text 134 | return d 135 | 136 | # push subnode keys up one level and list dictionaries by index 137 | def push_up_and_index(tree, node, subnode, index_name): 138 | node_list = tree[node][subnode] 139 | if type(node_list) != list: 140 | node_list = [node_list] 141 | new_node_list = {} 142 | for nn in node_list: 143 | new_node_list[int(nn[index_name])] = nn 144 | tree[node] = new_node_list 145 | return tree 146 | 147 | # make it easier to find commonly used things 148 | def manipulate_sections(conf_db): 149 | # Take out top level "Profile" 150 | new_db = conf_db['Profile'] 151 | 152 | # push mix effect blocks up one level and list dictionaries by index 153 | new_db = push_up_and_index(new_db, "MixEffectBlocks", "MixEffectBlock", "index") 154 | # me_list = new_db['MixEffectBlocks']['MixEffectBlock'] 155 | # if type(me_list) != list: 156 | # me_list = [me_list] 157 | # new_me_list = {} 158 | # for me in me_list: 159 | # new_me_list[int(me['index'])] = me 160 | # new_db['MixEffectBlocks'] = new_me_list 161 | 162 | # push downstream keys up one level and list dictionaries by index 163 | new_db = push_up_and_index(new_db, "DownstreamKeys", "DownstreamKey", "index") 164 | # dsk_list = new_db['DownstreamKeys']['DownstreamKey'] 165 | # if type(dsk_list) != list: 166 | # dsk_list = [dsk_list] 167 | # new_dsk_list = {} 168 | # for dsk in dsk_list: 169 | # new_dsk_list[int(dsk['index'])] = dsk 170 | # new_db['DownstreamKeys'] = new_dsk_list 171 | 172 | # push downstream keys up one level and list dictionaries by index 173 | new_db = push_up_and_index(new_db, "ColorGenerators", "ColorGenerator", "index") 174 | 175 | # push inputs keys up one level and list dictionaries by id 176 | new_db['Settings'] = push_up_and_index(new_db['Settings'], "Inputs", "Input", "id") 177 | 178 | return new_db 179 | 180 | 181 | def get_config(name:str): 182 | return(conf_db.get(name)) 183 | 184 | def set_config(name:str, val): 185 | if name in conf_db: 186 | conf_db[name] = val 187 | else: 188 | raise ValueError() 189 | 190 | 191 | 192 | 193 | if __name__ == "__main__": 194 | db = config_init("default_config.xml") 195 | pprint(db) 196 | 197 | -------------------------------------------------------------------------------- /atem_packet.py: -------------------------------------------------------------------------------- 1 | # Packet stuff 2 | 3 | import struct 4 | import time 5 | import atem_commands 6 | 7 | 8 | PACKET_HEADER_SIZE = 12 9 | 10 | class ATEMFlags: 11 | COMMAND = 0x01 12 | INIT = 0x2 13 | RETRANSMITION = 0x4 14 | UNKNOWN = 0x8 15 | ACK = 0x10 16 | 17 | class Packet(object): 18 | def __init__(self, ip_and_port=('', 0), raw_packet=b''): 19 | # raw packet data 20 | self.ip_and_port = ip_and_port 21 | self.bytes = bytearray(raw_packet) 22 | 23 | # parsed packet data 24 | self.flags = 0x00 25 | self.packet_length = 0 26 | self.session_id = 0 27 | self.ACKed_packet_id = 0x0000 28 | self.packet_id = 0x0000 29 | self.commands = [] 30 | 31 | # extra stuff 32 | self.timestamp = time.monotonic() 33 | self.last_send_timestamp = 0 34 | self.raw_cmd_data = None # if this is not None then use this instead of commands. Used mainly for init packets. 35 | 36 | def parse_packet(self): 37 | flags_and_size = struct.unpack_from('!H', self.bytes, 0)[0] 38 | self.flags = (flags_and_size >> 11) & 0x001F 39 | self.packet_length = flags_and_size & 0x007F 40 | self.session_id, self.ACKed_packet_id, self.packet_id = struct.unpack_from('!2H 4x H', self.bytes, 2) 41 | if self.packet_length > PACKET_HEADER_SIZE: 42 | # deal with commands 43 | bytes_remaining = self.packet_length - PACKET_HEADER_SIZE 44 | packet_offset = PACKET_HEADER_SIZE 45 | if self.flags & ATEMFlags.INIT: 46 | # for INIT packets, just put the command data into raw_cmd_data 47 | self.raw_cmd_data = self.bytes[PACKET_HEADER_SIZE:] 48 | else: 49 | while bytes_remaining > 0: 50 | # Iterate through the packet commands and create a list of 51 | # command objects 52 | cmd_length, cmd_raw_name = struct.unpack_from('!H 2x 4s', self.bytes, packet_offset) 53 | cmd_name = cmd_raw_name.decode('utf-8') 54 | cmd_bytes = self.bytes[packet_offset:(packet_offset + cmd_length)] 55 | cmd_obj = atem_commands.get_command_object(cmd_bytes, cmd_name) 56 | cmd_obj.parse_cmd() 57 | self.commands.append(cmd_obj) 58 | packet_offset += cmd_length 59 | bytes_remaining -= cmd_length 60 | 61 | def to_bytes(self): 62 | #temp = self.bytes 63 | self.bytes = bytearray() 64 | if type(self.commands) != list: 65 | self.commands = [self.commands] 66 | if len(self.commands) > 0: 67 | self.flags |= ATEMFlags.COMMAND 68 | flags = ((self.flags & 0x001F) << 11) 69 | self.bytes += struct.pack('!H', flags) 70 | self.bytes += struct.pack('!2H 4x H', self.session_id, self.ACKed_packet_id, self.packet_id) 71 | self.packet_length = PACKET_HEADER_SIZE 72 | if self.raw_cmd_data != None: 73 | self.bytes += self.raw_cmd_data 74 | self.packet_length += len(self.raw_cmd_data) 75 | else: 76 | for cmd in self.commands: 77 | cmd.to_bytes() 78 | self.bytes += cmd.bytes 79 | self.packet_length += cmd.length 80 | # now add length of packet 81 | flags_and_size = struct.unpack_from('!H', self.bytes, 0)[0] 82 | flags_and_size |= (self.packet_length & 0x07FF) 83 | struct.pack_into('!H', self.bytes, 0, flags_and_size) 84 | #print(f"b1 = {temp}") 85 | #print(f"b2 = {self.bytes}") 86 | assert(self.packet_length == len(self.bytes)) 87 | 88 | 89 | if __name__ == "__main__": 90 | # Quick test 91 | b1 = b'\x10\x14Z\xce\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00' 92 | p = Packet(('192.168.1.50', 9910), b1) 93 | p.parse_packet() 94 | p.to_bytes() 95 | b2 = p.bytes 96 | assert(b1 == b2) 97 | -------------------------------------------------------------------------------- /atem_server.py: -------------------------------------------------------------------------------- 1 | # ATEM server: 2 | # takes in a packet object 3 | # processes the commands received 4 | 5 | 6 | import socket 7 | import argparse 8 | import sys 9 | import select 10 | 11 | from client_manager import ClientManager 12 | from atem_packet import Packet 13 | import atem_config 14 | 15 | 16 | 17 | def main(): 18 | # Parse the input aruments 19 | ap = argparse.ArgumentParser() 20 | 21 | ap.add_argument("--address", "-a", required=False, default="0.0.0.0", help="listening IP address, default=\"0.0.0.0\"") 22 | ap.add_argument("--port", "-p", required=False, default=9910, help="listening UDP Port, default=9910") 23 | ap.add_argument("--config", required=False, default="default_config.xml", help="config XML file from ATEM software (default=default_config.xml)") 24 | ap.add_argument("--debug", "-d", required=False, default="INFO", help="debug level (in quotes): NONE, INFO (default), WARNING, DEBUG") 25 | 26 | 27 | args = ap.parse_args() 28 | host = args.address 29 | port = args.port 30 | config_file = args.config 31 | 32 | print("ATEM Server Starting...") 33 | 34 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 35 | s.bind((host, port)) 36 | 37 | client_mgr = ClientManager() 38 | atem_config.config_init(config_file) 39 | 40 | print("ATEM Server Running...Hit ctrl-c to exit") 41 | 42 | while True: 43 | try: 44 | # Process incoming packets but timeout after a while so the clients 45 | # can perform cleanup and resend unresponded packets. 46 | readers, writers, errors = select.select([s], [], [], 0.050) 47 | if len(readers) > 0: 48 | try: 49 | bytes, addr = s.recvfrom(2048) 50 | packet = Packet(addr, bytes) 51 | packet.parse_packet() 52 | client = client_mgr.get_client(packet.ip_and_port, packet.session_id) 53 | client.process_inbound_packet(packet) 54 | except ConnectionResetError: 55 | print("connection reset!") 56 | s.close() 57 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 58 | s.bind((host, port)) 59 | continue 60 | except KeyboardInterrupt: 61 | raise 62 | 63 | # Perform regularly regardless of incoming packets 64 | client_mgr.run_clients(s) 65 | except KeyboardInterrupt: 66 | # quit 67 | sys.exit() 68 | 69 | 70 | 71 | 72 | # take next packet out of the UDP queue 73 | # parse packet 74 | # get the client object based on the packet contents 75 | # - if client doesn't exist then check whether it is an init packet and create a new client otherwise discard 76 | # send packet object to the client to process 77 | # clientObj: if the packet has a response with response packet id then remove the corresponding packet from the packet queue 78 | # clientObj sends to packet processor: packet processor reads commands, updates ATEM db and gets back list of command(s) in response, or none if nothing to return 79 | # clientObj then sends the response commands if any to the other clients if any, based on whether it is a multicast update or not 80 | # clientObj then builds a response packet and puts it in the packet queue 81 | # run through the client objects and see if there is anything to send out (or delete client object if timeouts have occurred) 82 | 83 | 84 | 85 | 86 | 87 | # Event Loop: 88 | 89 | #################### 90 | # packet parser 91 | #################### 92 | # take in packet and parse it into a python dictionary or object, including client info 93 | 94 | #################### 95 | # process packet 96 | #################### 97 | # -if init for a new client (or maybe it's a re-init?) 98 | # -check client list for an exact match (IP and socket) and reinit that client 99 | # -if not in client list then create new client 100 | 101 | # -if ack for a packet then remove the packet off the client's outbound queue 102 | # -remove any packets off the outbound queue that are older than the ack just received 103 | # -this ack packet may also contain new commmands, keep for next part 104 | 105 | # -if a new command then process the command (or array of commands) 106 | # -the result is a tuple of 2 things -- Maybe 1 and 2 are the same?? 107 | # 1. response packet for the client that sent the command(s) 108 | # 2. update packet for the other clients (add to a broadcast queue) 109 | 110 | ################################ 111 | # manage broadcast command list 112 | ################################ 113 | # distribute the update commands to all the clients if any 114 | 115 | ############################## 116 | # iterate through each client 117 | ############################## 118 | # -check packet state: if still in the init state and > 3 seconds has elapsed since last_receive then silently drop client 119 | 120 | # -run packet builder to take command objects and turn them into packets that can go onto the outbound queue 121 | # -the packet builder has to exist because one blob of commands may need to span multiple packets 122 | # -each packet gets assigned a sequential packet id by the packet builder (packet counter maintained in client object) 123 | 124 | # -if anything in the outbound queue: 125 | # -check the last time the client packet was sent 126 | # -if never sent (send time = 0) then send packet 127 | # -if more than 1 second has elapsed (now - last_send_time > 1sec), retransmit 128 | # -if last_response > 3 seconds then send init packet and drop client 129 | # -if nothing in outbound queue: 130 | # -if more than 0.5 second has elapsed (now - last_receive > 0.5sec) then send ping command 131 | 132 | 133 | 134 | 135 | if __name__ == "__main__": 136 | main() 137 | -------------------------------------------------------------------------------- /client_manager.py: -------------------------------------------------------------------------------- 1 | # The client manager: 2 | # Keeps a list of connected clients 3 | # Keeps track of the last time there was communication with that client 4 | # and ping the client regularly to ensure it is still there. 5 | 6 | import time 7 | import random 8 | from atem_packet import Packet, ATEMFlags 9 | import atem_commands 10 | from atem_commands import CommandCarrier 11 | import socket 12 | import struct 13 | from typing import List 14 | import copy 15 | 16 | CLIENT_ACTIVITY_TIMEOUT = 1.0 # seconds 17 | CLIENT_DROPOUT_TIMEOUT = 3.0 # seconds 18 | PACKET_RESEND_INTERVAL = 0.5 # seconds 19 | 20 | class ATEMClientState: 21 | UNINITIALIZED = 0 22 | INITIALIZE = 1 23 | WAIT_FOR_INIT_RESPONSE = 2 24 | ESTABLISHED = 3 25 | FINISHED = 4 26 | 27 | 28 | class ATEMClient(object): 29 | def __init__(self, ip_and_port=(), client_id=0, session_id=0, client_manager=None): 30 | self.ip_and_port = ip_and_port 31 | # There is a weird issue in Windows 32 | # where if the destination port is closed then the socket dies and 33 | # a subsequent recvfrom() will also not work. This is bad for a UDP 34 | # server, so it's safest if each client has it's own socket to 35 | # reply with. 36 | # https://bobobobo.wordpress.com/2009/05/17/udp-an-existing-connection-was-forcibly-closed-by-the-remote-host/ 37 | #self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 38 | self.client_id = client_id 39 | self.session_id = session_id 40 | self.current_packet_id = 0 41 | 42 | # State variables and other client maintenance 43 | # this is the last time the client sent a packet 44 | self.last_activity_time = 0 45 | self.last_ACKed_packet_id = 0 46 | self.client_state = ATEMClientState.UNINITIALIZED 47 | self.outbound_commands_list: List[CommandCarrier] = [] 48 | self.outbound_packet_list: List[Packet] = [] 49 | self.client_manager: ClientManager = client_manager 50 | 51 | # When an inbount packet has a command, store the packet id so 52 | # the ack can be sent on the next outgoing packet 53 | self.packet_id_needs_ack = None 54 | 55 | def get_next_packet_id(self): 56 | self.current_packet_id += 1 57 | return(self.current_packet_id) 58 | 59 | def add_to_outbound_commands_list(self, outbound_obj): 60 | self.outbound_commands_list.append(outbound_obj) 61 | 62 | def process_inbound_packet(self, in_packet: Packet): 63 | # timestamp the most recent activity from the client 64 | self.last_activity_time = time.monotonic() 65 | 66 | # if init packet then initialize this object and send a response 67 | if in_packet.flags & ATEMFlags.INIT and ( 68 | # first connection 69 | in_packet.raw_cmd_data == b'\x01\x00\x00\x00\x00\x00\x00\x00' 70 | # disconnect 71 | or in_packet.raw_cmd_data == b'\x04\x00\x00\x00\x00\x00\x00\x00'): 72 | # This is an init packet. (re)Initialize client 73 | if self.client_state != ATEMClientState.UNINITIALIZED: 74 | self.__init__(self.ip_and_port, self.client_id, self.session_id) 75 | self.last_activity_time = time.monotonic() 76 | # Create response packet 77 | init_response_packet = Packet(self.ip_and_port) 78 | init_response_packet.flags |= ATEMFlags.INIT 79 | init_response_packet.session_id = self.session_id 80 | # client ID must be baked into the session ID when the connection 81 | # is successful. Bytes 3..4 of the init response packet are the 82 | # client ID. The session ID formula appears to be: 83 | # 0x8000 + client_id 84 | init_response_packet.raw_cmd_data = struct.pack('!2H 4x', 0x0200, self.client_id) 85 | #init_response_packet.raw_cmd_data = b'\x02\x00\x00\x1a\x00\x00\x00\x00' 86 | init_response_packet.to_bytes() 87 | self.outbound_packet_list.append(init_response_packet) 88 | self.client_state = ATEMClientState.WAIT_FOR_INIT_RESPONSE 89 | return 90 | 91 | # if response packet then remove the matching outbound packet off the 92 | # outbound packet list, plus any older packets 93 | if in_packet.flags & ATEMFlags.ACK: 94 | if self.client_state == ATEMClientState.WAIT_FOR_INIT_RESPONSE and in_packet.ACKed_packet_id == self.current_packet_id: 95 | # Connected to client! 96 | # Expected client session id = 0x8000 + client_id 97 | self.session_id = 0x8000 + self.client_id 98 | self.client_state = ATEMClientState.ESTABLISHED 99 | print(f"Connected client={self.ip_and_port}, session=0x{self.session_id:x}") 100 | # Special case: response packet for the init (part of the handshake) 101 | setup_commands_list = atem_commands.build_setup_commands_list() 102 | # still need to add the session ID, packet_id and run to_bytes() on each packet 103 | for cmds in setup_commands_list: 104 | setup_packet = Packet(self.ip_and_port) 105 | setup_packet.session_id = self.session_id 106 | setup_packet.flags |= ATEMFlags.COMMAND 107 | setup_packet.packet_id = self.get_next_packet_id() 108 | setup_packet.commands = cmds 109 | setup_packet.to_bytes() 110 | self.outbound_packet_list.append(setup_packet) 111 | 112 | last_packet = Packet(self.ip_and_port) 113 | last_packet.session_id = self.session_id 114 | last_packet.flags |= ATEMFlags.COMMAND 115 | last_packet.packet_id = self.get_next_packet_id() 116 | last_packet.commands = atem_commands.Cmd_InCm() 117 | last_packet.to_bytes() 118 | self.outbound_packet_list.append(last_packet) 119 | 120 | else: 121 | packets_to_keep = [] 122 | while self.outbound_packet_list: 123 | p = self.outbound_packet_list.pop(0) 124 | # discard if this packet is older than the packet being acked 125 | if p.packet_id <= in_packet.ACKed_packet_id and p.packet_id != 0: 126 | pass # discard packet 127 | else: 128 | packets_to_keep.append(p) 129 | # Put the packets to keep back into the outbout_packet_list 130 | self.outbound_packet_list = packets_to_keep 131 | 132 | 133 | if in_packet.flags & ATEMFlags.COMMAND: 134 | # This packet has commands 135 | # It will have to process the command(s) and return an ACK packet 136 | # which may include response commands. 137 | # Also, it will likely need to update all the other clients with 138 | # the new information. 139 | 140 | # Get the response command(s). The result is one or more 141 | # commands, contained in a list of CommandCarrier objects. The 142 | # object contains metadata for the command(s). There 143 | # may be more than one CommandCarrier object if more 144 | # than one packet needs to be sent as a result of the 145 | # command (eg. a transition). 146 | # If it returns an empty list then it is an unknown command, 147 | # so just send an ack packet to keep the client happy. 148 | cmds_carrier_list = atem_commands.get_response(in_packet.commands) 149 | if len(cmds_carrier_list) == 0: 150 | # unknown command, just ack 151 | ack_packet = Packet(self.ip_and_port) 152 | ack_packet.flags |= ATEMFlags.ACK 153 | ack_packet.ACKed_packet_id = in_packet.packet_id 154 | ack_packet.session_id = self.session_id 155 | ack_packet.to_bytes() 156 | self.last_ACKed_packet_id = in_packet.packet_id 157 | self.outbound_packet_list.append(ack_packet) 158 | else: 159 | # iterate through the commands sent back 160 | sent_ack = False 161 | for cc in cmds_carrier_list: 162 | if cc.multicast == True: 163 | self.client_manager.send_to_other_clients(self, cc) 164 | if sent_ack == False: 165 | cc.ack_packet_id = in_packet.packet_id 166 | self.last_ACKed_packet_id = in_packet.packet_id 167 | sent_ack = True 168 | self.outbound_commands_list.append(cc) 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | def update(self, sock: socket.socket): 177 | now = time.monotonic() 178 | 179 | # Perform regular client update activities. This mainly involves creating packets 180 | # and sending, or retransmitting packets if they haven't been ACK'd. 181 | # 1. iterate through the outbound objects 182 | # generate one or more packets (split into multiple packets based on MTU=1500) 183 | # add to the outbound packet list 184 | # TODO: if one command object has too many commands in it, then split 185 | # across multiple packets 186 | carriers_to_keep = [] 187 | for cmd_carrier in self.outbound_commands_list: 188 | if cmd_carrier.send_time > now: 189 | # not time to send this packet yet 190 | carriers_to_keep.append(cmd_carrier) 191 | else: 192 | out_packet = Packet(self.ip_and_port) 193 | out_packet.flags |= ATEMFlags.COMMAND 194 | if cmd_carrier.ack_packet_id > 0: 195 | # this is an ack packet 196 | out_packet.flags |= ATEMFlags.ACK 197 | out_packet.ACKed_packet_id = cmd_carrier.ack_packet_id 198 | out_packet.packet_id = self.get_next_packet_id() 199 | out_packet.session_id = self.session_id 200 | out_packet.commands = cmd_carrier.commands 201 | out_packet.to_bytes() 202 | self.outbound_packet_list.append(out_packet) 203 | self.outbound_commands_list = carriers_to_keep 204 | 205 | 206 | # 2. check the inactivity time (based on the last time the client communicated to the server) 207 | # If > client inactivity timeout (say 1 sec) then generate an "are you there?" packet 208 | # If > client dropout timeout (say 3 sec) then generate a "goodbye" init packet 209 | if self.client_state == ATEMClientState.ESTABLISHED: 210 | if now - self.last_activity_time > CLIENT_ACTIVITY_TIMEOUT: 211 | ping_packet = Packet(self.ip_and_port) 212 | ping_packet.flags |= ATEMFlags.COMMAND | ATEMFlags.ACK 213 | ping_packet.packet_id = self.get_next_packet_id() 214 | ping_packet.session_id = self.session_id 215 | ping_packet.ACKed_packet_id = self.last_ACKed_packet_id 216 | ping_packet.to_bytes() 217 | self.outbound_packet_list.append(ping_packet) 218 | 219 | if now - self.last_activity_time > CLIENT_DROPOUT_TIMEOUT: 220 | goodbye_packet = Packet(self.ip_and_port) 221 | goodbye_packet.flags |= ATEMFlags.INIT 222 | goodbye_packet.session_id = self.session_id 223 | goodbye_packet.to_bytes() 224 | self.outbound_packet_list.append(goodbye_packet) 225 | 226 | # 3. iterate through the outbound packets 227 | # if it's an init packet, send and delete 228 | # if it's a response packet only with no command data then send and delete 229 | # if it's a packet with command data and send timestamp is 0 then send and keep 230 | # if it's a packet with command data and send timestamp is >0 then 231 | # wait until the response timeout has elapsed (say 1 sec) and send again 232 | packets_to_keep = [] 233 | while self.outbound_packet_list: 234 | pkt = self.outbound_packet_list.pop(0) 235 | if pkt.flags & ATEMFlags.INIT: 236 | sock.sendto(pkt.bytes, pkt.ip_and_port) 237 | # init response, discard packet after sending 238 | elif (pkt.flags & ATEMFlags.ACK) and ((pkt.flags & ATEMFlags.COMMAND) == 0): 239 | sock.sendto(pkt.bytes, pkt.ip_and_port) 240 | # ping response, discard packet after sending 241 | elif (pkt.flags & ATEMFlags.COMMAND) and pkt.last_send_timestamp == 0: 242 | sock.sendto(pkt.bytes, pkt.ip_and_port) 243 | pkt.last_send_timestamp = now 244 | # command packet, keep until an ack has been received 245 | packets_to_keep.append(pkt) 246 | elif (pkt.flags & ATEMFlags.COMMAND) and pkt.last_send_timestamp > 0: 247 | if now - pkt.last_send_timestamp > PACKET_RESEND_INTERVAL: 248 | pkt.flags |= ATEMFlags.RETRANSMITION 249 | sock.sendto(pkt.bytes, pkt.ip_and_port) 250 | pkt.last_send_timestamp = now 251 | # command packet (resending), keep until an ack has been received 252 | packets_to_keep.append(pkt) 253 | # Put the packets to keep back into the outbout_packet_list 254 | self.outbound_packet_list = packets_to_keep 255 | 256 | # 4. If client dropout timeout (say >3 sec) then delete client 257 | if now - self.last_activity_time > CLIENT_DROPOUT_TIMEOUT: 258 | self.client_state = ATEMClientState.FINISHED 259 | 260 | 261 | 262 | 263 | class ClientManager(object): 264 | def __init__(self): 265 | self.clients = [] 266 | # every client needs a unique id, which gets baked into the session ID 267 | self.client_counter = 0 268 | 269 | # Get the client based on the packet info or create a new client 270 | def get_client(self, ip_and_port, session_id) -> ATEMClient: 271 | for client in self.clients: 272 | if client.ip_and_port == ip_and_port and client.session_id == session_id: 273 | return client 274 | client_id = self.get_next_client_id() 275 | new_client = ATEMClient(ip_and_port, client_id, session_id, self) 276 | print(f"Create client={new_client.ip_and_port}, session=0x{new_client.session_id:x}") 277 | self.clients.append(new_client) 278 | print(f"client count={len(self.clients)}") 279 | return new_client 280 | 281 | def run_clients(self, sock: socket.socket): 282 | clients_to_keep = [] 283 | drop = False 284 | while self.clients: 285 | client = self.clients.pop(0) 286 | client.update(sock) 287 | if client.client_state == ATEMClientState.FINISHED: 288 | print(f"Dropping client={client.ip_and_port}, session=0x{client.session_id:x}") 289 | drop = True 290 | else: 291 | clients_to_keep.append(client) 292 | self.clients = clients_to_keep 293 | if drop == True: 294 | print(f"client count={len(self.clients)}") 295 | 296 | def send_to_other_clients(self, sending_client, outbound_obj): 297 | for client in self.clients: 298 | if client.ip_and_port == sending_client.ip_and_port and client.session_id == sending_client.session_id: 299 | # this is the sending client, so don't send to itself 300 | pass 301 | else: 302 | # Give each client a shallow copy of the commands carrier so the ack_packet_id 303 | # can be different for each client. 304 | client.outbound_commands_list.append(copy.copy(outbound_obj)) 305 | 306 | def get_next_client_id(self): 307 | self.client_counter += 1 308 | return self.client_counter 309 | -------------------------------------------------------------------------------- /default_config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 |