Ejemplo n.º 1
0
def flvsplit(outbase, srcfile,
             framerate=12, keyframe=120, blocksize=32,
             duration=sys.maxsize, overlap=0, nameformat='%s-%03d.flv',
             force=False, debug=0):
    fin = open(srcfile, 'rb')
    parser = FLVParser(fin)
    totaldur = parser.get_duration()
    (_,_,totaldur,_,_) = parser[-1]
    print('total duration: %d' % totaldur, file=sys.stderr)
    t0 = 0
    i = 0
    while 1:
        outfile = nameformat % (outbase, i)
        if not force and os.path.exists(outfile):
            raise IOError('file already exists: %r' % outfile)
        fout = open(outfile, 'wb')
        writer = FLVWriter(fout, has_video=True, has_audio=True,
                           framerate=framerate, debug=debug)
        processor = FLVMovieProcessor(writer=writer, debug=debug)
        audiosink = AudioSink()
        videosink = FLVVideoSink(writer, framerate=framerate, keyframe=keyframe,
                                 blocksize=blocksize, debug=debug)
        t1 = min(t0+duration, totaldur)
        print('writing %r (%d-%d)...' % (outfile, t0, t1), file=sys.stderr)
        ranges = MultipleRange([(t0, t1)])
        processor.process_flv(parser, audiosink, videosink, ranges=ranges)
        writer.close()
        fout.close()
        if totaldur <= t1: break
        t0 = max(0, t1-overlap)
        i += 1
    parser.close()
    fin.close()
    return
Ejemplo n.º 2
0
def flvsplit(outbase, srcfile, 
             framerate=12, keyframe=120, blocksize=32,
             duration=sys.maxint, overlap=0, nameformat='%s-%03d.flv',
             force=False, debug=0):
    fin = file(srcfile, 'rb')
    parser = FLVParser(fin)
    totaldur = parser.get_duration()
    (_,_,totaldur,_,_) = parser[-1]
    print >>sys.stderr, 'total duration: %d' % totaldur
    t0 = 0
    i = 0
    while 1:
        outfile = nameformat % (outbase, i)
        if not force and os.path.exists(outfile):
            raise IOError('file already exists: %r' % outfile)
        fout = file(outfile, 'wb')
        writer = FLVWriter(fout, has_video=True, has_audio=True,
                           framerate=framerate, debug=debug)
        processor = FLVMovieProcessor(writer=writer, debug=debug)
        audiosink = AudioSink()
        videosink = FLVVideoSink(writer, framerate=framerate, keyframe=keyframe,
                                 blocksize=blocksize, debug=debug)
        t1 = min(t0+duration, totaldur)
        print >>sys.stderr, 'writing %r (%d-%d)...' % (outfile, t0, t1)
        ranges = MultipleRange([(t0, t1)])
        processor.process_flv(parser, audiosink, videosink, ranges=ranges)
        writer.close()
        fout.close()
        if totaldur <= t1: break
        t0 = max(0, t1-overlap)
        i += 1
    parser.close()
    fin.close()
    return
Ejemplo n.º 3
0
def flvcat(outfile, srcfiles,
           framerate=12, keyframe=120,
           blocksize=32, clipping=None,
           panwindow=None, panspeed=0,
           force=False, debug=0):
    if not force and os.path.exists(outfile):
        raise IOError('file already exists: %r' % outfile)
    fout = open(outfile, 'wb')
    writer = FLVWriter(fout, has_video=True, has_audio=True, framerate=framerate, debug=debug)
    processor = FLVMovieProcessor(writer=writer, debug=debug)
    for fname in srcfiles:
        ranges = None
        m = re.match(r'([^:]+):(.+)$', fname)
        if m:
            fname = m.group(1)
            ranges = MultipleRange(m.group(2))
        fin = open(fname, 'rb')
        parser = FLVParser(fin)
        audiosink = AudioSink()
        videosink = FLVVideoSink(writer, framerate=framerate, keyframe=keyframe,
                                 blocksize=blocksize, clipping=clipping,
                                 panwindow=panwindow, panspeed=panspeed,
                                 debug=debug)
        processor.process_flv(parser, audiosink, videosink, ranges=ranges)
        parser.close()
        fin.close()
    writer.close()
    fout.close()
    return
Ejemplo n.º 4
0
def flvcat(outfile, srcfiles,
           framerate=12, keyframe=120,
           blocksize=32, clipping=None,
           panwindow=None, panspeed=0,
           force=False, debug=0):
    if not force and os.path.exists(outfile):
        raise IOError('file already exists: %r' % outfile)
    fout = file(outfile, 'wb')
    writer = FLVWriter(fout, has_video=True, has_audio=True, framerate=framerate, debug=debug)
    processor = FLVMovieProcessor(writer=writer, debug=debug)
    for fname in srcfiles:
        ranges = None
        m = re.match(r'([^:]+):(.+)$', fname)
        if m:
            fname = m.group(1)
            ranges = MultipleRange(m.group(2))
        fin = file(fname, 'rb')
        parser = FLVParser(fin)
        audiosink = AudioSink()
        videosink = FLVVideoSink(writer, framerate=framerate, keyframe=keyframe,
                                 blocksize=blocksize, clipping=clipping,
                                 panwindow=panwindow, panspeed=panspeed,
                                 debug=debug)
        processor.process_flv(parser, audiosink, videosink, ranges=ranges)
        parser.close()
        fin.close()
    writer.close()
    fout.close()
    return
Ejemplo n.º 5
0
def flvrec(filename,
           host='localhost',
           port=5900,
           framerate=12,
           keyframe=120,
           preferred_encoding=(0, ),
           pwdfile=None,
           blocksize=32,
           clipping=None,
           cmdline=None,
           debug=0,
           verbose=1):
    fp = file(filename, 'wb')
    if pwdfile:
        pwdcache = PWDFile(pwdfile)
    else:
        pwdcache = PWDCache('%s:%d' % (host, port))
    writer = FLVWriter(fp, framerate=framerate, debug=debug)
    sink = FLVVideoSink(writer,
                        blocksize=blocksize,
                        framerate=framerate,
                        keyframe=keyframe,
                        clipping=clipping,
                        debug=debug)
    client = RFBNetworkClient(host,
                              port,
                              sink,
                              timeout=500 / framerate,
                              pwdcache=pwdcache,
                              preferred_encoding=preferred_encoding,
                              debug=debug)
    if verbose:
        print >> sys.stderr, 'start recording'
    pid = 0
    if cmdline:
        pid = os.fork()
        if pid == 0:
            os.setpgrp()
            os.execvp('sh', ['sh', '-c', cmdline])
            sys.exit(1)
    retval = 0
    try:

        def sigint_handler(sig, frame):
            raise KeyboardInterrupt

        signal.signal(signal.SIGINT, sigint_handler)
        client.open()
        try:
            while 1:
                client.idle()
        finally:
            client.close()
    except KeyboardInterrupt:
        pass
    except socket.error, e:
        print >> sys.stderr, 'Socket error:', e
        retval = 1
Ejemplo n.º 6
0
def mp3add(srcfile, mp3files, outfile, force=False, debug=0):
    if not force and os.path.exists(outfile):
        raise IOError('file already exists: %r' % outfile)
    fout = open(outfile, 'wb')
    writer = FLVWriter(fout, debug=debug, has_video=True, has_audio=True)
    fin = open(srcfile, 'rb')
    parser = FLVParser(fin, debug=debug)
    for (i, (tag, _, timestamp, _, _)) in enumerate(parser):
        if tag == 8:
            pass
        elif tag == 9:
            writer.write_video_frame(timestamp, parser.get_data(i))
        elif tag == 18:
            (k, v) = parser.parse_metadata(parser.get_data(i))
            if k == 'onMetaData':
                writer.set_screen_size(v.get('width', 0), v.get('height', 0))
            else:
                writer.write_other_data(tag, parser.get_data(i))
    parser.close()
    fin.close()
    for fname in mp3files:
        m = re.match(r'([^:]+):(.+)$', fname)
        ranges = None
        if m:
            fname = m.group(1)
            ranges = MultipleRange(m.group(2))
        audio = AudioSink()
        fp = open(fname, 'rb')
        audio.load(fp)
        fp.close()
        if ranges:
            for (_, s, e) in ranges:
                audio.put(writer, s, e, s)
        else:
            audio.put(writer)
    writer.close()
    fout.close()
    return
Ejemplo n.º 7
0
def mp3add(srcfile, mp3files, outfile, force=False, debug=0):
    if not force and os.path.exists(outfile):
        raise IOError('file already exists: %r' % outfile)
    fout = file(outfile, 'wb')
    writer = FLVWriter(fout, debug=debug, has_video=True, has_audio=True)
    fin = file(srcfile, 'rb')
    parser = FLVParser(fin, debug=debug)
    for (i, (tag, _, timestamp, _, _)) in enumerate(parser):
        if tag == 8:
            pass
        elif tag == 9:
            writer.write_video_frame(timestamp, parser.get_data(i))
        elif tag == 18:
            (k,v) = parser.parse_metadata(parser.get_data(i))
            if k == 'onMetaData':
                writer.set_screen_size(v.get('width',0), v.get('height',0))
            else:
                writer.write_other_data(tag, parser.get_data(i))
    parser.close()
    fin.close()
    for fname in mp3files:
        m = re.match(r'([^:]+):(.+)$', fname)
        ranges = None
        if m:
            fname = m.group(1)
            ranges = MultipleRange(m.group(2))
        audio = AudioSink()
        fp = file(fname, 'rb')
        audio.load(fp)
        fp.close()
        if ranges:
            for (_,s,e) in ranges:
                audio.put(writer, s, e, s)
        else:
            audio.put(writer)
    writer.close()
    fout.close()
    return
Ejemplo n.º 8
0
    def run(self):
        self.fp = file(self.filename, 'wb')

        self.writer = FLVWriter(self.fp, framerate = self.framerate, logger  = self.logger)

        self.sink = FLVVideoSink(
                            self.writer,
                            blocksize = self.blocksize, 
                            framerate = self.framerate, 
                            keyframe = self.keyframe,
                            clipping = self.clipping, 
                            logger = self.logger
                    )

        self.client = RFBNetworkClient(
                                self.host, 
                                self.port, 
                                self.sink, 
                                timeout = 500 / self.framerate,
                                pwdcache = self.pwdcache, 
                                preferred_encoding = self.preferred_encoding,
                                logger = self.logger
                        )

        self.logger.info('[vnc2flv] Start recording')

        try:
            self.client.open()

            self.is_recording = True
            while self.keep_recording:
                try:
                    self.client.idle()
                except RFBError as e:
                    self.logger.error("[vnc2flv] RFB error: %s"%unicode(e))
                    sleep(1)

            self.is_recording = False

        except socket.error as e:
            self.is_recording = False
            tb = traceback.format_exc()
            self.logger.error("[vnc2flv] Socket traceback: %s"%unicode(tb))
            self.stop()
            raise Exception("[vnc2flv] Socket error: %s"%unicode(e))
Ejemplo n.º 9
0
    def client_from_config(config):
        password = config.get('password')
        filename = config.get('filename')
        host = config.get('host')
        port = config.get('port')
        output_path = config.get('output_path')
        framerate = config.get('framerate')
        keyframe = config.get('keyframe')
        preferred_encoding = config.get('preferred_encoding')
        blocksize = config.get('blocksize')
        clipping = config.get('clipping')
        debug = config.get('debug')

        pwdcache = MemoryPWD(password)

        try:
            os.makedirs(output_path)
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(output_path):
                pass
            else:
                raise
        fp = open(os.path.join(output_path, filename), 'wb')

        writer = FLVWriter(fp, framerate=framerate, debug=debug)
        sink = FLVVideoSink(writer,
                            blocksize=blocksize,
                            framerate=framerate,
                            keyframe=keyframe,
                            clipping=clipping,
                            debug=debug)
        client = RFBNetworkClient(host,
                                  port,
                                  sink,
                                  timeout=500 / framerate,
                                  pwdcache=pwdcache,
                                  preferred_encoding=preferred_encoding,
                                  debug=debug)

        return fp, writer, client
Ejemplo n.º 10
0
class FlvRec(threading.Thread):
    """Record a vnc session to a flv file
    """
    def __init__(self, filename,
            host = 'localhost',
            port = 5900,
            framerate = 12,
            keyframe = 120,
            preferred_encoding = (0,),
            pwdfile = None,
            blocksize = 32,
            clipping = None,
            logger_level = 'INFO',
            logger_log_dir = False,
            logger_name = 'CastroRedux'):

        super(FlvRec, self).__init__()

        self.filename = filename
        self.host = host
        self.port = port
        self.framerate = framerate
        self.keyframe = keyframe
        self.preferred_encoding = preferred_encoding
        self.pwdfile = pwdfile
        self.blocksize = blocksize
        self.clipping = clipping
        self.logger_name = logger_name
        self.logger_level = logger_level
        self.logger_log_dir = logger_log_dir

        self.pwdcache = PWDFile(self.pwdfile)
        self.is_recording = False
        self.keep_recording = True

        self.configure_logger()

    def configure_logger(self):
        #Logger
        self.logger = logging.getLogger(self.logger_name)

        #File logger
        if self.logger_log_dir:
            fh = logging.FileHandler(os.path.join(
                self.logger_log_dir,
                '%s-CastroRedux.log'%self.logger_name
            ))
            self.logger.addHandler(fh)

        #Stream logger 
        self.logger.addHandler(logging.StreamHandler())

        #Set level
        self.logger.setLevel(self.logger_level)

    def run(self):
        self.fp = file(self.filename, 'wb')

        self.writer = FLVWriter(self.fp, framerate = self.framerate, logger  = self.logger)

        self.sink = FLVVideoSink(
                            self.writer,
                            blocksize = self.blocksize, 
                            framerate = self.framerate, 
                            keyframe = self.keyframe,
                            clipping = self.clipping, 
                            logger = self.logger
                    )

        self.client = RFBNetworkClient(
                                self.host, 
                                self.port, 
                                self.sink, 
                                timeout = 500 / self.framerate,
                                pwdcache = self.pwdcache, 
                                preferred_encoding = self.preferred_encoding,
                                logger = self.logger
                        )

        self.logger.info('[vnc2flv] Start recording')

        try:
            self.client.open()

            self.is_recording = True
            while self.keep_recording:
                try:
                    self.client.idle()
                except RFBError as e:
                    self.logger.error("[vnc2flv] RFB error: %s"%unicode(e))
                    sleep(1)

            self.is_recording = False

        except socket.error as e:
            self.is_recording = False
            tb = traceback.format_exc()
            self.logger.error("[vnc2flv] Socket traceback: %s"%unicode(tb))
            self.stop()
            raise Exception("[vnc2flv] Socket error: %s"%unicode(e))

    def stop(self):
        self.logger.info('[vnc2flv] Stop recording...')

        self.keep_recording = False
        #Wait until the recording is over
        for i in range(10):
            if self.is_recording:
                sleep(1)
            else:
                break

        self.client.close()
        self.writer.close()
        self.fp.close()