Exemple #1
0
 def __init__(self):
     StubClientMixin.__init__(self)
     #rpc / dbus:
     self.rpc_counter = AtomicInteger()
     self.rpc_pending_requests = {}
     self.server_dbus_proxy = False
     self.server_rpc_types = []
     self.rpc_filter_timers = {}
Exemple #2
0
 def __init__(self, uid, gid, env_options, session_options, socket_dir,
              video_encoder_modules, csc_modules, client_conn, disp_desc,
              client_state, cipher, encryption_key, server_conn, caps,
              message_queue):
     Process.__init__(self, name=str(client_conn))
     self.uid = uid
     self.gid = gid
     self.env_options = env_options
     self.session_options = session_options
     self.socket_dir = socket_dir
     self.video_encoder_modules = video_encoder_modules
     self.csc_modules = csc_modules
     self.client_conn = client_conn
     self.disp_desc = disp_desc
     self.client_state = client_state
     self.cipher = cipher
     self.encryption_key = encryption_key
     self.server_conn = server_conn
     self.caps = caps
     log("ProxyProcess%s",
         (uid, gid, env_options, session_options, socket_dir,
          video_encoder_modules, csc_modules, client_conn, disp_desc,
          repr_ellipsized(str(client_state)), cipher, encryption_key,
          server_conn, "%s: %s.." %
          (type(caps), repr_ellipsized(str(caps))), message_queue))
     self.client_protocol = None
     self.server_protocol = None
     self.exit = False
     self.main_queue = None
     self.message_queue = message_queue
     self.encode_queue = None  #holds draw packets to encode
     self.encode_thread = None
     self.video_encoding_defs = None
     self.video_encoders = None
     self.video_encoders_last_used_time = None
     self.video_encoder_types = None
     self.video_helper = None
     self.lost_windows = None
     #for handling the local unix domain socket:
     self.control_socket_cleanup = None
     self.control_socket = None
     self.control_socket_thread = None
     self.control_socket_path = None
     self.potential_protocols = []
     self.max_connections = MAX_CONCURRENT_CONNECTIONS
     self.timer_id = AtomicInteger()
     self.timers = {}
     self.timer_lock = RLock()
Exemple #3
0
    def test_AtomicInteger_threading(self):
        a = AtomicInteger()
        N = 5000

        def increase():
            for _ in range(N):
                a.increase()

        def decrease():
            for _ in range(N):
                a.decrease()

        T = 20
        from threading import Thread
        threads = []
        for i in range(T):
            if i % 2 == 0:
                target = increase
            else:
                target = decrease
            t = Thread(target=target, name=str(target))
            t.daemon = True
            threads.append(t)
        for t in threads:
            t.start()
        for t in threads:
            t.join()
Exemple #4
0
class RPCClient(StubClientMixin):
    def __init__(self):
        StubClientMixin.__init__(self)
        #rpc / dbus:
        self.rpc_counter = AtomicInteger()
        self.rpc_pending_requests = {}
        self.server_dbus_proxy = False
        self.server_rpc_types = []
        self.rpc_filter_timers = {}

    def cleanup(self):
        timers = tuple(self.rpc_filter_timers.values())
        self.rpc_filter_timers = {}
        for t in timers:
            self.source_remove(t)

    def run(self):
        pass

    def parse_server_capabilities(self):
        c = self.server_capabilities
        self.server_dbus_proxy = c.boolget("dbus_proxy")
        #default for pre-0.16 servers:
        if self.server_dbus_proxy:
            default_rpc_types = ["dbus"]
        else:
            default_rpc_types = []
        self.server_rpc_types = c.strlistget("rpc-types", default_rpc_types)
        return True

    def process_ui_capabilities(self):
        pass

    def rpc_call(self,
                 rpc_type,
                 rpc_args,
                 reply_handler=None,
                 error_handler=None):
        assert rpc_type in self.server_rpc_types, "server does not support %s rpc" % rpc_type
        rpcid = self.rpc_counter.increase()
        self.rpc_filter_pending(rpcid)
        #keep track of this request (for timeout / error and reply callbacks):
        req = monotonic_time(
        ), rpc_type, rpc_args, reply_handler, error_handler
        self.rpc_pending_requests[rpcid] = req
        log("sending %s rpc request %s to server: %s", rpc_type, rpcid, req)
        packet = ["rpc", rpc_type, rpcid] + rpc_args
        self.send(*packet)
        self.rpc_filter_timers[rpcid] = self.timeout_add(
            RPC_TIMEOUT, self.rpc_filter_pending, rpcid)

    def rpc_filter_pending(self, rpcid):
        """ removes timed out dbus requests """
        del self.rpc_filter_timers[rpcid]
        for k in tuple(self.rpc_pending_requests.keys()):
            v = self.rpc_pending_requests.get(k)
            if v is None:
                continue
            t, rpc_type, _rpc_args, _reply_handler, ecb = v
            if 1000 * (monotonic_time() - t) >= RPC_TIMEOUT:
                log.warn("%s rpc request: %s has timed out", rpc_type,
                         _rpc_args)
                try:
                    del self.rpc_pending_requests[k]
                    if ecb is not None:
                        ecb("timeout")
                except Exception as e:
                    log.error(
                        "Error during timeout handler for %s rpc callback:",
                        rpc_type)
                    log.error(" %s", e)
                    del e

    ######################################################################
    #packet handlers
    def _process_rpc_reply(self, packet):
        rpc_type, rpcid, success, args = packet[1:5]
        log("rpc_reply: %s", (rpc_type, rpcid, success, args))
        v = self.rpc_pending_requests.get(rpcid)
        assert v is not None, "pending dbus handler not found for id %s" % rpcid
        assert rpc_type == v[
            1], "rpc reply type does not match: expected %s got %s" % (
                v[1], rpc_type)
        del self.rpc_pending_requests[rpcid]
        if success:
            ctype = "ok"
            rh = v[-2]  #ok callback
        else:
            ctype = "error"
            rh = v[-1]  #error callback
        if rh is None:
            log("no %s rpc callback defined, return values=%s", ctype, args)
            return
        log("calling %s callback %s(%s)", ctype, rh, args)
        try:
            rh(*args)
        except Exception as e:
            log.error("Error processing rpc reply handler %s(%s) :", rh, args)
            log.error(" %s", e)

    def init_authenticated_packet_handlers(self):
        log("init_authenticated_packet_handlers()")
        self.add_packet_handler("rpc-reply", self._process_rpc_reply)
Exemple #5
0
    return dbus_to_native(*args)


def ni(*args):
    return int(n(*args))


def nb(*args):
    return bool(n(*args))


def ns(*args):
    return str(n(*args))


sequence = AtomicInteger()


class DBUS_Source(dbus.service.Object):
    SUPPORTS_MULTIPLE_OBJECT_PATHS = True

    def __init__(self, source=None, extra=""):
        self.source = source
        session_bus = init_session_bus()
        name = BUS_NAME
        self.path = PATH + str(sequence.increase())
        if extra:
            name += extra.replace(".", "_").replace(":", "_")
        bus_name = dbus.service.BusName(name, session_bus)
        dbus.service.Object.__init__(self, bus_name, self.path)
        self.log("(%s)", source)
from xpra.server.source.clientinfo_mixin import ClientInfoMixin
from xpra.server.source.dbus_mixin import DBUS_Mixin
from xpra.server.source.windows_mixin import WindowsMixin
from xpra.server.source.encodings_mixin import EncodingsMixin
from xpra.server.source.idle_mixin import IdleMixin
from xpra.server.source.input_mixin import InputMixin
from xpra.server.source.avsync_mixin import AVSyncMixin
from xpra.server.source.clientdisplay_mixin import ClientDisplayMixin
from xpra.server.source.webcam_mixin import WebcamMixin
from xpra.os_util import monotonic_time
from xpra.util import merge_dicts, flatten_dict, notypedict, envbool, envint, AtomicInteger

BANDWIDTH_DETECTION = envbool("XPRA_BANDWIDTH_DETECTION", True)
MIN_BANDWIDTH = envint("XPRA_MIN_BANDWIDTH", 5 * 1024 * 1024)

counter = AtomicInteger()
"""
This class mediates between the server class (which only knows about actual window objects and display server events)
and the client specific WindowSource instances (which only know about window ids
and manage window pixel compression).
It sends messages to the client via its 'protocol' instance (the network connection),
directly for a number of cases (cursor, sound, notifications, etc)
or on behalf of the window sources for pixel data.

Strategy: if we have 'ordinary_packets' to send, send those.
When we don't, then send packets from the 'packet_queue'. (compressed pixels or clipboard data)
See 'next_packet'.

The UI thread calls damage(), which goes into WindowSource and eventually (batching may be involved)
adds the damage pixels ready for processing to the encode_work_queue,
items are picked off by the separate 'encode' thread (see 'encode_loop')
Exemple #7
0
def test_gl_client_window(gl_client_window_class,
                          max_window_size=(1024, 1024),
                          pixel_depth=24,
                          show=False):
    #try to render using a temporary window:
    draw_result = {}
    window = None
    try:
        x, y = -100, -100
        if show:
            x, y = 100, 100
        w, h = 250, 250
        from xpra.codecs.loader import load_codec
        load_codec("dec_pillow")
        from xpra.client.window_border import WindowBorder
        border = WindowBorder()
        default_cursor_data = None
        noclient = FakeClient()
        #test with alpha, but not on win32
        #because we can't do alpha on win32 with opengl
        metadata = typedict({b"has-alpha": not WIN32})

        class NoHeaderGLClientWindow(gl_client_window_class):
            def add_header_bar(self):
                pass

            def schedule_recheck_focus(self):
                pass

        window = NoHeaderGLClientWindow(noclient, None, None, 2**32 - 1, x, y,
                                        w, h, w, h, metadata, False,
                                        typedict({}), border, max_window_size,
                                        default_cursor_data, pixel_depth)
        window_backing = window._backing
        window_backing.idle_add = no_idle_add
        window_backing.timeout_add = no_timeout_add
        window_backing.source_remove = no_source_remove
        window.realize()
        window_backing.paint_screen = True
        pixel_format = "BGRX"
        bpp = len(pixel_format)
        options = typedict({"pixel_format": pixel_format})
        stride = bpp * w
        coding = "rgb32"
        widget = window_backing._backing
        widget.realize()

        def paint_callback(success, message=""):
            log("paint_callback(%s, %s)", success, message)
            draw_result["success"] = success
            if message:
                draw_result["message"] = message.replace("\n", " ")

        log("OpenGL: testing draw on %s widget %s with %s : %s", window,
            widget, coding, pixel_format)
        pix = AtomicInteger(0x7f)
        REPAINT_DELAY = envint("XPRA_REPAINT_DELAY", int(show) * 16)
        gl_icon = get_icon_filename("opengl", ext="png")
        icon_data = None
        if os.path.exists(gl_icon):
            from PIL import Image
            img = Image.open(gl_icon)
            img.load()
            icon_w, icon_h = img.size
            icon_stride = icon_w * 4
            noalpha = Image.new("RGB", img.size, (255, 255, 255))
            noalpha.paste(img, mask=img.split()[3])  # 3 is the alpha channel
            buf = BytesIO()
            noalpha.save(buf, format="JPEG")
            icon_data = buf.getvalue()
            buf.close()
            icon_format = "jpeg"
        if not icon_data:
            icon_w = 32
            icon_h = 32
            icon_stride = icon_w * 4
            icon_data = bytes([0]) * icon_stride * icon_h
            icon_format = "rgb32"

        def draw():
            v = pix.increase()
            img_data = bytes([v % 256] * stride * h)
            options["flush"] = 1
            window.draw_region(0, 0, w, h, coding, img_data, stride, v,
                               options, [paint_callback])
            options["flush"] = 0
            mx = w // 2 - icon_w // 2
            my = h // 2 - icon_h // 2
            x = iround(mx * (1 + sin(v / 100)))
            y = iround(my * (1 + cos(v / 100)))
            window.draw_region(x, y, icon_w, icon_h, icon_format, icon_data,
                               icon_stride, v, options, [paint_callback])
            return REPAINT_DELAY > 0

        #the paint code is actually synchronous here,
        #so we can check the present_fbo() result:
        if show:
            widget.show()
            window.show()
            from gi.repository import Gtk, GLib

            def window_close_event(*_args):
                Gtk.main_quit()

            noclient.window_close_event = window_close_event
            GLib.timeout_add(REPAINT_DELAY, draw)
            Gtk.main()
        else:
            draw()
        if window_backing.last_present_fbo_error:
            return {
                "success":
                False,
                "message":
                "failed to present FBO on screen: %s" %
                window_backing.last_present_fbo_error
            }
    finally:
        if window:
            window.destroy()
    log("test_gl_client_window(..) draw_result=%s", draw_result)
    return draw_result
Exemple #8
0
 def __init__(self):
     self.main_queue = Queue()
     self.exit = False
     self.timer_id = AtomicInteger()
     self.timers = {}
     self.timer_lock = RLock()
Exemple #9
0
class QueueScheduler(object):
    def __init__(self):
        self.main_queue = Queue()
        self.exit = False
        self.timer_id = AtomicInteger()
        self.timers = {}
        self.timer_lock = RLock()

    def source_remove(self, tid):
        log("source_remove(%i)", tid)
        with self.timer_lock:
            try:
                timer = self.timers[tid]
                if timer is not None:
                    del self.timers[tid]
                if timer:
                    timer.cancel()
            except KeyError:
                pass

    def idle_add(self, fn, *args, **kwargs):
        tid = self.timer_id.increase()
        self.main_queue.put(
            (self.idle_repeat_call, (tid, fn, args, kwargs), {}))
        #add an entry,
        #but use the value False to stop us from trying to call cancel()
        self.timers[tid] = False
        return tid

    def idle_repeat_call(self, tid, fn, args, kwargs):
        if tid not in self.timers:
            return False  #cancelled
        return fn(*args, **kwargs)

    def timeout_add(self, timeout, fn, *args, **kwargs):
        tid = self.timer_id.increase()
        self.do_timeout_add(tid, timeout, fn, *args, **kwargs)
        return tid

    def do_timeout_add(self, tid, timeout, fn, *args, **kwargs):
        #emulate glib's timeout_add using Timers
        args = (tid, timeout, fn, args, kwargs)
        t = Timer(timeout / 1000.0, self.queue_timeout_function, args)
        self.timers[tid] = t
        t.start()

    def queue_timeout_function(self, tid, timeout, fn, fn_args, fn_kwargs):
        if tid not in self.timers:
            return  #cancelled
        #add to run queue:
        mqargs = [tid, timeout, fn, fn_args, fn_kwargs]
        self.main_queue.put((self.timeout_repeat_call, mqargs, {}))

    def timeout_repeat_call(self, tid, timeout, fn, fn_args, fn_kwargs):
        #executes the function then re-schedules it (if it returns True)
        if tid not in self.timers:
            return False  #cancelled
        v = fn(*fn_args, **fn_kwargs)
        if bool(v):
            #create a new timer with the same tid:
            with self.timer_lock:
                if tid in self.timers:
                    self.do_timeout_add(tid, timeout, fn, *fn_args,
                                        **fn_kwargs)
        else:
            try:
                del self.timers[tid]
            except KeyError:
                pass
        #we do the scheduling via timers, so always return False here
        #so that the main queue won't re-schedule this function call itself:
        return False

    def run(self):
        log("run() queue has %s items already in it", self.main_queue.qsize())
        #process "idle_add"/"timeout_add" events in the main loop:
        while not self.exit:
            log("run() size=%s", self.main_queue.qsize())
            v = self.main_queue.get()
            if v is None:
                log("run() None exit marker")
                break
            fn, args, kwargs = v
            log("run() %s%s%s", fn, args, kwargs)
            try:
                r = fn(*args, **kwargs)
                if bool(r):
                    #re-run it
                    self.main_queue.put(v)
            except Exception:
                log.error("error during main loop callback %s",
                          fn,
                          exc_info=True)
        self.exit = True

    def stop(self):
        self.exit = True
        self.stop_main_queue()

    def stop_main_queue(self):
        self.main_queue.put(None)
        #empty the main queue:
        q = Queue()
        q.put(None)
        self.main_queue = q
Exemple #10
0
def test_gl_client_window(gl_client_window_class, max_window_size=(1024, 1024), pixel_depth=24, show=False):
    #try to render using a temporary window:
    draw_result = {}
    window = None
    try:
        x, y = -100, -100
        if show:
            x, y = 100, 100
        w, h = 250, 250
        from xpra.client.window_border import WindowBorder
        border = WindowBorder()
        default_cursor_data = None
        noclient = FakeClient()
        #test with alpha, but not on win32
        #because we can't do alpha on win32 with opengl
        metadata = typedict({b"has-alpha" : not WIN32})
        window = gl_client_window_class(noclient, None, None, 2**32-1, x, y, w, h, w, h,
                                        metadata, False, typedict({}),
                                        border, max_window_size, default_cursor_data, pixel_depth)
        window_backing = window._backing
        window_backing.idle_add = no_idle_add
        window_backing.timeout_add = no_timeout_add
        window_backing.source_remove = no_source_remove
        window.realize()
        window_backing.paint_screen = True
        pixel_format = "BGRX"
        bpp = len(pixel_format)
        options = typedict({"pixel_format" : pixel_format})
        stride = bpp*w
        coding = "rgb32"
        widget = window_backing._backing
        widget.realize()
        def paint_callback(success, message):
            log("paint_callback(%s, %s)", success, message)
            draw_result.update({
                "success"   : success,
                "message"   : message,
                })
        log("OpenGL: testing draw on %s widget %s with %s : %s", window, widget, coding, pixel_format)
        pix = AtomicInteger(0x7f)
        REPAINT_DELAY = envint("XPRA_REPAINT_DELAY", 0)
        def draw():
            if PYTHON3:
                img_data = bytes([pix.increase() % 256]*stride*h)
            else:
                img_data = chr(pix.increase() % 256)*stride*h
            window.draw_region(0, 0, w, h, coding, img_data, stride, 1, options, [paint_callback])
            return REPAINT_DELAY>0
        #the paint code is actually synchronous here,
        #so we can check the present_fbo() result:
        if show:
            widget.show()
            window.show()
            from xpra.gtk_common.gobject_compat import import_gtk, import_glib
            gtk = import_gtk()
            glib = import_glib()
            def window_close_event(*_args):
                gtk.main_quit()
            noclient.window_close_event = window_close_event
            glib.timeout_add(REPAINT_DELAY, draw)
            gtk.main()
        else:
            draw()
        if window_backing.last_present_fbo_error:
            return {
                "success" : False,
                "message" : "failed to present FBO on screen: %s" % window_backing.last_present_fbo_error
                }
    finally:
        if window:
            window.destroy()
    log("test_gl_client_window(..) draw_result=%s", draw_result)
    return draw_result
Exemple #11
0
class SoundPipeline(GObject.GObject):

    generation = AtomicInteger()

    __generic_signals__ = {
        "state-changed": one_arg_signal,
        "error": one_arg_signal,
        "new-stream": one_arg_signal,
        "info": one_arg_signal,
    }

    def __init__(self, codec):
        GObject.GObject.__init__(self)
        self.stream_compressor = None
        self.codec = codec
        self.codec_description = ""
        self.codec_mode = ""
        self.container_format = ""
        self.container_description = ""
        self.bus = None
        self.bus_message_handler_id = None
        self.bitrate = -1
        self.pipeline = None
        self.pipeline_str = ""
        self.start_time = 0
        self.state = "stopped"
        self.buffer_count = 0
        self.byte_count = 0
        self.emit_info_timer = None
        self.info = {
            "codec": self.codec,
            "state": self.state,
        }
        self.idle_add = GLib.idle_add
        self.timeout_add = GLib.timeout_add
        self.source_remove = GLib.source_remove
        self.file = None

    def init_file(self, codec):
        gen = self.generation.increase()
        log("init_file(%s) generation=%s, SAVE_AUDIO=%s", codec, gen,
            SAVE_AUDIO)
        if SAVE_AUDIO is not None:
            parts = codec.split("+")
            if len(parts) > 1:
                filename = SAVE_AUDIO + str(
                    gen) + "-" + parts[0] + ".%s" % parts[1]
            else:
                filename = SAVE_AUDIO + str(gen) + ".%s" % codec
            self.file = open(filename, 'wb')
            log.info("saving %s stream to %s", codec, filename)

    def save_to_file(self, *buffers):
        f = self.file
        if f and buffers:
            for x in buffers:
                self.file.write(x)
            self.file.flush()

    def idle_emit(self, sig, *args):
        self.idle_add(self.emit, sig, *args)

    def emit_info(self):
        if self.emit_info_timer:
            return

        def do_emit_info():
            self.emit_info_timer = None
            if self.pipeline:
                info = self.get_info()
                #reset info:
                self.info = {}
                self.emit("info", info)

        self.emit_info_timer = self.timeout_add(200, do_emit_info)

    def cancel_emit_info_timer(self):
        eit = self.emit_info_timer
        if eit:
            self.emit_info_timer = None
            self.source_remove(eit)

    def get_info(self) -> dict:
        info = self.info.copy()
        if inject_fault():
            info["INJECTING_NONE_FAULT"] = None
            log.warn("injecting None fault: get_info()=%s", info)
        return info

    def setup_pipeline_and_bus(self, elements):
        gstlog("pipeline elements=%s", elements)
        self.pipeline_str = " ! ".join([x for x in elements if x is not None])
        gstlog("pipeline=%s", self.pipeline_str)
        self.start_time = monotonic_time()
        try:
            self.pipeline = gst.parse_launch(self.pipeline_str)
        except Exception as e:
            self.pipeline = None
            gstlog.error("Error setting up the sound pipeline:")
            gstlog.error(" %s", e)
            gstlog.error(" GStreamer pipeline for %s:", self.codec)
            for i, x in enumerate(elements):
                gstlog.error("  %s%s", x,
                             ["", " ! \\"][int(i < (len(elements) - 1))])
            self.cleanup()
            return False
        self.bus = self.pipeline.get_bus()
        self.bus_message_handler_id = self.bus.connect("message",
                                                       self.on_message)
        self.bus.add_signal_watch()
        self.info["pipeline"] = self.pipeline_str
        return True

    def do_get_state(self, state):
        if not self.pipeline:
            return "stopped"
        return {
            gst.State.PLAYING: "active",
            gst.State.PAUSED: "paused",
            gst.State.NULL: "stopped",
            gst.State.READY: "ready"
        }.get(state, "unknown")

    def get_state(self):
        return self.state

    def update_bitrate(self, new_bitrate):
        if new_bitrate == self.bitrate:
            return
        self.bitrate = new_bitrate
        log("new bitrate: %s", self.bitrate)
        self.info["bitrate"] = new_bitrate

    def update_state(self, state):
        log("update_state(%s)", state)
        self.state = state
        self.info["state"] = state

    def inc_buffer_count(self, inc=1):
        self.buffer_count += inc
        self.info["buffer_count"] = self.buffer_count

    def inc_byte_count(self, count):
        self.byte_count += count
        self.info["bytes"] = self.byte_count

    def set_volume(self, volume=100):
        if self.volume:
            self.volume.set_property("volume", volume / 100.0)
            self.info["volume"] = volume

    def get_volume(self):
        if self.volume:
            return int(self.volume.get_property("volume") * 100)
        return GST_FLOW_OK

    def start(self):
        if not self.pipeline:
            log.error("cannot start")
            return
        register_SIGUSR_signals(self.idle_add)
        log("SoundPipeline.start() codec=%s", self.codec)
        self.idle_emit("new-stream", self.codec)
        self.update_state("active")
        self.pipeline.set_state(gst.State.PLAYING)
        if self.stream_compressor:
            self.info["stream-compressor"] = self.stream_compressor
        self.emit_info()
        #we may never get the stream start, synthesize codec event so we get logging:
        parts = self.codec.split("+")
        self.timeout_add(1000, self.new_codec_description, parts[0])
        if len(parts) > 1 and parts[1] != self.stream_compressor:
            self.timeout_add(1000, self.new_container_description, parts[1])
        elif self.container_format:
            self.timeout_add(1000, self.new_container_description,
                             self.container_format)
        if self.stream_compressor:

            def logsc():
                self.gstloginfo("using stream compression %s",
                                self.stream_compressor)

            self.timeout_add(1000, logsc)
        log("SoundPipeline.start() done")

    def stop(self):
        p = self.pipeline
        self.pipeline = None
        if not p:
            return
        log("SoundPipeline.stop() state=%s", self.state)
        #uncomment this to see why we end up calling stop()
        #import traceback
        #for x in traceback.format_stack():
        #    for s in x.split("\n"):
        #        v = s.replace("\r", "").replace("\n", "")
        #        if v:
        #            log(v)
        if self.state not in ("starting", "stopped", "ready", None):
            log.info("stopping")
        self.update_state("stopped")
        p.set_state(gst.State.NULL)
        log("SoundPipeline.stop() done")

    def cleanup(self):
        log("SoundPipeline.cleanup()")
        self.cancel_emit_info_timer()
        self.stop()
        b = self.bus
        self.bus = None
        log("SoundPipeline.cleanup() bus=%s", b)
        if not b:
            return
        b.remove_signal_watch()
        bmhid = self.bus_message_handler_id
        log("SoundPipeline.cleanup() bus_message_handler_id=%s", bmhid)
        if bmhid:
            self.bus_message_handler_id = None
            b.disconnect(bmhid)
        self.pipeline = None
        self.codec = None
        self.bitrate = -1
        self.state = None
        self.volume = None
        self.info = {}
        f = self.file
        if f:
            self.file = None
            noerr(f.close)
        log("SoundPipeline.cleanup() done")

    def gstloginfo(self, msg, *args):
        if self.state != "stopped":
            gstlog.info(msg, *args)
        else:
            gstlog(msg, *args)

    def gstlogwarn(self, msg, *args):
        if self.state != "stopped":
            gstlog.warn(msg, *args)
        else:
            gstlog(msg, *args)

    def new_codec_description(self, desc):
        log("new_codec_description(%s) current codec description=%s", desc,
            self.codec_description)
        if not desc:
            return
        dl = desc.lower()
        if dl == "wav" and self.codec_description:
            return
        cdl = self.codec_description.lower()
        if not cdl or (cdl != dl and dl.find(cdl) < 0 and cdl.find(dl) < 0):
            self.gstloginfo("using '%s' audio codec", dl)
        self.codec_description = dl
        self.info["codec_description"] = dl

    def new_container_description(self, desc):
        log("new_container_description(%s) current container description=%s",
            desc, self.container_description)
        if not desc:
            return
        cdl = self.container_description.lower()
        dl = {
            "mka": "matroska",
            "mpeg4": "iso fmp4",
        }.get(desc.lower(), desc.lower())
        if not cdl or (cdl != dl and dl.find(cdl) < 0 and cdl.find(dl) < 0):
            self.gstloginfo("using '%s' container format", dl)
        self.container_description = dl
        self.info["container_description"] = dl

    def on_message(self, _bus, message):
        #log("on_message(%s, %s)", bus, message)
        gstlog("on_message: %s", message)
        t = message.type
        if t == gst.MessageType.EOS:
            self.pipeline.set_state(gst.State.NULL)
            self.gstloginfo("EOS")
            self.update_state("stopped")
            self.idle_emit("state-changed", self.state)
        elif t == gst.MessageType.ERROR:
            self.pipeline.set_state(gst.State.NULL)
            err, details = message.parse_error()
            gstlog.error("Gstreamer pipeline error: %s", err.message)
            for l in err.args:
                if l != err.message:
                    gstlog(" %s", l)
            try:
                #prettify (especially on win32):
                p = details.find("\\Source\\")
                if p > 0:
                    details = details[p + len("\\Source\\"):]
                for d in details.split(": "):
                    for dl in d.splitlines():
                        if dl.strip():
                            gstlog.error(" %s", dl.strip())
            except Exception:
                gstlog.error(" %s", details)
            self.update_state("error")
            self.idle_emit("error", str(err))
            #exit
            self.cleanup()
        elif t == gst.MessageType.TAG:
            try:
                self.parse_message(message)
            except Exception as e:
                self.gstlogwarn("Warning: failed to parse gstreamer message:")
                self.gstlogwarn(" %s: %s", type(e), e)
        elif t == gst.MessageType.ELEMENT:
            try:
                self.parse_element_message(message)
            except Exception as e:
                self.gstlogwarn(
                    "Warning: failed to parse gstreamer element message:")
                self.gstlogwarn(" %s: %s", type(e), e)
        elif t == gst.MessageType.STREAM_STATUS:
            gstlog("stream status: %s", message)
        elif t == gst.MessageType.STREAM_START:
            log("stream start: %s", message)
            #with gstreamer 1.x, we don't always get the "audio-codec" message..
            #so print the codec from here instead (and assume gstreamer is using what we told it to)
            #after a delay, just in case we do get the real "audio-codec" message!
            self.timeout_add(500, self.new_codec_description,
                             self.codec.split("+")[0])
        elif t in (gst.MessageType.ASYNC_DONE, gst.MessageType.NEW_CLOCK):
            gstlog("%s", message)
        elif t == gst.MessageType.STATE_CHANGED:
            _, new_state, _ = message.parse_state_changed()
            gstlog("state-changed on %s: %s", message.src,
                   gst.Element.state_get_name(new_state))
            state = self.do_get_state(new_state)
            if isinstance(message.src, gst.Pipeline):
                self.update_state(state)
                self.idle_emit("state-changed", state)
        elif t == gst.MessageType.DURATION_CHANGED:
            gstlog("duration changed: %s", message)
        elif t == gst.MessageType.LATENCY:
            gstlog("latency message from %s: %s", message.src, message)
        elif t == gst.MessageType.INFO:
            self.gstloginfo("pipeline message: %s", message)
        elif t == gst.MessageType.WARNING:
            w = message.parse_warning()
            self.gstlogwarn("pipeline warning: %s", w[0].message)
            for x in w[1:]:
                for l in x.split(":"):
                    if l:
                        if l.startswith("\n"):
                            l = l.strip("\n") + " "
                            for lp in l.split(". "):
                                lp = lp.strip()
                                if lp:
                                    self.gstlogwarn(" %s", lp)
                        else:
                            self.gstlogwarn("                  %s",
                                            l.strip("\n\r"))
        else:
            self.gstlogwarn("unhandled bus message type %s: %s", t, message)
        self.emit_info()
        return GST_FLOW_OK

    def parse_element_message(self, message):
        structure = message.get_structure()
        props = {
            "seqnum": int(message.seqnum),
        }
        for i in range(structure.n_fields()):
            name = structure.nth_field_name(i)
            props[name] = structure.get_value(name)
        self.do_parse_element_message(message, message.src.get_name(), props)

    def do_parse_element_message(self, message, name, props=None):
        gstlog("do_parse_element_message%s", (message, name, props))

    def parse_message(self, message):
        #message parsing code for GStreamer 1.x
        taglist = message.parse_tag()
        tags = [taglist.nth_tag_name(x) for x in range(taglist.n_tags())]
        gstlog("bus message with tags=%s", tags)
        if not tags:
            #ignore it
            return
        if "bitrate" in tags:
            new_bitrate = taglist.get_uint("bitrate")
            if new_bitrate[0] is True:
                self.update_bitrate(new_bitrate[1])
                gstlog("bitrate: %s", new_bitrate[1])
        if "codec" in tags:
            desc = taglist.get_string("codec")
            if desc[0] is True:
                self.new_codec_description(desc[1])
        if "audio-codec" in tags:
            desc = taglist.get_string("audio-codec")
            if desc[0] is True:
                self.new_codec_description(desc[1])
                gstlog("audio-codec: %s", desc[1])
        if "mode" in tags:
            mode = taglist.get_string("mode")
            if mode[0] is True and self.codec_mode != mode[1]:
                gstlog("mode: %s", mode[1])
                self.codec_mode = mode[1]
                self.info["codec_mode"] = self.codec_mode
        if "container-format" in tags:
            cf = taglist.get_string("container-format")
            if cf[0] is True:
                self.new_container_description(cf[1])
        for x in ("encoder", "description", "language-code"):
            if x in tags:
                desc = taglist.get_string(x)
                gstlog("%s: %s", x, desc[1])
        if not set(tags).intersection(KNOWN_TAGS):
            structure = message.get_structure()
            self.gstloginfo("unknown sound pipeline tag message: %s, tags=%s",
                            structure.to_string(), tags)
class ProxyInstanceProcess(Process):
    def __init__(self, uid, gid, env_options, session_options, socket_dir,
                 video_encoder_modules, csc_modules, client_conn, client_state,
                 cipher, encryption_key, server_conn, caps, message_queue):
        Process.__init__(self, name=str(client_conn))
        self.uid = uid
        self.gid = gid
        self.env_options = env_options
        self.session_options = session_options
        self.socket_dir = socket_dir
        self.video_encoder_modules = video_encoder_modules
        self.csc_modules = csc_modules
        self.client_conn = client_conn
        self.client_state = client_state
        self.cipher = cipher
        self.encryption_key = encryption_key
        self.server_conn = server_conn
        self.caps = caps
        log("ProxyProcess%s",
            (uid, gid, env_options, session_options, socket_dir,
             video_encoder_modules, csc_modules, client_conn,
             repr_ellipsized(str(client_state)), cipher, encryption_key,
             server_conn, "%s: %s.." %
             (type(caps), repr_ellipsized(str(caps))), message_queue))
        self.client_protocol = None
        self.server_protocol = None
        self.exit = False
        self.main_queue = None
        self.message_queue = message_queue
        self.encode_queue = None  #holds draw packets to encode
        self.encode_thread = None
        self.video_encoding_defs = None
        self.video_encoders = None
        self.video_encoders_last_used_time = None
        self.video_encoder_types = None
        self.video_helper = None
        self.lost_windows = None
        #for handling the local unix domain socket:
        self.control_socket_cleanup = None
        self.control_socket = None
        self.control_socket_thread = None
        self.control_socket_path = None
        self.potential_protocols = []
        self.max_connections = MAX_CONCURRENT_CONNECTIONS
        self.timer_id = AtomicInteger()
        self.timers = {}
        self.timer_lock = RLock()

    def server_message_queue(self):
        while True:
            log("waiting for server message on %s", self.message_queue)
            m = self.message_queue.get()
            log("received proxy server message: %s", m)
            if m == "stop":
                self.stop("proxy server request")
                return
            elif m == "socket-handover-complete":
                log("setting sockets to blocking mode: %s",
                    (self.client_conn, self.server_conn))
                #set sockets to blocking mode:
                set_blocking(self.client_conn)
                set_blocking(self.server_conn)
            else:
                log.error("unexpected proxy server message: %s", m)

    def signal_quit(self, signum, _frame):
        log.info("")
        log.info("proxy process pid %s got signal %s, exiting", os.getpid(),
                 SIGNAMES.get(signum, signum))
        self.exit = True
        signal.signal(signal.SIGINT, deadly_signal)
        signal.signal(signal.SIGTERM, deadly_signal)
        self.stop(SIGNAMES.get(signum, signum))

    def source_remove(self, tid):
        log("source_remove(%i)", tid)
        with self.timer_lock:
            try:
                timer = self.timers[tid]
                if timer is not None:
                    del self.timers[tid]
                if timer:
                    timer.cancel()
            except:
                pass

    def idle_add(self, fn, *args, **kwargs):
        tid = self.timer_id.increase()
        self.main_queue.put(
            (self.idle_repeat_call, (tid, fn, args, kwargs), {}))
        #add an entry,
        #but use the value False to stop us from trying to call cancel()
        self.timers[tid] = False
        return tid

    def idle_repeat_call(self, tid, fn, args, kwargs):
        if tid not in self.timers:
            return False  #cancelled
        return fn(*args, **kwargs)

    def timeout_add(self, timeout, fn, *args, **kwargs):
        tid = self.timer_id.increase()
        self.do_timeout_add(tid, timeout, fn, *args, **kwargs)
        return tid

    def do_timeout_add(self, tid, timeout, fn, *args, **kwargs):
        #emulate glib's timeout_add using Timers
        args = (tid, timeout, fn, args, kwargs)
        t = Timer(timeout / 1000.0, self.queue_timeout_function, args)
        self.timers[tid] = t
        t.start()

    def queue_timeout_function(self, tid, timeout, fn, fn_args, fn_kwargs):
        if tid not in self.timers:
            return  #cancelled
        #add to run queue:
        mqargs = [tid, timeout, fn, fn_args, fn_kwargs]
        self.main_queue.put((self.timeout_repeat_call, mqargs, {}))

    def timeout_repeat_call(self, tid, timeout, fn, fn_args, fn_kwargs,
                            **kwargs):
        #executes the function then re-schedules it (if it returns True)
        if tid not in self.timers:
            return  #cancelled
        v = fn(*fn_args, **fn_kwargs)
        if bool(v):
            #create a new timer with the same tid:
            with self.timer_lock:
                if tid in self.timers:
                    self.do_timeout_add(tid, timeout, fn, *fn_args,
                                        **fn_kwargs)
        else:
            try:
                del self.timers[tid]
            except:
                pass
        #we do the scheduling via timers, so always return False here
        #so that the main queue won't re-schedule this function call itself:
        return False

    def setproctitle(self, title):
        try:
            import setproctitle
            setproctitle.setproctitle(title)
        except ImportError as e:
            log("setproctitle not installed: %s", e)

    def run(self):
        log("ProxyProcess.run() pid=%s, uid=%s, gid=%s", os.getpid(), getuid(),
            getgid())
        self.setproctitle("Xpra Proxy Instance for %s" % self.server_conn)
        setuidgid(self.uid, self.gid)
        if self.env_options:
            #TODO: whitelist env update?
            os.environ.update(self.env_options)
        self.video_init()

        log.info("new proxy instance started")
        log.info(" for client %s", self.client_conn)
        log.info(" and server %s", self.server_conn)

        signal.signal(signal.SIGTERM, self.signal_quit)
        signal.signal(signal.SIGINT, self.signal_quit)
        log("registered signal handler %s", self.signal_quit)

        start_thread(self.server_message_queue, "server message queue")

        if not self.create_control_socket():
            #TODO: should send a message to the client
            return
        self.control_socket_thread = start_thread(self.control_socket_loop,
                                                  "control")

        self.main_queue = Queue()
        #setup protocol wrappers:
        self.server_packets = Queue(PROXY_QUEUE_SIZE)
        self.client_packets = Queue(PROXY_QUEUE_SIZE)
        self.client_protocol = Protocol(self, self.client_conn,
                                        self.process_client_packet,
                                        self.get_client_packet)
        self.client_protocol.restore_state(self.client_state)
        self.server_protocol = Protocol(self, self.server_conn,
                                        self.process_server_packet,
                                        self.get_server_packet)
        #server connection tweaks:
        self.server_protocol.large_packets.append("input-devices")
        self.server_protocol.large_packets.append("draw")
        self.server_protocol.large_packets.append("window-icon")
        self.server_protocol.large_packets.append("keymap-changed")
        self.server_protocol.large_packets.append("server-settings")
        if self.caps.boolget("file-transfer"):
            self.client_protocol.large_packets.append("send-file")
            self.client_protocol.large_packets.append("send-file-chunk")
            self.server_protocol.large_packets.append("send-file")
            self.server_protocol.large_packets.append("send-file-chunk")
        self.server_protocol.set_compression_level(
            self.session_options.get("compression_level", 0))
        self.server_protocol.enable_default_encoder()

        self.lost_windows = set()
        self.encode_queue = Queue()
        self.encode_thread = start_thread(self.encode_loop, "encode")

        log("starting network threads")
        self.server_protocol.start()
        self.client_protocol.start()

        self.send_hello()
        self.timeout_add(VIDEO_TIMEOUT * 1000, self.timeout_video_encoders)

        try:
            self.run_queue()
        except KeyboardInterrupt as e:
            self.stop(str(e))
        finally:
            log("ProxyProcess.run() ending %s", os.getpid())

    def video_init(self):
        enclog("video_init() loading codecs")
        load_codecs(decoders=False)
        enclog("video_init() will try video encoders: %s",
               csv(self.video_encoder_modules) or "none")
        self.video_helper = getVideoHelper()
        #only use video encoders (no CSC supported in proxy)
        self.video_helper.set_modules(
            video_encoders=self.video_encoder_modules)
        self.video_helper.init()

        self.video_encoding_defs = {}
        self.video_encoders = {}
        self.video_encoders_dst_formats = []
        self.video_encoders_last_used_time = {}
        self.video_encoder_types = []

        #figure out which encoders we want to proxy for (if any):
        encoder_types = set()
        for encoding in self.video_helper.get_encodings():
            colorspace_specs = self.video_helper.get_encoder_specs(encoding)
            for colorspace, especs in colorspace_specs.items():
                if colorspace not in ("BGRX", "BGRA", "RGBX", "RGBA"):
                    #only deal with encoders that can handle plain RGB directly
                    continue

                for spec in especs:  #ie: video_spec("x264")
                    spec_props = spec.to_dict()
                    del spec_props["codec_class"]  #not serializable!
                    spec_props[
                        "score_boost"] = 50  #we want to win scoring so we get used ahead of other encoders
                    spec_props[
                        "max_instances"] = 3  #limit to 3 video streams we proxy for (we really want 2,
                    # but because of races with garbage collection, we need to allow more)
                    #store it in encoding defs:
                    self.video_encoding_defs.setdefault(
                        encoding, {}).setdefault(colorspace,
                                                 []).append(spec_props)
                    encoder_types.add(spec.codec_type)

        enclog("encoder types found: %s", tuple(encoder_types))
        #remove duplicates and use preferred order:
        order = PREFERRED_ENCODER_ORDER[:]
        for x in tuple(encoder_types):
            if x not in order:
                order.append(x)
        self.video_encoder_types = [x for x in order if x in encoder_types]
        enclog.info("proxy video encoders: %s",
                    ", ".join(self.video_encoder_types or [
                        "none",
                    ]))

    def create_control_socket(self):
        assert self.socket_dir
        username = get_username_for_uid(self.uid)
        dotxpra = DotXpra(self.socket_dir,
                          actual_username=username,
                          uid=self.uid,
                          gid=self.gid)
        sockname = ":proxy-%s" % os.getpid()
        sockpath = dotxpra.socket_path(sockname)
        log("%s.socket_path(%s)=%s", dotxpra, sockname, sockpath)
        state = dotxpra.get_server_state(sockpath)
        log(
            "create_control_socket: socket path='%s', uid=%i, gid=%i, state=%s",
            sockpath, getuid(), getgid(), state)
        if state in (DotXpra.LIVE, DotXpra.UNKNOWN, DotXpra.INACCESSIBLE):
            log.error("Error: you already have a proxy server running at '%s'",
                      sockpath)
            log.error(" the control socket will not be created")
            return False
        d = os.path.dirname(sockpath)
        try:
            dotxpra.mksockdir(d)
        except Exception as e:
            log.warn("Warning: failed to create socket directory '%s'", d)
            log.warn(" %s", e)
        try:
            sock, self.control_socket_cleanup = create_unix_domain_socket(
                sockpath, None, 0o600)
            sock.listen(5)
        except Exception as e:
            log("create_unix_domain_socket failed for '%s'",
                sockpath,
                exc_info=True)
            log.error("Error: failed to setup control socket '%s':", sockpath)
            log.error(" %s", e)
            return False
        self.control_socket = sock
        self.control_socket_path = sockpath
        log.info("proxy instance now also available using unix domain socket:")
        log.info(" %s", self.control_socket_path)
        return True

    def control_socket_loop(self):
        while not self.exit:
            log("waiting for connection on %s", self.control_socket_path)
            sock, address = self.control_socket.accept()
            self.new_control_connection(sock, address)

    def new_control_connection(self, sock, address):
        if len(self.potential_protocols) >= self.max_connections:
            log.error("too many connections (%s), ignoring new one",
                      len(self.potential_protocols))
            sock.close()
            return True
        try:
            peername = sock.getpeername()
        except:
            peername = str(address)
        sockname = sock.getsockname()
        target = peername or sockname
        #sock.settimeout(0)
        log(
            "new_control_connection() sock=%s, sockname=%s, address=%s, peername=%s",
            sock, sockname, address, peername)
        sc = SocketConnection(sock, sockname, address, target, "unix-domain")
        log.info("New proxy instance control connection received: %s", sc)
        protocol = Protocol(self, sc, self.process_control_packet)
        protocol.large_packets.append("info-response")
        self.potential_protocols.append(protocol)
        protocol.enable_default_encoder()
        protocol.start()
        self.timeout_add(SOCKET_TIMEOUT * 1000,
                         self.verify_connection_accepted, protocol)
        return True

    def verify_connection_accepted(self, protocol):
        if not protocol._closed and protocol in self.potential_protocols:
            log.error("connection timedout: %s", protocol)
            self.send_disconnect(protocol, LOGIN_TIMEOUT)

    def process_control_packet(self, proto, packet):
        try:
            self.do_process_control_packet(proto, packet)
        except Exception as e:
            log.error("error processing control packet", exc_info=True)
            self.send_disconnect(proto, CONTROL_COMMAND_ERROR, str(e))

    def do_process_control_packet(self, proto, packet):
        log("process_control_packet(%s, %s)", proto, packet)
        packet_type = packet[0]
        if packet_type == Protocol.CONNECTION_LOST:
            log.info("Connection lost")
            if proto in self.potential_protocols:
                self.potential_protocols.remove(proto)
            return
        if packet_type == "hello":
            caps = typedict(packet[1])
            if caps.boolget("challenge"):
                self.send_disconnect(
                    proto, AUTHENTICATION_ERROR,
                    "this socket does not use authentication")
                return
            generic_request = caps.strget("request")

            def is_req(mode):
                return generic_request == mode or caps.boolget(
                    "%s_request" % mode)

            if is_req("info"):
                proto.send_now(("hello", self.get_proxy_info(proto)))
                self.timeout_add(5 * 1000, self.send_disconnect, proto,
                                 CLIENT_EXIT_TIMEOUT, "info sent")
                return
            elif is_req("stop"):
                self.stop("socket request", None)
                return
            elif is_req("version"):
                version = XPRA_VERSION
                if caps.boolget("full-version-request"):
                    version = full_version_str()
                proto.send_now(("hello", {"version": version}))
                self.timeout_add(5 * 1000, self.send_disconnect, proto,
                                 CLIENT_EXIT_TIMEOUT, "version sent")
                return
        self.send_disconnect(
            proto, CONTROL_COMMAND_ERROR,
            "this socket only handles 'info', 'version' and 'stop' requests")

    def send_disconnect(self, proto, *reasons):
        log("send_disconnect(%s, %s)", proto, reasons)
        if proto._closed:
            return
        proto.send_disconnect(reasons)
        self.timeout_add(1000, self.force_disconnect, proto)

    def force_disconnect(self, proto):
        proto.close()

    def get_proxy_info(self, proto):
        sinfo = {}
        sinfo.update(get_server_info())
        sinfo.update(get_thread_info(proto))
        return {
            "proxy": {
                "version": XPRA_VERSION,
                "": sinfo,
            },
            "window": self.get_window_info(),
        }

    def send_hello(self, challenge_response=None, client_salt=None):
        hello = self.filter_client_caps(self.caps)
        if challenge_response:
            hello.update({
                "challenge_response": challenge_response,
                "challenge_client_salt": client_salt,
            })
        self.queue_server_packet(("hello", hello))

    def sanitize_session_options(self, options):
        d = {}

        def number(k, v):
            return parse_number(int, k, v)

        OPTION_WHITELIST = {
            "compression_level": number,
            "lz4": parse_bool,
            "lzo": parse_bool,
            "zlib": parse_bool,
            "rencode": parse_bool,
            "bencode": parse_bool,
            "yaml": parse_bool
        }
        for k, v in options.items():
            parser = OPTION_WHITELIST.get(k)
            if parser:
                log("trying to add %s=%s using %s", k, v, parser)
                try:
                    d[k] = parser(k, v)
                except Exception as e:
                    log.warn("failed to parse value %s for %s using %s: %s", v,
                             k, parser, e)
        return d

    def filter_client_caps(self, caps):
        fc = self.filter_caps(caps,
                              ("cipher", "challenge", "digest", "aliases",
                               "compression", "lz4", "lz0", "zlib"))
        #update with options provided via config if any:
        fc.update(self.sanitize_session_options(self.session_options))
        #add video proxies if any:
        fc["encoding.proxy.video"] = len(self.video_encoding_defs) > 0
        if self.video_encoding_defs:
            fc["encoding.proxy.video.encodings"] = self.video_encoding_defs
        return fc

    def filter_server_caps(self, caps):
        self.server_protocol.enable_encoder_from_caps(caps)
        return self.filter_caps(caps, ("aliases", ))

    def filter_caps(self, caps, prefixes):
        #removes caps that the proxy overrides / does not use:
        #(not very pythonic!)
        pcaps = {}
        removed = []
        for k in caps.keys():
            skip = len([e for e in prefixes if k.startswith(e)])
            if skip == 0:
                pcaps[k] = caps[k]
            else:
                removed.append(k)
        log("filtered out %s matching %s", removed, prefixes)
        #replace the network caps with the proxy's own:
        pcaps.update(flatten_dict(get_network_caps()))
        #then add the proxy info:
        updict(pcaps, "proxy", get_server_info(), flatten_dicts=True)
        pcaps["proxy"] = True
        pcaps["proxy.hostname"] = socket.gethostname()
        return pcaps

    def run_queue(self):
        log("run_queue() queue has %s items already in it",
            self.main_queue.qsize())
        #process "idle_add"/"timeout_add" events in the main loop:
        while not self.exit:
            log("run_queue() size=%s", self.main_queue.qsize())
            v = self.main_queue.get()
            if v is None:
                log("run_queue() None exit marker")
                break
            fn, args, kwargs = v
            log("run_queue() %s%s%s", fn, args, kwargs)
            try:
                v = fn(*args, **kwargs)
                if bool(v):
                    #re-run it
                    self.main_queue.put(v)
            except:
                log.error("error during main loop callback %s",
                          fn,
                          exc_info=True)
        self.exit = True
        #wait for connections to close down cleanly before we exit
        for i in range(10):
            if self.client_protocol._closed and self.server_protocol._closed:
                break
            if i == 0:
                log.info("waiting for network connections to close")
            else:
                log("still waiting %i/10 - client.closed=%s, server.closed=%s",
                    i + 1, self.client_protocol._closed,
                    self.server_protocol._closed)
            sleep(0.1)
        log.info("proxy instance %s stopped", os.getpid())

    def stop(self, reason="proxy terminating", skip_proto=None):
        log.info("stop(%s, %s)", reason, skip_proto)
        self.exit = True
        try:
            self.control_socket.close()
        except:
            pass
        csc = self.control_socket_cleanup
        if csc:
            self.control_socket_cleanup = None
            csc()
        self.main_queue.put(None)
        #empty the main queue:
        q = Queue()
        q.put(None)
        self.main_queue = q
        #empty the encode queue:
        q = Queue()
        q.put(None)
        self.encode_queue = q
        for proto in (self.client_protocol, self.server_protocol):
            if proto and proto != skip_proto:
                log("sending disconnect to %s", proto)
                proto.send_disconnect([SERVER_SHUTDOWN, reason])

    def queue_client_packet(self, packet):
        log("queueing client packet: %s", packet[0])
        self.client_packets.put(packet)
        self.client_protocol.source_has_more()

    def get_client_packet(self):
        #server wants a packet
        p = self.client_packets.get()
        s = self.client_packets.qsize()
        log("sending to client: %s (queue size=%i)", p[0], s)
        return p, None, None, None, True, s > 0

    def process_client_packet(self, proto, packet):
        packet_type = packet[0]
        log("process_client_packet: %s", packet_type)
        if packet_type == Protocol.CONNECTION_LOST:
            self.stop("client connection lost", proto)
            return
        elif packet_type == "disconnect":
            log("got disconnect from client: %s", packet[1])
            if self.exit:
                self.client_protocol.close()
            else:
                self.stop("disconnect from client: %s" % packet[1])
        elif packet_type == "set_deflate":
            #echo it back to the client:
            self.client_packets.put(packet)
            self.client_protocol.source_has_more()
            return
        elif packet_type == "hello":
            log.warn(
                "Warning: invalid hello packet received after initial authentication (dropped)"
            )
            return
        self.queue_server_packet(packet)

    def queue_server_packet(self, packet):
        log("queueing server packet: %s", packet[0])
        self.server_packets.put(packet)
        self.server_protocol.source_has_more()

    def get_server_packet(self):
        #server wants a packet
        p = self.server_packets.get()
        s = self.server_packets.qsize()
        log("sending to server: %s (queue size=%i)", p[0], s)
        return p, None, None, None, True, s > 0

    def _packet_recompress(self, packet, index, name):
        if len(packet) > index:
            data = packet[index]
            if len(data) < 512:
                packet[index] = str(data)
                return
            #FIXME: this is ugly and not generic!
            zlib = compression.use_zlib and self.caps.boolget("zlib", True)
            lz4 = compression.use_lz4 and self.caps.boolget("lz4", False)
            lzo = compression.use_lzo and self.caps.boolget("lzo", False)
            if zlib or lz4 or lzo:
                packet[index] = compressed_wrapper(name,
                                                   data,
                                                   zlib=zlib,
                                                   lz4=lz4,
                                                   lzo=lzo,
                                                   can_inline=False)
            else:
                #prevent warnings about large uncompressed data
                packet[index] = Compressed("raw %s" % name,
                                           data,
                                           can_inline=True)

    def process_server_packet(self, proto, packet):
        packet_type = packet[0]
        log("process_server_packet: %s", packet_type)
        if packet_type == Protocol.CONNECTION_LOST:
            self.stop("server connection lost", proto)
            return
        elif packet_type == "disconnect":
            log("got disconnect from server: %s", packet[1])
            if self.exit:
                self.server_protocol.close()
            else:
                self.stop("disconnect from server: %s" % packet[1])
        elif packet_type == "hello":
            c = typedict(packet[1])
            maxw, maxh = c.intpair("max_desktop_size", (4096, 4096))
            caps = self.filter_server_caps(c)
            #add new encryption caps:
            if self.cipher:
                from xpra.net.crypto import crypto_backend_init, new_cipher_caps, DEFAULT_PADDING
                crypto_backend_init()
                padding_options = self.caps.strlistget(
                    "cipher.padding.options", [DEFAULT_PADDING])
                auth_caps = new_cipher_caps(self.client_protocol, self.cipher,
                                            self.encryption_key,
                                            padding_options)
                caps.update(auth_caps)
            #may need to bump packet size:
            proto.max_packet_size = maxw * maxh * 4 * 4
            file_transfer = self.caps.boolget("file-transfer") and c.boolget(
                "file-transfer")
            file_size_limit = max(self.caps.intget("file-size-limit"),
                                  c.intget("file-size-limit"))
            file_max_packet_size = int(file_transfer) * (
                1024 + file_size_limit * 1024 * 1024)
            self.client_protocol.max_packet_size = max(
                self.client_protocol.max_packet_size, file_max_packet_size)
            self.server_protocol.max_packet_size = max(
                self.server_protocol.max_packet_size, file_max_packet_size)
            packet = ("hello", caps)
        elif packet_type == "info-response":
            #adds proxy info:
            #note: this is only seen by the client application
            #"xpra info" is a new connection, which talks to the proxy server...
            info = packet[1]
            info.update(self.get_proxy_info(proto))
        elif packet_type == "lost-window":
            wid = packet[1]
            #mark it as lost so we can drop any current/pending frames
            self.lost_windows.add(wid)
            #queue it so it gets cleaned safely (for video encoders mostly):
            self.encode_queue.put(packet)
            #and fall through so tell the client immediately
        elif packet_type == "draw":
            #use encoder thread:
            self.encode_queue.put(packet)
            #which will queue the packet itself when done:
            return
        #we do want to reformat cursor packets...
        #as they will have been uncompressed by the network layer already:
        elif packet_type == "cursor":
            #packet = ["cursor", x, y, width, height, xhot, yhot, serial, pixels, name]
            #or:
            #packet = ["cursor", "png", x, y, width, height, xhot, yhot, serial, pixels, name]
            #or:
            #packet = ["cursor", ""]
            if len(packet) >= 8:
                #hard to distinguish png cursors from normal cursors...
                try:
                    int(packet[1])
                    self._packet_recompress(packet, 8, "cursor")
                except:
                    self._packet_recompress(packet, 9, "cursor")
        elif packet_type == "window-icon":
            self._packet_recompress(packet, 5, "icon")
        elif packet_type == "send-file":
            if packet[6]:
                packet[6] = Compressed("file-data", packet[6])
        elif packet_type == "send-file-chunk":
            if packet[3]:
                packet[3] = Compressed("file-chunk-data", packet[3])
        elif packet_type == "challenge":
            password = self.session_options.get("password")
            if not password:
                self.stop(
                    "authentication requested by the server, but no password available for this session"
                )
                return
            from xpra.net.crypto import get_salt, gendigest
            #client may have already responded to the challenge,
            #so we have to handle authentication from this end
            server_salt = bytestostr(packet[1])
            l = len(server_salt)
            digest = bytestostr(packet[3])
            salt_digest = "xor"
            if len(packet) >= 5:
                salt_digest = bytestostr(packet[4])
            if salt_digest in ("xor", "des"):
                if not LEGACY_SALT_DIGEST:
                    self.stop("server uses legacy salt digest '%s'" %
                              salt_digest)
                    return
                log.warn(
                    "Warning: server using legacy support for '%s' salt digest",
                    salt_digest)
            if salt_digest == "xor":
                #with xor, we have to match the size
                assert l >= 16, "server salt is too short: only %i bytes, minimum is 16" % l
                assert l <= 256, "server salt is too long: %i bytes, maximum is 256" % l
            else:
                #other digest, 32 random bytes is enough:
                l = 32
            client_salt = get_salt(l)
            salt = gendigest(salt_digest, client_salt, server_salt)
            challenge_response = gendigest(digest, password, salt)
            if not challenge_response:
                log("invalid digest module '%s': %s", digest)
                self.stop(
                    "server requested '%s' digest but it is not supported" %
                    digest)
                return
            log.info("sending %s challenge response", digest)
            self.send_hello(challenge_response, client_salt)
            return
        self.queue_client_packet(packet)

    def encode_loop(self):
        """ thread for slower encoding related work """
        while not self.exit:
            packet = self.encode_queue.get()
            if packet is None:
                return
            try:
                packet_type = packet[0]
                if packet_type == "lost-window":
                    wid = packet[1]
                    self.lost_windows.remove(wid)
                    ve = self.video_encoders.get(wid)
                    if ve:
                        del self.video_encoders[wid]
                        del self.video_encoders_last_used_time[wid]
                        ve.clean()
                elif packet_type == "draw":
                    #modify the packet with the video encoder:
                    if self.process_draw(packet):
                        #then send it as normal:
                        self.queue_client_packet(packet)
                elif packet_type == "check-video-timeout":
                    #not a real packet, this is added by the timeout check:
                    wid = packet[1]
                    ve = self.video_encoders.get(wid)
                    now = monotonic_time()
                    idle_time = now - self.video_encoders_last_used_time.get(
                        wid)
                    if ve and idle_time > VIDEO_TIMEOUT:
                        enclog(
                            "timing out the video encoder context for window %s",
                            wid)
                        #timeout is confirmed, we are in the encoding thread,
                        #so it is now safe to clean it up:
                        ve.clean()
                        del self.video_encoders[wid]
                        del self.video_encoders_last_used_time[wid]
                else:
                    enclog.warn("unexpected encode packet: %s", packet_type)
            except:
                enclog.warn("error encoding packet", exc_info=True)

    def process_draw(self, packet):
        wid, x, y, width, height, encoding, pixels, _, rowstride, client_options = packet[
            1:11]
        #never modify mmap packets
        if encoding in ("mmap", "scroll"):
            return True

        #we have a proxy video packet:
        rgb_format = client_options.get("rgb_format", "")
        enclog("proxy draw: client_options=%s", client_options)

        def send_updated(encoding, compressed_data, updated_client_options):
            #update the packet with actual encoding data used:
            packet[6] = encoding
            packet[7] = compressed_data
            packet[10] = updated_client_options
            enclog("returning %s bytes from %s, options=%s",
                   len(compressed_data), len(pixels), updated_client_options)
            return (wid not in self.lost_windows)

        def passthrough(strip_alpha=True):
            enclog(
                "proxy draw: %s passthrough (rowstride: %s vs %s, strip alpha=%s)",
                rgb_format, rowstride, client_options.get("rowstride",
                                                          0), strip_alpha)
            if strip_alpha:
                #passthrough as plain RGB:
                Xindex = rgb_format.upper().find("X")
                if Xindex >= 0 and len(rgb_format) == 4:
                    #force clear alpha (which may be garbage):
                    newdata = bytearray(pixels)
                    for i in range(len(pixels) / 4):
                        newdata[i * 4 + Xindex] = chr(255)
                    packet[9] = client_options.get("rowstride", 0)
                    cdata = bytes(newdata)
                else:
                    cdata = pixels
                new_client_options = {"rgb_format": rgb_format}
            else:
                #preserve
                cdata = pixels
                new_client_options = client_options
            wrapped = Compressed("%s pixels" % encoding, cdata)
            #FIXME: we should not assume that rgb32 is supported here...
            #(we may have to convert to rgb24..)
            return send_updated("rgb32", wrapped, new_client_options)

        proxy_video = client_options.get("proxy", False)
        if PASSTHROUGH and (encoding in ("rgb32", "rgb24") or proxy_video):
            #we are dealing with rgb data, so we can pass it through:
            return passthrough(proxy_video)
        elif not self.video_encoder_types or not client_options or not proxy_video:
            #ensure we don't try to re-compress the pixel data in the network layer:
            #(re-add the "compressed" marker that gets lost when we re-assemble packets)
            packet[7] = Compressed("%s pixels" % encoding, packet[7])
            return True

        #video encoding: find existing encoder
        ve = self.video_encoders.get(wid)
        if ve:
            if ve in self.lost_windows:
                #we cannot clean the video encoder here, there may be more frames queue up
                #"lost-window" in encode_loop will take care of it safely
                return False
            #we must verify that the encoder is still valid
            #and scrap it if not (ie: when window is resized)
            if ve.get_width() != width or ve.get_height() != height:
                enclog(
                    "closing existing video encoder %s because dimensions have changed from %sx%s to %sx%s",
                    ve, ve.get_width(), ve.get_height(), width, height)
                ve.clean()
                ve = None
            elif ve.get_encoding() != encoding:
                enclog(
                    "closing existing video encoder %s because encoding has changed from %s to %s",
                    ve.get_encoding(), encoding)
                ve.clean()
                ve = None
        #scaling and depth are proxy-encoder attributes:
        scaling = client_options.get("scaling", (1, 1))
        depth = client_options.get("depth", 24)
        rowstride = client_options.get("rowstride", rowstride)
        quality = client_options.get("quality", -1)
        speed = client_options.get("speed", -1)
        timestamp = client_options.get("timestamp")

        image = ImageWrapper(x,
                             y,
                             width,
                             height,
                             pixels,
                             rgb_format,
                             depth,
                             rowstride,
                             planes=ImageWrapper.PACKED)
        if timestamp is not None:
            image.set_timestamp(timestamp)

        #the encoder options are passed through:
        encoder_options = client_options.get("options", {})
        if not ve:
            #make a new video encoder:
            spec = self._find_video_encoder(encoding, rgb_format)
            if spec is None:
                #no video encoder!
                enc_pillow = get_codec("enc_pillow")
                if not enc_pillow:
                    from xpra.server.picture_encode import warn_encoding_once
                    warn_encoding_once(
                        "no-video-no-PIL",
                        "no video encoder found for rgb format %s, sending as plain RGB!"
                        % rgb_format)
                    return passthrough(True)
                enclog("no video encoder available: sending as jpeg")
                coding, compressed_data, client_options, _, _, _, _ = enc_pillow.encode(
                    "jpeg", image, quality, speed, False)
                return send_updated(coding, compressed_data, client_options)

            enclog("creating new video encoder %s for window %s", spec, wid)
            ve = spec.make_instance()
            #dst_formats is specified with first frame only:
            dst_formats = client_options.get("dst_formats")
            if dst_formats is not None:
                #save it in case we timeout the video encoder,
                #so we can instantiate it again, even from a frame no>1
                self.video_encoders_dst_formats = dst_formats
            else:
                assert self.video_encoders_dst_formats, "BUG: dst_formats not specified for proxy and we don't have it either"
                dst_formats = self.video_encoders_dst_formats
            ve.init_context(width, height, rgb_format, dst_formats, encoding,
                            quality, speed, scaling, {})
            self.video_encoders[wid] = ve
            self.video_encoders_last_used_time[wid] = monotonic_time(
            )  #just to make sure this is always set
        #actual video compression:
        enclog("proxy compression using %s with quality=%s, speed=%s", ve,
               quality, speed)
        data, out_options = ve.compress_image(image, quality, speed,
                                              encoder_options)
        #pass through some options if we don't have them from the encoder
        #(maybe we should also use the "pts" from the real server?)
        for k in ("timestamp", "rgb_format", "depth", "csc"):
            if k not in out_options and k in client_options:
                out_options[k] = client_options[k]
        self.video_encoders_last_used_time[wid] = monotonic_time()
        return send_updated(ve.get_encoding(), Compressed(encoding, data),
                            out_options)

    def timeout_video_encoders(self):
        #have to be careful as another thread may come in...
        #so we just ask the encode thread (which deals with encoders already)
        #to do what may need to be done if we find a timeout:
        now = monotonic_time()
        for wid in tuple(self.video_encoders_last_used_time.keys()):
            idle_time = int(now - self.video_encoders_last_used_time.get(wid))
            if idle_time is None:
                continue
            enclog("timeout_video_encoders() wid=%s, idle_time=%s", wid,
                   idle_time)
            if idle_time and idle_time > VIDEO_TIMEOUT:
                self.encode_queue.put(["check-video-timeout", wid])
        return True  #run again

    def _find_video_encoder(self, encoding, rgb_format):
        #try the one specified first, then all the others:
        try_encodings = [encoding] + [
            x for x in self.video_helper.get_encodings() if x != encoding
        ]
        for encoding in try_encodings:
            colorspace_specs = self.video_helper.get_encoder_specs(encoding)
            especs = colorspace_specs.get(rgb_format)
            if len(especs) == 0:
                continue
            for etype in self.video_encoder_types:
                for spec in especs:
                    if etype == spec.codec_type:
                        enclog("_find_video_encoder(%s, %s)=%s", encoding,
                               rgb_format, spec)
                        return spec
        enclog("_find_video_encoder(%s, %s) not found", encoding, rgb_format)
        return None

    def get_window_info(self):
        info = {}
        now = monotonic_time()
        for wid, encoder in self.video_encoders.items():
            einfo = encoder.get_info()
            einfo["idle_time"] = int(
                now - self.video_encoders_last_used_time.get(wid, 0))
            info[wid] = {
                "proxy": {
                    "": encoder.get_type(),
                    "encoder": einfo
                },
            }
        enclog("get_window_info()=%s", info)
        return info
Exemple #13
0
log = Logger("sound")
gstlog = Logger("gstreamer")

APPSINK = os.environ.get(
    "XPRA_SOURCE_APPSINK",
    "appsink name=sink emit-signals=true max-buffers=10 drop=true sync=false async=false qos=false"
)
JITTER = envint("XPRA_SOUND_SOURCE_JITTER", 0)
SOURCE_QUEUE_TIME = get_queue_time(50, "SOURCE_")

BUFFER_TIME = envint("XPRA_SOUND_SOURCE_BUFFER_TIME", 0)  #ie: 64
LATENCY_TIME = envint("XPRA_SOUND_SOURCE_LATENCY_TIME", 0)  #ie: 32
BUNDLE_METADATA = envbool("XPRA_SOUND_BUNDLE_METADATA", True)
SAVE_TO_FILE = os.environ.get("XPRA_SAVE_TO_FILE")

generation = AtomicInteger()


class SoundSource(SoundPipeline):

    __gsignals__ = SoundPipeline.__generic_signals__.copy()
    __gsignals__.update({
        "new-buffer": n_arg_signal(3),
    })

    def __init__(self,
                 src_type=None,
                 src_options={},
                 codecs=get_encoders(),
                 codec_options={},
                 volume=1.0):