示例#1
0
        public void Close()
        {
            if (videoRendererSink != null)
            {
                videoRendererSink.Stop();
                //videoRendererSink.Close();
                videoRendererSink = null;
            }

            if (VideoReceiver != null)
            {
                VideoReceiver.DataReceived -= VideoReceiver_DataReceived;
                VideoReceiver.Stop();
                VideoReceiver = null;
            }

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

            if (factory != null)
            {
                factory.Closed -= Factory_Closed;

                factory.Abort();
                factory = null;
            }

            //state = ClientState.Disconnected;
        }
示例#2
0
    /// <summary>
    /// 启动实时取景视频流。调用这个API,会创建一个TCP服务器,端口为890.客户端可以通过SOCKET端口,读取视频流。视频流格式为MJPEG.
    /// 返回: 成功返回 状态代码 200 OK,否则返回状态代码500.
    /// </summary>
    /// <param name="request"></param>
    /// <param name="response"></param>
    void onCaptureMovie(HTTPRequest request, HTTPResponse response)
    {
        if (RequestIsSuccess(request, response))
        {
            if (response.StatusCode == 200)
            {
                Debug.Log("连接实时取景成功 : ");

                if (_videoReceiver == null)
                {
                    _videoReceiver = new VideoReceiver(onVideoFramePrepared);
                }
                _videoReceiver.Receive();

                _connectLiveShowSuccess = true;
            }
            else
            {
                // 实时取景失败
                _connectLiveShowSuccess = false;
            }
        }
        else
        {
            Debug.Log("连接实时取景失败 : ");
            // 连接实时取景失败
            _connectLiveShowSuccess = false;
        }

        if (!_connectLiveShowSuccess)
        {
            _onCameraManagerError.Invoke("_connect Live Show Error");
        }
    }
示例#3
0
        public void Close()
        {
            if (imageProvider != null)
            {
                imageProvider.Close();

            }

            if (VideoReceiver != null)
            {
                VideoReceiver.UpdateBuffer -= VideoReceiver_UpdateBuffer;
                VideoReceiver.Stop();
                VideoReceiver = null;
            }

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


            if (factory != null)
            {
                factory.Abort();
                factory = null;
            }
        }
示例#4
0
        internal void Stop()
        {
            logger.Debug("RemoteDesktopClient::Stop()");

            if (VideoReceiver != null)
            {
                VideoReceiver.UpdateBuffer -= VideoReceiver_UpdateBuffer;
                VideoReceiver.Stop();
            }
        }
示例#5
0
        internal void Play(VideoEncoderSettings inputPars, VideoEncoderSettings outputPars, NetworkSettings networkPars)
        {
            logger.Debug("RemoteDesktopClient::Play(...)");
            VideoReceiver = new VideoReceiver();

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

            VideoReceiver.Play();
        }
示例#6
0
        public async Task <IActionResult> ConfirmDeleteFromVideoreceivers_list(int?id)
        {
            if (id != null)
            {
                VideoReceiver find_part = await PartsContext.VideoReceivers.FirstOrDefaultAsync(p => p.Id == id);

                return(DeleteView(find_part, "Videoreceivers_list"));
            }
            return(NotFound());
        }
示例#7
0
        public async Task <IActionResult> DeleteVideoreceivers_list(int?id)
        {
            if (id != null)
            {
                VideoReceiver find_part = new VideoReceiver {
                    Id = id.Value
                };
                await DeletePart(find_part);

                return(RedirectToAction("Index"));
            }
            return(NotFound());
        }
示例#8
0
 /// <summary>
 /// 启动实时取景视频流。调用这个API,会创建一个TCP服务器,端口为890.客户端可以通过SOCKET端口,读取视频流。视频流格式为MJPEG.
 /// 返回: 成功返回 状态代码 200 OK,否则返回状态代码500.
 /// </summary>
 /// <param name="request"></param>
 /// <param name="response"></param>
 void onCaptureMovie(HTTPRequest request, HTTPResponse response)
 {
     if (RequestIsSuccess(request, response))
     {
         if (response.StatusCode == 200)
         {
             VideoReceiver videoReceiver = new VideoReceiver(onVideoFramePrepared);
             videoReceiver.Receive();
         }
         else
         {
             // 实时取景失败
         }
     }
     else
     {
         // 连接实时取景失败
     }
 }
示例#9
0
        public void Close()
        {
            if (VideoReceiver != null)
            {
                VideoReceiver.UpdateBuffer -= VideoReceiver_UpdateBuffer;
                VideoReceiver.Stop();
                VideoReceiver = null;
            }

            if (InputManager != null)
            {
                InputManager.Stop();
                InputManager = null;
            }

            if (factory != null)
            {
                factory.Abort();
                factory = null;
            }
        }
示例#10
0
        public void Close()
        {
            if (d3dProvider != null)
            {
                d3dProvider.Close();
                d3dProvider = null;
            }

            if (d3dRenderer != null)
            {
                d3dRenderer.Shutdown();
            }

            if (VideoReceiver != null)
            {
                VideoReceiver.UpdateBuffer -= VideoReceiver_UpdateBuffer;
                VideoReceiver.Stop();
                VideoReceiver = null;
            }

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

            if (factory != null)
            {
                factory.Closed -= Factory_Closed;

                factory.Abort();
                factory = null;
            }

            //state = ClientState.Disconnected;
        }
示例#11
0
        private void SetupVideo(ScreencastChannelInfo videoChannelInfo)
        {
            tracer.Verb("ScreenCastControl::SetupVideo(...)");


            //logger.Debug("SetupVideo(...)");

            var videoInfo = videoChannelInfo.MediaInfo as VideoChannelInfo;

            if (videoInfo == null)
            {
                return;
            }


            var videoAddr = videoChannelInfo.Address;

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

            var videoPort = videoChannelInfo.Port;
            var inputPars = new VideoEncoderSettings
            {
                //Resolution = videoInfo.Resolution,
                Width     = videoInfo.Resolution.Width,
                Height    = videoInfo.Resolution.Height,
                FrameRate = new MediaRatio(videoInfo.Fps, 1),
            };

            var outputPars = new VideoEncoderSettings
            {
                //Resolution = videoInfo.Resolution,
                Width  = videoInfo.Resolution.Width,
                Height = videoInfo.Resolution.Height,
                //AspectRatio = new MediaRatio(1, 1),
                //Resolution = new System.Drawing.Size(1920, 1080);

                FrameRate = new MediaRatio(videoInfo.Fps, 1),
            };

            var networkPars = new NetworkSettings
            {
                LocalAddr     = videoAddr,
                LocalPort     = videoPort,
                TransportMode = videoChannelInfo.Transport,
                SSRC          = videoChannelInfo.SSRC,
            };

            VideoReceiver = new VideoReceiver();

            VideoReceiver.UpdateBuffer += VideoReceiver_UpdateBuffer;

            VideoReceiver.Setup(inputPars, outputPars, networkPars);

            d3dProvider = new D3D11RendererProvider();
            d3dProvider.Init(VideoReceiver.sharedTexture);


            //d3dRenderer.Setup(VideoReceiver.sharedTexture);
        }
示例#12
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);
            });
        }
示例#13
0
        private IEnumerator SingleTwoWaysImpl(bool withSender1, bool withReceiver1, bool withSender2, bool withReceiver2)
        {
            // Create the peer connections
            var pc1_go = new GameObject("pc1");

            pc1_go.SetActive(false); // prevent auto-activation of components
            var pc1 = pc1_go.AddComponent <PeerConnection>();

            pc1.AutoInitializeOnStart = false;
            var pc2_go = new GameObject("pc2");

            pc2_go.SetActive(false); // prevent auto-activation of components
            var pc2 = pc2_go.AddComponent <PeerConnection>();

            pc2.AutoInitializeOnStart = false;

            // Batch changes manually
            pc1.AutoCreateOfferOnRenegotiationNeeded = false;
            pc2.AutoCreateOfferOnRenegotiationNeeded = false;

            // Create the signaler
            var sig_go = new GameObject("signaler");
            var sig    = sig_go.AddComponent <LocalOnlySignaler>();

            sig.Peer1 = pc1;
            sig.Peer2 = pc2;

            // Create the video sources on peer #1
            VideoTrackSource source1   = null;
            VideoReceiver    receiver1 = null;

            if (withSender1)
            {
                source1 = pc1_go.AddComponent <UniformColorVideoSource>();
            }
            if (withReceiver1)
            {
                receiver1 = pc1_go.AddComponent <VideoReceiver>();
            }
            MediaLine ml1 = pc1.AddMediaLine(MediaKind.Video);

            ml1.SenderTrackName = "video_track_1";
            ml1.Source          = source1;
            ml1.Receiver        = receiver1;

            // Create the video sources on peer #2
            VideoTrackSource source2   = null;
            VideoReceiver    receiver2 = null;

            if (withSender2)
            {
                source2 = pc2_go.AddComponent <UniformColorVideoSource>();
            }
            if (withReceiver2)
            {
                receiver2 = pc1_go.AddComponent <VideoReceiver>();
            }
            MediaLine ml2 = pc2.AddMediaLine(MediaKind.Video);

            ml2.SenderTrackName = "video_track_2";
            ml2.Source          = source2;
            ml2.Receiver        = receiver2;

            // Activate
            pc1_go.SetActive(true);
            pc2_go.SetActive(true);

            // Initialize
            var initializedEvent1 = new ManualResetEventSlim(initialState: false);

            pc1.OnInitialized.AddListener(() => initializedEvent1.Set());
            Assert.IsNull(pc1.Peer);
            pc1.InitializeAsync().Wait(millisecondsTimeout: 50000);
            var initializedEvent2 = new ManualResetEventSlim(initialState: false);

            pc2.OnInitialized.AddListener(() => initializedEvent2.Set());
            Assert.IsNull(pc2.Peer);
            pc2.InitializeAsync().Wait(millisecondsTimeout: 50000);

            // Wait a frame so that the Unity event OnInitialized can propagate
            yield return(null);

            // Check the event was raised
            Assert.IsTrue(initializedEvent1.Wait(millisecondsTimeout: 50000));
            Assert.IsNotNull(pc1.Peer);
            Assert.IsTrue(initializedEvent2.Wait(millisecondsTimeout: 50000));
            Assert.IsNotNull(pc2.Peer);

            // Confirm the sources are ready
            if (withSender1)
            {
                Assert.IsTrue(source1.IsStreaming);
            }
            if (withSender2)
            {
                Assert.IsTrue(source2.IsStreaming);
            }

            // Confirm the sender track is not created yet; it will be when the connection starts
            Assert.IsNull(ml1.SenderTrack);
            Assert.IsNull(ml2.SenderTrack);

            // Confirm the receiver track is not added yet, since remote tracks are only instantiated
            // as the result of a session negotiation.
            if (withReceiver1)
            {
                Assert.IsNull(receiver1.Track);
            }
            if (withReceiver2)
            {
                Assert.IsNull(receiver2.Track);
            }

            // Connect
            Assert.IsTrue(sig.StartConnection());
            yield return(sig.WaitForConnection(millisecondsTimeout: 10000));

            Assert.IsTrue(sig.IsConnected);

            // Wait a frame so that the Unity events for streams started can propagate
            yield return(null);

            // Check pairing
            {
                bool hasSend1 = false;
                bool hasSend2 = false;
                bool hasRecv1 = false;
                bool hasRecv2 = false;

                // Local tracks exist if manually added (independently of negotiation)
                Assert.AreEqual(withSender1 ? 1 : 0, pc1.Peer.LocalVideoTracks.Count());
                Assert.AreEqual(withSender2 ? 1 : 0, pc2.Peer.LocalVideoTracks.Count());

                // Remote tracks exist if paired with a sender on the remote peer
                if (withReceiver1 && withSender2) // R <= S
                {
                    Assert.IsNotNull(receiver1.Track);
                    Assert.IsNotNull(ml2.SenderTrack);
                    hasRecv1 = true;
                    hasSend2 = true;
                }
                if (withSender1 && withReceiver2) // S => R
                {
                    Assert.IsNotNull(ml1.SenderTrack);
                    Assert.IsNotNull(receiver2.Track);
                    hasSend1 = true;
                    hasRecv2 = true;
                }
                Assert.AreEqual(hasRecv1 ? 1 : 0, pc1.Peer.RemoteVideoTracks.Count());
                Assert.AreEqual(hasRecv2 ? 1 : 0, pc2.Peer.RemoteVideoTracks.Count());

                // Transceivers are consistent with pairing
                Assert.IsTrue(ml1.Transceiver.NegotiatedDirection.HasValue);
                Assert.AreEqual(hasSend1, Transceiver.HasSend(ml1.Transceiver.NegotiatedDirection.Value));
                Assert.AreEqual(hasRecv1, Transceiver.HasRecv(ml1.Transceiver.NegotiatedDirection.Value));
                Assert.IsTrue(ml2.Transceiver.NegotiatedDirection.HasValue);
                Assert.AreEqual(hasSend2, Transceiver.HasSend(ml2.Transceiver.NegotiatedDirection.Value));
                Assert.AreEqual(hasRecv2, Transceiver.HasRecv(ml2.Transceiver.NegotiatedDirection.Value));
            }
        }
        public IEnumerator EnableAndDisableWithTracks()
        {
            var pc1_go = new GameObject("pc1");

            pc1_go.SetActive(false); // prevent auto-activation of components
            var pc1    = pc1_go.AddComponent <PeerConnection>();
            var pc2_go = new GameObject("pc2");

            pc2_go.SetActive(false); // prevent auto-activation of components
            var pc2 = pc2_go.AddComponent <PeerConnection>();

            // Create the signaler
            var sig_go = new GameObject("signaler");
            var sig    = sig_go.AddComponent <LocalOnlySignaler>();

            sig.Peer1 = pc1;
            sig.Peer2 = pc2;

            // Create the video source on peer #1
            VideoTrackSource source1   = pc1_go.AddComponent <UniformColorVideoSource>();
            VideoReceiver    receiver1 = pc1_go.AddComponent <VideoReceiver>();
            MediaLine        ml1       = pc1.AddMediaLine(MediaKind.Video);

            ml1.SenderTrackName = "video_track_1";
            ml1.Source          = source1;
            ml1.Receiver        = receiver1;

            // Create the video source on peer #2
            VideoTrackSource source2   = pc2_go.AddComponent <UniformColorVideoSource>();
            VideoReceiver    receiver2 = pc2_go.AddComponent <VideoReceiver>();
            MediaLine        ml2       = pc2.AddMediaLine(MediaKind.Video);

            ml2.SenderTrackName = "video_track_2";
            ml2.Source          = source2;
            ml2.Receiver        = receiver2;

            // Init/quit twice.
            for (int i = 0; i < 2; ++i)
            {
                // Initialize
                yield return(InitializeAndWait(pc1));

                yield return(InitializeAndWait(pc2));

                // Confirm the sources are ready.
                Assert.IsTrue(source1.IsLive);
                Assert.IsTrue(source2.IsLive);

                // Sender tracks will be created on connection.
                Assert.IsNull(ml1.LocalTrack);
                Assert.IsNull(ml2.LocalTrack);

                // Connect
                Assert.IsTrue(sig.StartConnection());
                yield return(sig.WaitForConnection(millisecondsTimeout: 10000));

                Assert.IsTrue(sig.IsConnected);

                // Wait a frame so that the Unity events for streams started can propagate
                yield return(null);

                // Check pairing
                Assert.IsNotNull(receiver1.Transceiver);
                Assert.IsTrue(receiver1.IsLive);
                Assert.AreEqual(1, pc1.Peer.RemoteVideoTracks.Count());
                Assert.IsNotNull(receiver2.Transceiver);
                Assert.IsTrue(receiver2.IsLive);
                Assert.AreEqual(1, pc2.Peer.RemoteVideoTracks.Count());

                // Shutdown peer #1
                pc1.enabled = false;
                Assert.IsNull(pc1.Peer);

                // We cannot reliably detect remote shutdown, so only check local peer.
                VerifyLocalShutdown(ml1);

                // Shutdown peer #2
                pc2.enabled = false;
                Assert.IsNull(pc2.Peer);

                VerifyLocalShutdown(ml2);
            }
            UnityEngine.Object.Destroy(pc1_go);
            UnityEngine.Object.Destroy(pc2_go);
            UnityEngine.Object.Destroy(sig_go);
        }
示例#15
0
        public IEnumerator SwapReceiver()
        {
            // Create the peer connections
            var pc1_go = new GameObject("pc1");

            pc1_go.SetActive(false); // prevent auto-activation of components
            var pc1    = pc1_go.AddComponent <PeerConnection>();
            var pc2_go = new GameObject("pc2");

            pc2_go.SetActive(false); // prevent auto-activation of components
            var pc2 = pc2_go.AddComponent <PeerConnection>();

            // Batch changes manually
            pc1.AutoCreateOfferOnRenegotiationNeeded = false;
            pc2.AutoCreateOfferOnRenegotiationNeeded = false;

            // Create the signaler
            var sig_go = new GameObject("signaler");
            var sig    = sig_go.AddComponent <LocalOnlySignaler>();

            sig.Peer1 = pc1;
            sig.Peer2 = pc2;

            // Create the video source on peer #1
            {
                VideoTrackSource source   = pc1_go.AddComponent <UniformColorVideoSource>();
                MediaLine        senderMl = pc1.AddMediaLine(MediaKind.Video);
                senderMl.SenderTrackName = "video_track_1";
                senderMl.Source          = source;
            }

            // Create the receivers on peer #2
            VideoReceiver receiver1 = pc2_go.AddComponent <VideoReceiver>();
            VideoReceiver receiver2 = pc2_go.AddComponent <VideoReceiver>();
            MediaLine     ml        = pc2.AddMediaLine(MediaKind.Video);

            ml.Receiver = receiver1;

            // Initialize
            yield return(PeerConnectionTests.InitializeAndWait(pc1));

            yield return(PeerConnectionTests.InitializeAndWait(pc2));

            // Connect
            Assert.IsTrue(sig.StartConnection());
            yield return(sig.WaitForConnection(millisecondsTimeout: 10000));

            // Wait a frame so that the Unity events for streams started can propagate
            yield return(null);

            // receiver1 is correctly wired.
            Assert.AreEqual(ml.Transceiver.DesiredDirection, Transceiver.Direction.ReceiveOnly);
            Assert.AreEqual(pc2.Peer.RemoteVideoTracks.Count(), 1);
            Assert.IsTrue(receiver1.IsLive);
            Assert.AreEqual(receiver1.Track, ml.Transceiver.RemoteTrack);
            Assert.AreEqual(receiver1.MediaLine, ml);

            // Reset receiver
            ml.Receiver = null;

            // receiver1 has been detached.
            Assert.AreEqual(ml.Transceiver.DesiredDirection, Transceiver.Direction.Inactive);
            Assert.IsFalse(receiver1.IsLive);
            Assert.IsNull(receiver1.MediaLine);

            // Set receiver2.
            ml.Receiver = receiver2;

            // receiver2 is correctly wired.
            Assert.AreEqual(ml.Transceiver.DesiredDirection, Transceiver.Direction.ReceiveOnly);
            Assert.AreEqual(pc2.Peer.RemoteVideoTracks.Count(), 1);
            Assert.IsTrue(receiver2.IsLive);
            Assert.AreEqual(receiver2.Track, ml.Transceiver.RemoteTrack);
            Assert.AreEqual(receiver2.MediaLine, ml);

            // Swap receiver2 with receiver1.
            ml.Receiver = receiver1;

            // receiver1 is correctly wired.
            Assert.AreEqual(ml.Transceiver.DesiredDirection, Transceiver.Direction.ReceiveOnly);
            Assert.AreEqual(pc2.Peer.RemoteVideoTracks.Count(), 1);
            Assert.IsTrue(receiver1.IsLive);
            Assert.AreEqual(receiver1.Track, ml.Transceiver.RemoteTrack);
            Assert.AreEqual(receiver1.MediaLine, ml);

            // receiver2 has been detached.
            Assert.IsFalse(receiver2.IsLive);
            Assert.IsNull(receiver2.MediaLine);

            Object.Destroy(pc1_go);
            Object.Destroy(pc2_go);
        }
示例#16
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();
            }
        }