Exemple #1
0
 private void _setup()
 {
     Done = true;
     _endPoint = new IPEndPoint(IPAddress.Any, Port);
     _udpSocket = new UdpSocket();
     _udpSocket.Bind(_endPoint);
 }
Exemple #2
0
        public void Unpack(UdpStream buffer, UdpSocket socket)
        {
            buffer.Position = 0;

            ObjSequence = TrimSequence(buffer.ReadUShort(SEQ_BITS + SEQ_PADD));
            AckSequence = TrimSequence(buffer.ReadUShort(SEQ_BITS + SEQ_PADD));
            AckHistory = buffer.ReadULong(UdpSocket.AckRedundancy);

            if (UdpSocket.CalculateNetworkPing) {
                AckTime = buffer.ReadUShort(NETPING_BITS);
            }
        }
Exemple #3
0
        /// <summary>
        /// Creates a new instance of the <see cref="OutClient"/> class with the specified timeout.
        /// </summary>
        /// <param name="timeout">The timeout period for the socket.</param>
        protected OutClient(TimeSpan timeout) {
            udpSocket = new UdpSocket();
            udpSocket.PacketDataReceived += new EventHandler<PacketDataEventArgs>(udpSocket_PacketDataReceived);
            udpSocket.SocketError += new EventHandler<InSimErrorEventArgs>(udpSocket_SocketError);

            Timeout = timeout;
            if (timeout > TimeSpan.Zero) {
                timeoutTimer = new Timer();
                timeoutTimer.Interval = timeout.TotalMilliseconds;
                timeoutTimer.AutoReset = false;
                timeoutTimer.Elapsed += new ElapsedEventHandler(timeoutTimer_Elapsed);
            }
        }
Exemple #4
0
        public void Unpack(UdpBitStream buffer, UdpSocket socket)
        {
            ObjSequence = TrimSequence(buffer.ReadUShort(16));
            AckSequence = TrimSequence(buffer.ReadUShort(16));
            AckHistory = buffer.ReadULong(socket.Config.AckRedundancy);

            if (socket.Config.CalculateNetworkPing) {
                AckTime = buffer.ReadUShort(16);
            }

            if (socket.Config.WritePacketBitSize) {
                BitSize = buffer.ReadUShort(16);
            }
        }
Exemple #5
0
        public void Pack(UdpBitStream buffer, UdpSocket socket)
        {
            buffer.WriteUShort(PadSequence(ObjSequence), 16);
            buffer.WriteUShort(PadSequence(AckSequence), 16);
            buffer.WriteULong(AckHistory, socket.Config.AckRedundancy);

            if (socket.Config.CalculateNetworkPing) {
                buffer.WriteUShort(AckTime, 16);
            }

            if (socket.Config.WritePacketBitSize) {
                buffer.WriteUShort(BitSize, 16);
            }
        }
Exemple #6
0
        public void Pack(UdpStream buffer, UdpSocket socket)
        {
            int pos = buffer.Position;

            buffer.Position = 0;
            buffer.WriteUShort(PadSequence(ObjSequence), SEQ_BITS + SEQ_PADD);
            buffer.WriteUShort(PadSequence(AckSequence), SEQ_BITS + SEQ_PADD);
            buffer.WriteULong(AckHistory, UdpSocket.AckRedundancy);

            if (UdpSocket.CalculateNetworkPing) {
                buffer.WriteUShort(AckTime, NETPING_BITS);
            }

            buffer.Position = pos;
        }
Exemple #7
0
        public void Pack(UdpStream buffer, UdpSocket socket, bool sendNow)
        {
            int pos = buffer.Position;

            sendNow &= buffer.CanWrite (32);
            if (sendNow)
            {
                buffer.WriteUInt (this.Now);
                pos = buffer.Position;
            }

            buffer.Position = 0;
            buffer.WriteUShort(PadSequence(ObjSequence), SEQ_BITS + SEQ_PADD);
            PackAckSequence (buffer, sendNow);
            buffer.WriteULong(AckHistory, UdpSocket.AckRedundancy);

            if (UdpSocket.CalculateNetworkPing) {
                buffer.WriteUShort(AckTime, NETPING_BITS);
            }

            buffer.Position = pos;
        }
Exemple #8
0
        /// <summary>
        /// Constructor that binds this object instance to an IPEndPoint.  If you need to change 
        /// IPEndPoint dynamically, Dispose and recreate a new object.
        /// </summary>
        /// <param name="endPoint">IPEndPoint where we should be listening for IP Multicast packets.</param>
        /// <param name="TimeoutMilliseconds">Milliseconds before lack of a packet == a Network Timeout</param>
        /// <example>
        /// ...
        /// UdpReceiver mcListener = new UdpReceiver(endPoint1);
        /// mcListener.Receive(packetBuffer);
        /// mcListener.Dispose();
        ///
        /// UdpReceiver mcListener = new UdpReceiver(endPoint2);
        /// mcListener.Receive(packetBuffer);
        /// mcListener.Dispose();
        ///
        /// mcListener = null;
        /// ...
        /// </example>
        public UdpReceiver(IPEndPoint endPoint, int timeoutMilliseconds)
        {
            this.MulticastEP = endPoint;
            this.disposed = false;
            this.fSocket = null;
            externalInterface = Utility.GetLocalRoutingInterface(endPoint.Address, endPoint.Port);

            //IPAddress ipa = IPAddress.Parse("192.0.0.11");
            //int ad = (int)ipa.Address;
            //s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, ad);


            // Create the socket
            this.fSocket = new UdpSocket(endPoint.AddressFamily);


            if (Utility.IsMulticast(endPoint.Address))
            {
                // Allow multiple binds to this socket, as it will still function properly
                //  (this is only the case if it is a multicast socket.  Unicast sockets fail to
                //   receive all data on all sockets)
                //fSocket.ExclusiveAddressUse = false;
                fSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            }

            // Bind to the socket before joining a multicast group
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, endPoint.Port);
            EndPoint localEndpoint = (EndPoint)iep;
            fSocket.Bind(localEndpoint);

            try
            {
                // Join the multicast group
                // This allows the kernel to inform routers that packets meant
                // for this group should come here.
                if (Utility.IsMulticast(endPoint.Address))
                {
                    if (endPoint.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        // Join the IPv6 Multicast group
                        fSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
                            new IPv6MulticastOption(endPoint.Address));
                    }
                    else
                    {
                        // Join the IPv4 Multicast group
                        MulticastOption mcOption = new MulticastOption(this.MulticastEP.Address);
                        fSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcOption);
                        
                        // The following is hinted at by MSDN, but is wrong
                        // The SocketOptionLevel needs to be 'IP', not 'Udp'
                        //fSocket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.AddMembership, mcOption);
                    }
                }

                // Set the timeout on the socket
                if (timeoutMilliseconds > 0)
                    fSocket.ReceiveTimeout = timeoutMilliseconds;
                //fSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeoutMilliseconds);

                // Make room for 80 packets plus some overhead
                //fSocket.ReceiveBufferSize = UDP.MTU * 80;
                //fSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, UDP.MTU * 80);
            }
            catch (SocketException sockex)
            {
                Console.WriteLine(sockex.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                this.Dispose();
                throw;
            }
        }
Exemple #9
0
 public void setSendBufferSize(UdpSocket fan, long v)
 {
     m_sendBufferSize = v;
 }
Exemple #10
0
 public UdpHandler(UdpSocket socket, ProudServer server)
 {
     _socket = socket;
     _server = server;
 }
 public static MessageInbound In(this UdpSocket udpSocket, BinaryParsing binaryParsing)
 {
     return(new MessageInbound(udpSocket, binaryParsing));
 }
Exemple #12
0
 public void setReceiveTimeout(UdpSocket fan, Duration v)
 {
     m_receiveTimeout = (v == null) ? 0 : (int)v.millis();
 }
Exemple #13
0
 public static int GetSize(UdpSocket socket)
 {
     return 16 + 16 + socket.Config.AckRedundancy + (socket.Config.CalculateNetworkPing ? 16 : 0) + (socket.Config.WritePacketBitSize ? 16 : 0);
 }
Exemple #14
0
 public long getReceiveBufferSize(UdpSocket fan)
 {
     return(m_receiveBufferSize);
 }
Exemple #15
0
 public UdpService(int targetPort, string targetHost)
 {
     //for client
     client = new UdpSocket(new IPEndPoint(IPAddress.Parse(targetHost), targetPort));
 }
Exemple #16
0
 public bool isConnected(UdpSocket fan)
 {
     return((m_dotnet == null) ? false : m_dotnet.Connected);
 }
Exemple #17
0
 public bool isClosed(UdpSocket fan)
 {
     return(m_closed);
 }
Exemple #18
0
        //////////////////////////////////////////////////////////////////////////
        // State
        //////////////////////////////////////////////////////////////////////////

        public bool isBound(UdpSocket fan)
        {
            return((m_dotnet == null) ? false : m_dotnet.IsBound);
        }
Exemple #19
0
 public void setTrafficClass(UdpSocket fan, long v)
 {
     m_trafficClass = v;
 }
Exemple #20
0
 public long getTrafficClass(UdpSocket fan)
 {
     return(m_trafficClass);
 }
Exemple #21
0
 public long getSendBufferSize(UdpSocket fan)
 {
     return(m_sendBufferSize);
 }
Exemple #22
0
 public bool getReuseAddr(UdpSocket fan)
 {
     return(m_reuseAddr);
 }
Exemple #23
0
 public SocketObject()
 {
     socket = UdpSocket.Create<UdpPlatformManaged, Serializer>(new UdpConfig { SimulatedLoss = 0.25f, ConnectionTimeout = 100000000, PingTimeout = 10, ConnectionLimit = -1 });
 }
    public void Ping(UdpSocket udpSocket)
    {
        int senderSessionId = -1;
        int pingCount       = 0;

        while (true)
        {
            bool initialized = false;
            udpSocket.Send(PacketHelper.createPingReceiverPacketBytes());
            ++pingCount;
            UnityEngine.Debug.Log("Sent ping");

            //Thread.Sleep(100);
            Thread.Sleep(300);

            SocketError error = SocketError.WouldBlock;
            while (true)
            {
                var packet = udpSocket.Receive(out error);
                if (packet == null)
                {
                    break;
                }

                int cursor    = 0;
                int sessionId = BitConverter.ToInt32(packet, cursor);
                cursor += 4;

                var packetType = (SenderPacketType)packet[cursor];
                cursor += 1;
                if (packetType != SenderPacketType.Init)
                {
                    UnityEngine.Debug.Log($"A different kind of a packet received before an init packet: {packetType}");
                    continue;
                }

                senderSessionId = sessionId;

                var initSenderPacketData = InitSenderPacketData.Parse(packet);

                textureGroup.SetWidth(initSenderPacketData.depthWidth);
                textureGroup.SetHeight(initSenderPacketData.depthHeight);
                PluginHelper.InitTextureGroup();

                colorDecoder = new Vp8Decoder();
                depthDecoder = new TrvlDecoder(initSenderPacketData.depthWidth * initSenderPacketData.depthHeight);

                azureKinectScreen.Setup(initSenderPacketData);

                initialized = true;
                break;
            }
            if (initialized)
            {
                break;
            }

            if (pingCount == 10)
            {
                UnityEngine.Debug.Log("Tried pinging 10 times and failed to received an init packet...\n");
                return;
            }
        }

        this.udpSocket = udpSocket;
        var videoPacketDataQueue = new ConcurrentQueue <VideoSenderPacketData>();
        var fecPacketDataQueue   = new ConcurrentQueue <FecSenderPacketData>();
        var audioPacketDataQueue = new ConcurrentQueue <AudioSenderPacketData>();

        var taskThread = new Thread(() =>
        {
            var receiveSenderPacketTask    = new ReceiveSenderPacketTask();
            var reassembleVideoMessageTask = new ReassembleVideoMessageTask();
            var consumeAudioPacketTask     = new ConsumeAudioPacketTask();

            while (!receiverStopped)
            {
                receiveSenderPacketTask.Run(this,
                                            senderSessionId,
                                            videoPacketDataQueue,
                                            fecPacketDataQueue,
                                            audioPacketDataQueue);
                reassembleVideoMessageTask.Run(this, videoPacketDataQueue, fecPacketDataQueue);
                consumeAudioPacketTask.Run(this, audioPacketDataQueue);
            }

            receiverStopped = true;
        });

        taskThread.Start();
    }
Exemple #25
0
 public InvokeHelper(UdpSocket sock, DatagramReceiveEventArgs e)
 {
     _sock = sock;
     _e = e;
 }
    public void UpdateFrame(UdpSocket udpSocket, SortedDictionary <int, VideoSenderMessage> videoMessages)
    {
        if (State != PrepareState.Prepared)
        {
            Debug.Log("TextureGroupUpdater is not prepared yet...");
            return;
        }

        int?frameIdToRender = null;

        if (lastFrameId == -1)
        {
            // For the first frame, find a keyframe.
            foreach (var videoMessagePair in videoMessages)
            {
                if (videoMessagePair.Value.keyframe)
                {
                    frameIdToRender = videoMessagePair.Key;
                    break;
                }
            }
        }
        else
        {
            // If there is a key frame, use the most recent one.
            foreach (var videoMessagePair in videoMessages)
            {
                if (videoMessagePair.Key <= lastFrameId)
                {
                    continue;
                }

                if (videoMessagePair.Value.keyframe)
                {
                    frameIdToRender = videoMessagePair.Key;
                }
            }

            // Find if there is the next frame.
            if (!frameIdToRender.HasValue)
            {
                if (videoMessages.ContainsKey(lastFrameId + 1))
                {
                    frameIdToRender = lastFrameId + 1;
                }
            }
        }

        if (!frameIdToRender.HasValue)
        {
            return;
        }

        var         videoMessage = videoMessages[frameIdToRender.Value];
        AVFrame     avFrame      = colorDecoder.Decode(videoMessage.colorEncoderFrame);
        DepthPixels depthPixels  = depthDecoder.Decode(videoMessage.depthEncoderFrame, videoMessage.keyframe);

        lastFrameId = frameIdToRender.Value;

        udpSocket.Send(PacketUtils.createReportReceiverPacketBytes(receiverId, lastFrameId).bytes, senderEndPoint);

        textureSet.SetAvFrame(avFrame);
        textureSet.SetDepthPixels(depthPixels);
        TelepresenceToolkitPlugin.UpdateTextureGroup(textureSet.GetId());
    }
Exemple #27
0
 public UdpService(int bindPort, int targetPort)
 {
     //for serverside
     client = new UdpSocket(new IPEndPoint(IPAddress.Any, targetPort), bindPort);
 }
Exemple #28
0
 public void setReuseAddr(UdpSocket fan, bool v)
 {
     m_reuseAddr = v;
 }
Exemple #29
0
    public bool UpdateFrame(MonoBehaviour monoBehaviour, UdpSocket udpSocket, SenderPacketSet senderPacketSet)
    {
        // UpdateFrame() should not be called before Prepare().
        Assert.AreEqual(PrepareState.Prepared, State);

        var videoMessageList = new List <Tuple <int, VideoSenderMessageData> >();

        try
        {
            if (heartbeatStopWatch.Elapsed.TotalSeconds > HEARTBEAT_INTERVAL_SEC)
            {
                udpSocket.Send(PacketHelper.createHeartbeatReceiverPacketBytes(ReceiverSessionId), SenderEndPoint);
                heartbeatStopWatch = Stopwatch.StartNew();
            }

            if (senderPacketSet.ReceivedAny)
            {
                // Use init packet to prepare rendering video messages.
                if (senderPacketSet.InitPacketDataList.Count > 0)
                {
                    if (KinectOrigin.Screen.State == PrepareState.Unprepared)
                    {
                        KinectOrigin.Screen.StartPrepare(senderPacketSet.InitPacketDataList[0]);
                        TextureGroupUpdater.StartPrepare(monoBehaviour, senderPacketSet.InitPacketDataList[0]);
                    }
                }

                videoMessageAssembler.Assemble(udpSocket,
                                               senderPacketSet.VideoPacketDataList,
                                               senderPacketSet.FecPacketDataList,
                                               TextureGroupUpdater.lastVideoFrameId,
                                               videoMessageList);
                audioPacketReceiver.Receive(senderPacketSet.AudioPacketDataList, KinectOrigin.Speaker.RingBuffer);
                receivedAnyStopWatch = Stopwatch.StartNew();
            }
            else
            {
                if (receivedAnyStopWatch.Elapsed.TotalSeconds > HEARTBEAT_TIME_OUT_SEC)
                {
                    UnityEngine.Debug.Log($"Timed out after waiting for {HEARTBEAT_TIME_OUT_SEC} seconds without a received packet.");
                    return(false);
                }
            }
        }
        catch (UdpSocketException e)
        {
            UnityEngine.Debug.Log($"UdpSocketRuntimeError: {e}");
            return(false);
        }

        if (KinectOrigin.Screen.State == PrepareState.Preparing)
        {
            KinectOrigin.SetProgressText(SenderEndPoint, KinectOrigin.screen.Progress);
            KinectOrigin.ProgressTextVisibility = true;
        }
        else if (KinectOrigin.Screen.State == PrepareState.Prepared)
        {
            KinectOrigin.ProgressTextVisibility = false;
        }

        KinectOrigin.UpdateFrame(senderPacketSet.FloorPacketDataList);
        TextureGroupUpdater.UpdateFrame(udpSocket, videoMessageList);

        return(true);
    }
 public MainWindow()
 {
     InitializeComponent();
     UdpSocket = new UdpSocket();
     UdpSocket.Start(10086);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToStart(object sender, ElapsedEventArgs e)
        {
#if _VERSION_00_
            try
            {
                _Comm = new UdpSocket(_Settings.Ip, _Settings.Port);
                _Comm.NewDataEvent += OnNewData;
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                _Logger.DebugException(ex.Message, ex);
            }

            _State.LocalNode.ValidAdapters = GetAdaptersState();
            if (_State.LocalNode.ValidAdapters > 0)
            {
                if (!ExistClusterAddresses(false))
                {
                    _State.LocalNode.SetState(NodeState.Activating, Resources.LocalActivateAsk);
                }
                else
                {
                    _State.LocalNode.SetState(NodeState.NoActive, Resources.FoundClusterIps);
                }
            }
            else
            {
                _State.LocalNode.SetState(NodeState.NoActive, Resources.DeactivateByNotAdapters);
            }

            if (_Comm != null)
            {
                _Comm.BeginReceive();
            }

            _PeriodicTasks.Enabled = true;
#else
            // 20170925. No arranca hasta que no consigue que se active la LAN Interna.
            // Se considera que hay red si se completa favorablemente toda la inicializacion ...

            // 20171019. Este parte del timer se ejecutará periodicamente hasta que se inicie la red interna...
            LogHelper.Log(LogLevel.Info, "ToStart TICK");
            try
            {
                _Comm = new UdpSocket(_Settings.Ip, _Settings.Port);
                _Comm.NewDataEvent += OnNewData;
                _Comm.BeginReceive();
                LogHelper.Log(LogLevel.Info, "Red Interna Disponible...");
            }
            catch (Exception x)
            {
                LogHelper.Log(LogLevel.Error, x.Message);
                // Rearranco este timer...
                _ToStart.Enabled = true;
            }

            try
            {
                // 20171019. Esta parte del timer solo se ejecuta la primera vez...Si no hay errores internos...
                if (_State.LocalNode.State == NodeState.NoValid)
                {
                    // 20171019. Fuerzo el borrado de la IP virtual...
                    ForceDeleteVirtualAddress();
                    /////////////////////////////////////////////////
                    _State.LocalNode.ValidAdapters = GetAdaptersState();
                    if (_State.LocalNode.ValidAdapters > 0)
                    {
                        if (!ExistClusterAddresses(false))
                        {
                            _State.LocalNode.SetState(NodeState.Activating, Resources.LocalActivateAsk);
                        }
                        else
                        {
                            _State.LocalNode.SetState(NodeState.NoActive, Resources.FoundClusterIps);
                        }
                    }
                    else
                    {
                        _State.LocalNode.SetState(NodeState.NoActive, Resources.DeactivateByNotAdapters);
                    }

                    _PeriodicTasks.Enabled = true;
                }
            }
            catch (Exception x)
            {
                LogHelper.Log(LogLevel.Error, x.Message);

                // Rearranco este timer...
                _ToStart.Enabled = true;
            }
#endif
        }
        /// <summary>
        /// This thread function measures server latency every
        /// MEASUREMENT_INTERVAL milliseconds.
        ///
        /// Note that, because this function does not execute from a script
        /// context, it cannot call script functions.  Instead, a companion
        /// DelayCommand continuation on the main server thread will check the
        /// current latency value and save it as appropriate.
        /// </summary>
        private static void LatencyMeasurementThreadRoutine()
        {
            byte[]     PingMessage = { (byte)'B', (byte)'N', (byte)'L', (byte)'M', 0, 0, 0, 0, 0, 0, 0 };
            byte[]     Response;
            IPEndPoint SourceEndpoint = new IPEndPoint(0, 0);

            for (; ;)
            {
                //
                // Flush the socket receive queue.
                //

                UdpSocket.Client.ReceiveTimeout = 1;

                try
                {
                    for (;;)
                    {
                        UdpSocket.Receive(ref SourceEndpoint);
                    }
                }
                catch
                {
                }

                //
                // Now send a ping message and wait for a response or timeout.
                //

                UdpSocket.Client.ReceiveTimeout = MAX_PING;

                try
                {
                    uint Tick = (uint)Environment.TickCount;

                    UdpSocket.Send(PingMessage, PingMessage.Length);
                    Response = UdpSocket.Receive(ref SourceEndpoint);

                    Tick = (uint)Environment.TickCount - Tick;

                    if (Response.Length < 4 || Response[0] != (byte)'B' || Response[1] != (byte)'N' || Response[2] != (byte)'L' || Response[3] != (byte)'R')
                    {
                        throw new ApplicationException("Invalid BNLM response message received.");
                    }

                    //
                    // Report the response time.
                    //

                    lock (CurrentLatencyLock)
                    {
                        CurrentLatency = (int)Tick;
                    }
                }
                catch
                {
                    //
                    // Report a response time of -1 to indicate that no
                    // measurement could be taken.
                    //

                    lock (CurrentLatencyLock)
                    {
                        CurrentLatency = (int)-1;
                    }
                }

                Thread.Sleep(MEASUREMENT_INTERVAL);
            }
        }
Exemple #33
0
    public void UpdateFrame(UdpSocket udpSocket, List <Tuple <int, VideoSenderMessageData> > videoMessageList)
    {
        // If texture is not created, create and assign them to quads.
        if (!prepared)
        {
            // Check whether the native plugin has Direct3D textures that
            // can be connected to Unity textures.
            if (textureGroup.IsInitialized())
            {
                // TextureGroup includes Y, U, V, and a depth texture.
                azureKinectScreenMaterial.SetTexture("_YTex", textureGroup.GetYTexture());
                azureKinectScreenMaterial.SetTexture("_UvTex", textureGroup.GetUvTexture());
                azureKinectScreenMaterial.SetTexture("_DepthTex", textureGroup.GetDepthTexture());

                prepared = true;

                UnityEngine.Debug.Log("textureGroup intialized");
            }
        }

        {
            foreach (var frameMessagePair in videoMessageList)
            {
                // C# Dictionary throws an error when you add an element with
                // a key that is already taken.
                if (videoMessages.ContainsKey(frameMessagePair.Item1))
                {
                    continue;
                }

                videoMessages.Add(frameMessagePair.Item1, frameMessagePair.Item2);
            }
        }

        if (videoMessages.Count == 0)
        {
            return;
        }

        int?beginFrameId = null;

        // If there is a key frame, use the most recent one.
        foreach (var frameMessagePair in videoMessages)
        {
            if (frameMessagePair.Key <= lastVideoFrameId)
            {
                continue;
            }

            if (frameMessagePair.Value.keyframe)
            {
                beginFrameId = frameMessagePair.Key;
            }
        }

        // When there is no key frame, go through all the frames to check
        // if there is the one right after the previously rendered one.
        if (!beginFrameId.HasValue)
        {
            if (videoMessages.ContainsKey(lastVideoFrameId + 1))
            {
                beginFrameId = lastVideoFrameId + 1;
            }
            else
            {
                // Wait for more frames if there is way to render without glitches.
                return;
            }
        }

        // ffmpegFrame and trvlFrame are guaranteed to be non-null
        // since the existence of beginIndex's value.
        FFmpegFrame ffmpegFrame = null;
        TrvlFrame   trvlFrame   = null;

        var decoderStopWatch = Stopwatch.StartNew();

        for (int i = beginFrameId.Value; ; ++i)
        {
            if (!videoMessages.ContainsKey(i))
            {
                break;
            }

            var frameMessage = videoMessages[i];
            lastVideoFrameId = i;

            var colorEncoderFrame = frameMessage.colorEncoderFrame;
            var depthEncoderFrame = frameMessage.depthEncoderFrame;

            ffmpegFrame = colorDecoder.Decode(colorEncoderFrame);
            trvlFrame   = depthDecoder.Decode(depthEncoderFrame, frameMessage.keyframe);
        }

        decoderStopWatch.Stop();
        var decoderTime = decoderStopWatch.Elapsed;

        frameStopWatch.Stop();
        var frameTime = frameStopWatch.Elapsed;

        frameStopWatch = Stopwatch.StartNew();

        udpSocket.Send(PacketHelper.createReportReceiverPacketBytes(sessionId,
                                                                    lastVideoFrameId,
                                                                    (float)decoderTime.TotalMilliseconds,
                                                                    (float)frameTime.TotalMilliseconds), endPoint);

        // Invokes a function to be called in a render thread.
        if (prepared)
        {
            //Plugin.texture_group_set_ffmpeg_frame(textureGroup, ffmpegFrame.Ptr);
            textureGroup.SetFFmpegFrame(ffmpegFrame);
            //Plugin.texture_group_set_depth_pixels(textureGroup, trvlFrame.Ptr);
            textureGroup.SetTrvlFrame(trvlFrame);
            PluginHelper.UpdateTextureGroup(textureGroup.GetId());
        }

        // Remove frame messages before the rendered frame.
        var frameMessageKeys = new List <int>();

        foreach (int key in videoMessages.Keys)
        {
            frameMessageKeys.Add(key);
        }
        foreach (int key in frameMessageKeys)
        {
            if (key < lastVideoFrameId)
            {
                videoMessages.Remove(key);
            }
        }
    }
Exemple #34
0
 private void Start()
 {
     udpSocket             = FindObjectOfType <UdpSocket>();
     sendToPythonText.text = "Send Number: " + numToSendToPython.ToString();
 }
Exemple #35
0
 internal ClientConnectionImpl(int id, UdpSocket socket, ServerConnectSettings settings, Encryptor encryptor, EncryptorGenerator encryptorGenerator) : base(socket, encryptorGenerator)
 {
     SelfId   = id;
     m_UseP2P = settings.UseP2P;
     m_PeerManager.Add(new PeerEntry(id, 0, encryptor, settings.EndPoint));
 }
Exemple #36
0
 public static void Send(byte[] data, IPEndPoint remote)
 {
     UdpSocket.SendTo(data, remote);
 }
Exemple #37
0
        static void Server(int count)
        {
            UdpSocket[] sockets = new UdpSocket[count];

            for (int i = 0; i < count; ++i) {
                sockets[i] = UdpSocket.Create<UdpPlatformManaged, DummySerializer>();
                sockets[i].Start(new UdpEndPoint(UdpIPv4Address.Localhost, (ushort) (14000 + i)));
            }

            UdpSocketMultiplexer multiplexer = UdpSocket.CreateMultiplexer(sockets);

            while (true) {
                UdpEvent ev;
                UdpSocket socket;

                while (multiplexer.Poll(out ev, out socket)) {
                    UdpLog.User("Event raised {0}", ev.EventType);

                    switch (ev.EventType) {
                        case UdpEventType.Connected:
                            UdpLog.User("Client connected from {0}", ev.Connection.RemoteEndPoint);
                            break;
                    }
                }

                // Simulate ~60fps game loop
                Thread.Sleep(16);
            }
        }
Exemple #38
0
 public Server()
 {
     socket = UdpSocket.Create<UdpPlatformManaged, ChatSerializer>();
     socket.Start(new UdpEndPoint(UdpIPv4Address.Localhost, 14000));
     clients = new List<UdpConnection>();
 }
Exemple #39
0
 /// <summary>
 /// Dispose per the IDisposable pattern
 /// </summary>
 public void Dispose()
 {
     GC.SuppressFinalize(this);
     
     if(!disposed) 
     {
         disposed = true;
         if (fSocket != null)
         {
             UdpSocket.ReleaseSocket(MulticastEP, fSocket);
             //fSocket.Close();
             fSocket = null;
         }
     }
 }
Exemple #40
0
        internal UdpConnection(UdpSocket s, UdpConnectionMode m, UdpEndPoint ep)
        {
            socket = s;
            mode = m;
            endpoint = ep;
            stats = new UdpStats();
            networkRtt = socket.Config.DefaultNetworkPing;
            aliasedRtt = socket.Config.DefaultAliasedPing;
            mtu = socket.Config.PacketSize;
            alwaysSendMtu = socket.Config.DefaultAlwaysSendMtu;
            state = UdpConnectionState.Connecting;
            recvTime = socket.GetCurrentTime();
            sendTime = recvTime;
            sendWindow = new UdpRingBuffer<UdpHandle>(socket.Config.PacketWindow);

            this.networkPingFilterRttValues = new uint[socket.Config.NetworkPingMedianFilterSize];
            this.networkPingFilterSortedIndices = new int[socket.Config.NetworkPingMedianFilterSize];
            for (int i = 0; i < this.networkPingFilterSortedIndices.Length; ++i)
            {
                this.networkPingFilterSortedIndices[i] = i;
            }
            networkPingFilterNextIndexToReplace = 0;

            serializer = socket.CreateSerializer();
            serializer.Connection = this;
        }
Exemple #41
0
 public Client()
 {
     socket = UdpSocket.Create<UdpPlatformManaged, ChatSerializer>();
     socket.Start(UdpEndPoint.Any);
     socket.Connect(new UdpEndPoint(UdpIPv4Address.Localhost, 14000));
 }
Exemple #42
0
 public void setReceiveBufferSize(UdpSocket fan, long v)
 {
     m_receiveBufferSize = v;
 }
        internal UdpConnection(UdpSocket s, UdpConnectionMode m, UdpEndPoint ep)
        {
            socket = s;
            mode = m;
            endpoint = ep;
            stats = new UdpStats();
            networkRtt = socket.Config.DefaultNetworkPing;
            aliasedRtt = socket.Config.DefaultAliasedPing;
            mtu = socket.Config.PacketSize;
            alwaysSendMtu = socket.Config.DefaultAlwaysSendMtu;
            state = UdpConnectionState.Connecting;
            recvTime = socket.GetCurrentTime();
            sendTime = recvTime;
            sendWindow = new UdpRingBuffer<UdpHandle>(socket.Config.PacketWindow);

            serializer = socket.CreateSerializer();
            serializer.Connection = this;
        }
Exemple #44
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                string[] ports = SerialPort.GetPortNames();
                Console.WriteLine("COM port parameter not provided.");
                Console.WriteLine("Available serial ports: ");
                foreach (var serialPort in ports)
                {
                    Console.WriteLine(serialPort);
                }
                Console.ReadKey();
                return;
            }

            StreamUART uartStream = new StreamUART(args[0]);

            ncpInterface = new NcpInterface();

            try
            {
                ncpInterface.Open(uartStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                return;
            }

            // NetworkingInterface.SetupInterface(ncpInterface);

            Console.Write("Networkname:");
            string networkname = Console.ReadLine();

            Console.Write("Channel:");
            byte channel = Convert.ToByte(Console.ReadLine());

            Console.Write("Masterkey:");
            string masterkey = Console.ReadLine();

            Console.Write("Panid:");
            ushort panid = Convert.ToUInt16(Console.ReadLine());

            Console.Write("Listener port:");
            ushort port = Convert.ToUInt16(Console.ReadLine());

            try
            {
                ncpInterface.Form(networkname, channel, masterkey, panid);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                return;
            }

            UdpSocket receiver = new UdpSocket();

            receiver.Bind(IPv6Address.IPv6Any, port);
            IPv6EndPoint remoteIp = null;

            while (true)
            {
                if (receiver.Poll(-1, SelectMode.SelectRead))
                {
                    byte[] data    = receiver.Receive(ref remoteIp);
                    string message = Encoding.ASCII.GetString(data);
                    Console.WriteLine("\n");
                    Console.WriteLine("{0} bytes from {1} {2} {3}", message.Length, remoteIp.Address, remoteIp.Port, message);
                    Console.WriteLine(">");
                }
            }
        }
 private MessageInbound ReceivesMessages(UdpSocket udpSocket, BinaryParsing binaryParsing)
 {
     return(new MessageInbound(udpSocket, binaryParsing));
 }
Exemple #46
0
 public SocketObject()
 {
     socket = UdpSocket.Create <UdpPlatformManaged, Serializer>(new UdpConfig {
         SimulatedLoss = 0.25f, ConnectionTimeout = 100000000, PingTimeout = 10, ConnectionLimit = -1
     });
 }
Exemple #47
0
        //internal class SockInterfacePair
        //{
        //    internal UdpSocket sock;
        //    internal IPAddress extInterface;
        //    public bool Initialized;

        //    internal SockInterfacePair(UdpSocket sock, IPAddress extIntf)
        //    {
        //        this.sock = sock;
        //        this.extInterface = extIntf;
        //        Initialized = false;
        //    }
        //}


        // Apparently binding to the same ports on UDPSender and UDPListener causes problems in unicast.
        // Sharing the socket though, allows us to tunnel through firewalls as data is sent and received
        // on the same  endpoint.
        // This region of code enables sharing sockets between the two classes.

        //internal static SockInterfacePair GetSharedSocket(IPEndPoint endPoint)
        //{
        //    lock (socks)
        //    {
        //        object sockObj = socks[endPoint];
        //        if (sockObj != null)
        //        {
        //            SockInterfacePair sip = (SockInterfacePair)sockObj;
        //            ++sip.sock.refCount;

        //            return sip;
        //        }
        //        else
        //        {
        //            // Create the socket
        //            UdpSocket sock = new UdpSocket(endPoint.AddressFamily);

        //            // Get the External Interface, save it for future use
        //            IPAddress externalInterface = Utility.GetLocalRoutingInterface(endPoint.Address);

        //            if (externalInterface == null)
        //            {
        //                // Pri3: Do something more helpful here
        //                throw new Exception(Strings.UnableToFindLocalRoutingInterface);
        //            }

        //            if (Utility.IsMulticast(endPoint.Address))
        //            {
        //                // Allow multiple binds to this socket, as it will still function properly
        //                //  (this is only the case if it is a multicast socket.  Unicast sockets fail to
        //                //   receive all data on all sockets)
        //                sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, -1);

        //                // We don't join the multicast group here, because we may not want to listen
        //                // to our own data (halfing our throughput).  jasonv - 10/28/2004
        //            }

        //            // Add the socket to the hashtable
        //            SockInterfacePair sip = new SockInterfacePair(sock, externalInterface);
        //            socks.Add(endPoint, sip);

        //            // Increase the socket's reference count
        //            ++sock.refCount;

        //            return sip;
        //        }
        //    }
        //}

        //internal static void ReleaseSharedSocket(IPEndPoint endPoint, UdpSocket sock)
        //{
        //    object sockObj = socks[endPoint];
        //    if (sockObj == null)
        //        throw new InvalidOperationException(Strings.SockDoesNotExistAsASharedSocket);

        //    lock (socks)
        //    {
        //        if (--sock.refCount <= 0)
        //        {
        //            // Leave the multicast group
        //            if (Utility.IsMulticast(endPoint.Address))
        //            {
        //                try
        //                {
        //                    if (endPoint.AddressFamily == AddressFamily.InterNetworkV6)
        //                    {
        //                        IPv6MulticastOption mo = new IPv6MulticastOption(endPoint.Address);
        //                        sock.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, mo);
        //                    }
        //                    else
        //                    {
        //                        MulticastOption mo = new MulticastOption(endPoint.Address);
        //                        sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, mo);
        //                    }
        //                }
        //                catch { } // The user of the socket *may* not have joined the multicast group (?)
        //            }

        //            // Remove ourselves from the shared pool
        //            socks.Remove(endPoint);

        //            // Close the socket
        //            try
        //            {
        //                sock.Close();
        //            }
        //            catch (ObjectDisposedException) { }
        //        }
        //    }
        //}

        internal static void ReleaseSocket(IPEndPoint endPoint, UdpSocket sock)
        {
            // Leave the multicast group
            if (Utility.IsMulticast(endPoint.Address))
            {
                try
                {
                    if (endPoint.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        IPv6MulticastOption mo = new IPv6MulticastOption(endPoint.Address);
                        sock.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, mo);
                    }
                    else
                    {
                        MulticastOption mo = new MulticastOption(endPoint.Address);
                        sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, mo);
                    }
                }
                catch { } // The user of the socket *may* not have joined the multicast group (?)
            }

            // Close the socket
            try
            {
                sock.Close();
            }
            catch (ObjectDisposedException) { }
        }
Exemple #48
0
 public void setBroadcast(UdpSocket fan, bool v)
 {
     m_enableBroadcast = v;
 }