#!/usr/bin/env python import yaml try: from yaml import CLoader as Loader from yaml import CDumper as Dumper except ImportError: from yaml import Loader, Dumper import time import os import threading import signal import sys import subprocess settings = 'ffmpeg.cfg' # Get settings from yaml config file def getSettings(): f = open(settings, 'r') cfg = yaml.load(f,Loader=Loader) f.close() return cfg # Build the command to execute def getStarted(name): try: cmd = "%s %s" % (cfg['binary'], cfg[name]['full']) except: cmd = "%s %s -i %s -vcodec %s %s" % (cfg['binary'], cfg[name]['args'], cfg[name]['url'], cfg[name]['codec'], cfg[name]['target']) return cmd # Kill all streams and exit def killall(signal, frame): for thr in mastert: mastert[thr].stop() sys.exit(0) # Create signal traps def trap(t): global mastert mastert = t signal.signal(1,killall) signal.signal(2,killall) signal.signal(15,killall) # Get a list of all cams (from config) def getCams(): return cfg['cams'].split() def writepid(name): id = str(os.getpid()) f = open("stream-%s.pid" % name, "w") f.write(id) f.close() # Create a thread to run the streams in class stream(threading.Thread): # Init def __init__(self, name): self.threshold = 120 threading.Thread.__init__(self) self.cmd = getStarted(name).split() self.name = name fd = os.open( "stream-%s.log" % name, os.O_RDWR|os.O_CREAT ) self.f = os.fdopen(fd, "w") self.debug = open("debug-%s.log" % name, "w") self.debug.write("started: %s " % " ".join(self.cmd)) # Life def run(self): self.run = 1 pointer = 0 self.startprocess() while self.run: cpid = self.checkpid() if not cpid: self.startprocess() self.debug.write("new process started\n") self.debug.write( "%s %s %s %s %s\n" % (pointer, self.f.tell(), cpid, self.cycle, "a") ) self.debug.flush() self.cycle += 10 if self.cycle > self.threshold and self.f.tell() == pointer: self.stop(True) pointer = self.f.tell() time.sleep(10) # cmd def startprocess(self): self.cycle = 0 self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stdin=None, stderr=self.f, shell=False, universal_newlines=True) self.pidid = self.process.pid self.debug.write( "started stream: %s/%s" % (self.name, self.pidid) ) # Check Run def checkpid(self): exit = self.process.poll() if exit == None: return True else: return False # Kill def stop(self, soft=False): self.debug.write( "killed stream: %s/%s" % (self.name, self.pidid)) if soft == False: self.run = 0 self.f.close() self.debug.close() os.kill(self.pidid, 9) # Load settings cfg = getSettings()