Exemplo n.º 1
0
 public PCMUSession()
 {
     SSRC        = RngProvider.GetRandomNumber();
     Sequence    = 0;
     PayloadType = 0;
     ClockRate   = 8000;
 }
Exemplo n.º 2
0
        public H264Session()
        {
            SSRC         = RngProvider.GetRandomNumber();
            Sequence     = 0;
            PayloadType  = 96;
            lastSequence = 0;

            logger.Debug("H264Session() " + SSRC);
        }
Exemplo n.º 3
0
        public void Connect(string addr, int port)
        {
            tracer.Verb("ScreenCastControl::Connecting(...) " + addr + " " + port);
            hWnd = this.Handle;//this.Parent.Parent.Handle;
            //logger.Debug("RemoteDesktopClient::Connecting(...) " + addr + " " + port);

            state = ClientState.Connecting;

            cancelled = false;
            errorCode = ErrorCode.Ok;

            this.ServerAddr = addr;
            this.ServerPort = port;

            this.ClientId = RngProvider.GetRandomNumber().ToString();

            var address = "net.tcp://" + ServerAddr + "/ScreenCaster";

            if (this.ServerPort > 0)
            {
                address = "net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster";
            }

            //Console.WriteLine(address);

            UpdateControls();

            mainTask = Task.Run(() =>
            {
                //int maxTryCount = 10;
                uint tryCount = 0;

                bool forceReconnect = (MaxTryConnectCount == uint.MaxValue);

                while ((forceReconnect || tryCount <= MaxTryConnectCount) && !cancelled)
                {
                    tracer.Verb("ScreenCastControl::Connecting count: " + tryCount);

                    //logger.Debug("Connecting count: " + tryCount);
                    //errorMessage = "";
                    errorCode = ErrorCode.Ok;

                    try
                    {
                        var uri = new Uri(address);

                        NetTcpSecurity security = new NetTcpSecurity
                        {
                            Mode = SecurityMode.None,
                        };

                        var binding = new NetTcpBinding
                        {
                            ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10),
                            SendTimeout    = TimeSpan.FromSeconds(5),
                            OpenTimeout    = TimeSpan.FromSeconds(5),

                            Security = security,
                        };

                        //var _uri = new Uri("net.tcp://" + ServerAddr + ":" + 0 + "/ScreenCaster");
                        //factory = new ChannelFactory<IScreenCastService>(binding, new EndpointAddress(_uri));

                        //var viaUri = new Uri("net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster");
                        //factory.Endpoint.EndpointBehaviors.Add(new System.ServiceModel.Description.ClientViaBehavior(viaUri));

                        factory         = new ChannelFactory <IScreenCastService>(binding, new EndpointAddress(uri));
                        factory.Closed += Factory_Closed;

                        var channel = factory.CreateChannel();

                        try
                        {
                            var channelInfos = channel.GetChannelInfos();

                            state = ClientState.Connected;
                            UpdateControls();
                            Connected?.Invoke();

                            if (channelInfos == null)
                            {
                                errorCode = ErrorCode.NotReady;
                                throw new Exception("Server not configured");
                            }

                            var videoChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is VideoChannelInfo);
                            if (videoChannelInfo != null)
                            {
                                if (videoChannelInfo.Transport == TransportMode.Tcp && videoChannelInfo.ClientsCount > 0)
                                {
                                    errorCode = ErrorCode.IsBusy;
                                    throw new Exception("Server is busy");
                                }
                                SetupVideo(videoChannelInfo);
                            }

                            var audioChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is AudioChannelInfo);
                            if (audioChannelInfo != null)
                            {
                                if (audioChannelInfo.Transport == TransportMode.Tcp && videoChannelInfo.ClientsCount > 0)
                                {
                                    errorCode = ErrorCode.IsBusy;
                                    throw new Exception("Server is busy");
                                }

                                SetupAudio(audioChannelInfo);
                            }

                            if (VideoReceiver != null)
                            {
                                VideoReceiver.Play();
                                // d3dRenderer.Start();
                            }

                            if (AudioReceiver != null)
                            {
                                AudioReceiver.Play();
                            }

                            channel.PostMessage(new ServerRequest {
                                Command = "Ping"
                            });
                            tryCount = 0;

                            state = ClientState.Running;
                            UpdateControls();

                            while (state == ClientState.Running)
                            {
                                try
                                {
                                    channel.PostMessage(new ServerRequest {
                                        Command = "Ping"
                                    });
                                    if (d3dRenderer.ErrorCode != 0)
                                    {
                                        tracer.Warn("ScreenCastControl::imageProvider.ErrorCode: " + d3dRenderer.ErrorCode);

                                        // logger.Debug("imageProvider.ErrorCode: " + videoRenderer.ErrorCode);
                                        //Process render error...
                                    }

                                    //TODO::
                                    // Receivers errors...

                                    syncEvent.WaitOne(1000);
                                }
                                catch (Exception ex)
                                {
                                    state     = ClientState.Interrupted;
                                    errorCode = ErrorCode.Interrupted;
                                }
                            }
                        }
                        finally
                        {
                            CloseChannel(channel);
                        }
                    }
                    catch (EndpointNotFoundException ex)
                    {
                        errorCode = ErrorCode.NotFound;

                        tracer.Error(ex.Message);

                        //logger.Error(ex.Message);

                        //Console.WriteLine(ex.Message);
                    }
                    catch (Exception ex)
                    {
                        tracer.Error(ex);
                        //logger.Error(ex);

                        if (errorCode == ErrorCode.Ok)
                        {
                            errorCode = ErrorCode.Fail;
                        }

                        //Console.WriteLine(ex);
                    }
                    finally
                    {
                        Close();
                    }

                    if (!cancelled)
                    {
                        if (errorCode != ErrorCode.Ok)
                        {
                            UpdateControls();

                            tryCount++;

                            var statusStr = "Attempting to connect..."; // + tryCount; // + " of " + maxTryCount;

                            SetStatus(statusStr);
                        }

                        Thread.Sleep(1000);
                        continue;
                    }
                    else
                    {
                        errorCode = ErrorCode.Cancelled;
                        break;
                    }
                }//while end

                cancelled = false;

                state = ClientState.Disconnected;
                UpdateControls();

                Disconnected?.Invoke(null);
            });
        }
Exemplo n.º 4
0
        private void ClientProc()
        {
            var address = "net.tcp://" + ServerAddr + "/RemoteDesktop";

            try
            {
                var uri = new Uri(address);
                //NetTcpSecurity security = new NetTcpSecurity
                //{
                //    Mode = SecurityMode.Transport,
                //    Transport = new TcpTransportSecurity
                //    {
                //        ClientCredentialType = TcpClientCredentialType.Windows,
                //        ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign,
                //    },
                //};

                NetTcpSecurity security = new NetTcpSecurity
                {
                    Mode = SecurityMode.None,
                };

                var binding = new NetTcpBinding
                {
                    ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10),
                    SendTimeout    = TimeSpan.FromSeconds(10),
                    Security       = security,
                };


                factory = new ChannelFactory <IRemoteDesktopService>(binding, new EndpointAddress(uri));
                var channel = factory.CreateChannel();

                try
                {
                    this.ClientId = RngProvider.GetRandomNumber().ToString();

                    var connectReq = new RemoteDesktopRequest
                    {
                        SenderId = ClientId,
                    };

                    var connectionResponse = channel.Connect(connectReq);
                    if (!connectionResponse.IsSuccess)
                    {
                        logger.Error("connectionResponse " + connectionResponse.FaultCode);
                        return;
                    }

                    this.ServerId   = connectionResponse.ServerId;
                    this.ServerName = connectionResponse.HostName;

                    var screens       = connectionResponse.Screens;
                    var primaryScreen = screens.FirstOrDefault(s => s.IsPrimary);

                    var startRequest = new StartSessionRequest
                    {
                        SenderId = this.ClientId,

                        SrcRect              = primaryScreen.Bounds,
                        DestAddr             = "", //"192.168.1.135",//localAddr.Address.ToString(), //localAddr.ToString(),
                        DestPort             = 1234,
                        DstSize              = new Size(1920, 1080),
                        EnableInputSimulator = true,
                    };


                    var startResponse = channel.Start(startRequest);
                    if (!startResponse.IsSuccess)
                    {
                        logger.Error("startResponse " + startResponse.FaultCode);
                        return;
                    }

                    var inputPars = new VideoEncoderSettings
                    {
                        Resolution = startRequest.DstSize,
                        //Width = startRequest.DstSize.Width,
                        //Height = startRequest.DstSize.Height,

                        //Width = 640,//2560,
                        //Height = 480,//1440,
                        FrameRate = 30,
                    };

                    var outputPars = new VideoEncoderSettings
                    {
                        //Width = 640,//2560,
                        //Height = 480,//1440,
                        //Width = startRequest.DstSize.Width,
                        //Height = startRequest.DstSize.Height,

                        Resolution = startRequest.DstSize,
                        FrameRate  = 30,
                    };
                    var transport = TransportMode.Udp;

                    var networkPars = new NetworkSettings
                    {
                        LocalAddr     = ServerAddr,
                        LocalPort     = 1234,
                        TransportMode = transport,
                    };

                    this.Play(inputPars, outputPars, networkPars);

                    InputManager = new InputManager();

                    InputManager.Start(ServerAddr, 8888);
                    running = true;

                    State = ClientState.Connected;

                    OnStateChanged(State);

                    while (running)
                    {
                        channel.PostMessage("Ping", null);


                        syncEvent.WaitOne(1000);

                        //InternalCommand command = null;
                        //do
                        //{
                        //    command = DequeueCommand();
                        //    if (command != null)
                        //    {
                        //        ProcessCommand(command);
                        //    }

                        //} while (command != null);
                    }
                }
                finally
                {
                    running = false;

                    State = ClientState.Disconnected;
                    OnStateChanged(State);

                    try
                    {
                        var c = (IClientChannel)channel;
                        if (c.State != CommunicationState.Faulted)
                        {
                            c.Close();
                        }
                        else
                        {
                            c.Abort();
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);


                State = ClientState.Faulted;
                OnStateChanged(State);

                Close();
            }
        }
Exemplo n.º 5
0
        private void ClientProc()
        {
            var address = "net.tcp://" + ServerAddr + "/ScreenCaster";

            if (this.ServerPort > 0)
            {
                address = "net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster";
            }
            
            try
            {

                var uri = new Uri(address);
                this.ClientId = RngProvider.GetRandomNumber().ToString();

                //NetTcpSecurity security = new NetTcpSecurity
                //{
                //    Mode = SecurityMode.Transport,
                //    Transport = new TcpTransportSecurity
                //    {
                //        ClientCredentialType = TcpClientCredentialType.Windows,
                //        ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign,
                //    },
                //};

                NetTcpSecurity security = new NetTcpSecurity
                {
                    Mode = SecurityMode.None,
                };

                var binding = new NetTcpBinding
                {
                    ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10),
                    SendTimeout = TimeSpan.FromSeconds(10),
                    Security = security,
                };

                factory = new ChannelFactory<IScreenCastService>(binding, new EndpointAddress(uri));
                var channel = factory.CreateChannel();

                try
                {
                    //channel.PostMessage(new ServerRequest { Command = "Ping" });

                    var channelInfos = channel.GetChannelInfos();

                    if (channelInfos == null)
                    {
                        logger.Error("channelInfos == null");
                        return;
                    }


                    TransportMode transportMode = TransportMode.Udp;
                    var videoChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is VideoChannelInfo);

                    if (videoChannelInfo != null)
                    {
                        transportMode = videoChannelInfo.Transport;

                        if(transportMode == TransportMode.Tcp)
                        {
                            if (videoChannelInfo.ClientsCount > 0)
                            {
                                throw new Exception("Server is busy");
                            }
                        }

                        var videoAddr = videoChannelInfo.Address;

                        if(transportMode == TransportMode.Tcp)
                        {
                            videoAddr = ServerAddr;
                        }

                        var videoPort = videoChannelInfo.Port;

                        //if (string.IsNullOrEmpty(videoAddr))
                        //{
                        //    //channel.Play()
                        //}

                        //if (transportMode == TransportMode.Tcp)
                        //{
                        //   var res = channel.Play(channelInfos);
                        //}

                        var videoInfo = videoChannelInfo.MediaInfo as VideoChannelInfo;
                        if (videoInfo != null)
                        {
                            var inputPars = new VideoEncoderSettings
                            {
                                Resolution = videoInfo.Resolution,
                                //Width = videoInfo.Resolution.Width,
                                //Height = videoInfo.Resolution.Height,
                                FrameRate = new MediaRatio(videoInfo.Fps,
                            };

                            var outputPars = new VideoEncoderSettings
                            {
                                //Width = 640,//2560,
                                //Height = 480,//1440,
                                //Width = 1920,
                                //Height = 1080,

                                //FrameRate = 30,

                                //Width = videoInfo.Resolution.Width,
                                //Height = videoInfo.Resolution.Height,
                                Resolution = videoInfo.Resolution,
                                FrameRate = videoInfo.Fps,

                            };

                            //bool keepRatio = true;
                            //if (keepRatio)
                            //{
                            //    var srcSize = new Size(inputPars.Width, inputPars.Height);
                            //    var destSize = new Size(outputPars.Width, outputPars.Height);


                            //    var ratio = srcSize.Width / (double)srcSize.Height;
                            //    int destWidth = destSize.Width;
                            //    int destHeight = (int)(destWidth / ratio);
                            //    if (ratio < 1)
                            //    {
                            //        destHeight = destSize.Height;
                            //        destWidth = (int)(destHeight * ratio);
                            //    }
                            //    outputPars.Width = destWidth;
                            //    outputPars.Height = destHeight;
                            //}



                            var networkPars = new NetworkSettings
                            {
                                LocalAddr = videoAddr,
                                LocalPort = videoPort,
                                TransportMode = transportMode,

                                SSRC = videoChannelInfo.SSRC,
                            };

                            VideoReceiver = new VideoReceiver();


                            VideoReceiver.Setup(inputPars, outputPars, networkPars);
                            VideoReceiver.UpdateBuffer += VideoReceiver_UpdateBuffer;
                        }

                    }


                    var audioChannelInfo =channelInfos.FirstOrDefault(c => c.MediaInfo is AudioChannelInfo);
                    if (audioChannelInfo != null)
                    {
                        var audioInfo = audioChannelInfo.MediaInfo as AudioChannelInfo;
                        if (audioInfo != null)
                        {

                            var audioAddr = audioChannelInfo.Address;
                            transportMode = audioChannelInfo.Transport;

                            if (transportMode == TransportMode.Tcp)
                            {
                                audioAddr = ServerAddr;
                            }

                            if (transportMode == TransportMode.Tcp)
                            {
                                if (audioChannelInfo.ClientsCount > 0)
                                {
                                    throw new Exception("Server is busy");
                                }
                            }

                            var audioPort = audioChannelInfo.Port;

                            AudioReceiver = new AudioReceiver();

                            var networkPars = new NetworkSettings
                            {
                                LocalAddr = audioAddr,
                                LocalPort = audioPort,
                                TransportMode = transportMode,

                                SSRC = audioChannelInfo.SSRC,

                            };

                            var audioDeviceId = "";
                            try
                            {
                                var devices = DirectSoundOut.Devices;
                                var device = devices.FirstOrDefault();
                                audioDeviceId = device?.Guid.ToString() ?? "";
                            }
                            catch(Exception ex)
                            {
                                logger.Error(ex);
                            }


                            var audioPars = new AudioEncoderSettings
                            {
                                SampleRate = audioInfo.SampleRate,
                                Channels = audioInfo.Channels,
                                Encoding = "ulaw",
                                DeviceId = audioDeviceId,//currentDirectSoundDeviceInfo?.Guid.ToString() ?? "",
                            };

                            AudioReceiver.Setup(audioPars, networkPars);
                        }

                    }


                    if (VideoReceiver != null)
                    {
                        VideoReceiver.Play();
                    }

                    if (AudioReceiver != null)
                    {
                        AudioReceiver.Play();
                    }


                    running = true;

                    State = ClientState.Connected;

                    OnStateChanged(State);

                    while (running)
                    {

                        channel.PostMessage(new ServerRequest { Command = "Ping" });


                        syncEvent.WaitOne(1000);

                        //InternalCommand command = null;
                        //do
                        //{
                        //    command = DequeueCommand();
                        //    if (command != null)
                        //    {
                        //        ProcessCommand(command);
                        //    }

                        //} while (command != null);
                    }


                }
                finally
                {
                    running = false;

                    State = ClientState.Disconnected;
                    OnStateChanged(State);

                    try
                    {
                        var c = (IClientChannel)channel;
                        if (c.State != CommunicationState.Faulted)
                        {
                            c.Close();
                        }
                        else
                        {
                            c.Abort();
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);


                State = ClientState.Faulted;
                OnStateChanged(State);

                //Close();
            }
            finally
            {
                Close();
            }
        }