Пример #1
0
        public void DecodeMultipleFrequencyVoicePacket()
        {
            var encodedUdpVoicePacket = new byte[80] {
                80, 0, 6, 0, 30, 0, 0, 1, 2, 3,
                4, 5, 0, 0, 0, 0, 0, 0, 0, 128,
                233, 235, 173, 65, 0, 0, 0, 0, 0, 0,
                56, 156, 124, 65, 1, 0, 0, 0, 0, 128,
                233, 235, 173, 65, 0, 1, 1, 0, 0, 0,
                1, 0, 0, 0, 0, 0, 0, 0, 117, 102,
                89, 83, 95, 87, 108, 76, 86, 107, 109, 70,
                80, 106, 113, 67, 103, 120, 122, 54, 71, 65
            };

            var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedUdpVoicePacket);

            Assert.AreEqual("ufYS_WlLVkmFPjqCgxz6GA", udpVoicePacket.Guid);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4, 5 }, udpVoicePacket.AudioPart1Bytes);
            Assert.AreEqual(6, udpVoicePacket.AudioPart1Length);
            CollectionAssert.AreEqual(new double[] { 251000000, 30000000, 251000000 }, udpVoicePacket.Frequencies);
            Assert.AreEqual((uint)1, udpVoicePacket.UnitId);
            CollectionAssert.AreEqual(new byte[] { 0, 0, 1 }, udpVoicePacket.Encryptions);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 0 }, udpVoicePacket.Modulations);
            Assert.AreEqual((ulong)1, udpVoicePacket.PacketNumber);
            Assert.AreEqual((ushort)80, udpVoicePacket.PacketLength);
        }
        public void DecodeMultipleFrequencyVoicePacket()
        {
            var encodedUdpVoicePacket = new byte[99] {
                // Total packet length
                99, 0,
                // Length of audio part
                6, 0,
                // Length of frequencies part
                30, 0,
                // Audio part
                0, 1, 2, 3, 4, 5,
                // Radio frequency #1
                0, 0, 0, 128, 233, 235, 173, 65,
                // Radio modulation #1
                0,
                // Radio encryption #1
                0,
                // Radio frequency #2
                0, 0, 0, 0, 56, 156, 124, 65,
                // Radio modulation #2
                1,
                // Radio encryption #2
                0,
                // Radio frequency #3
                0, 0, 0, 128, 233, 235, 173, 65,
                // Radio modulation #3
                0,
                // Radio encryption #3
                1,
                // Unit ID
                1, 0, 0, 0,
                // Packet ID
                1, 0, 0, 0, 0, 0, 0, 0,
                254,
                // Transmission GUID
                117, 102, 89, 83, 95, 87, 108, 76, 86, 107, 109, 70, 80, 106, 113, 67, 103, 120, 122, 54, 71, 65,
                // Client GUID
                117, 102, 89, 83, 95, 87, 108, 76, 86, 107, 109, 70, 80, 106, 113, 67, 103, 120, 122, 54, 71, 65
            };

            var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedUdpVoicePacket);

            Assert.AreEqual("ufYS_WlLVkmFPjqCgxz6GA", udpVoicePacket.Guid);
            Assert.AreEqual("ufYS_WlLVkmFPjqCgxz6GA", udpVoicePacket.OriginalClientGuid);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4, 5 }, udpVoicePacket.AudioPart1Bytes);
            Assert.AreEqual(6, udpVoicePacket.AudioPart1Length);
            CollectionAssert.AreEqual(new double[] { 251000000, 30000000, 251000000 }, udpVoicePacket.Frequencies);
            Assert.AreEqual((uint)1, udpVoicePacket.UnitId);
            CollectionAssert.AreEqual(new byte[] { 0, 0, 1 }, udpVoicePacket.Encryptions);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 0 }, udpVoicePacket.Modulations);
            Assert.AreEqual((ulong)1, udpVoicePacket.PacketNumber);
            Assert.AreEqual((ushort)99, udpVoicePacket.PacketLength);

            Assert.AreEqual((byte)254, udpVoicePacket.RetransmissionCount);
        }
Пример #3
0
        public void DecodeInitialVoicePacket()
        {
            var encodedUdpVoicePacket = new byte[78] {
                // Total packet length
                78, 0,
                // Length of audio part
                6, 0,
                // Length of frequencies part
                9, 0,
                // Audio part
                0, 1, 2, 3, 4, 5,
                // Radio frequency #1
                0, 0, 0, 0, 0, 0, 89, 64,
                // Radio modulation #1
                4,
                // Unit ID
                1, 0, 0, 0,
                // Packet ID
                1, 0, 0, 0, 0, 0, 0, 0,
                //Retransmission Count,
                231,
                // Transmission GUID
                117, 102, 89, 83, 95, 87, 108, 76, 86, 107, 109, 70, 80, 106, 113, 67, 103, 120, 122, 54, 71, 65,
                // Client GUID
                117, 102, 89, 83, 95, 87, 108, 76, 86, 107, 109, 70, 80, 106, 113, 67, 103, 120, 122, 54, 71, 65
            };

            var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedUdpVoicePacket);

            Assert.AreEqual("ufYS_WlLVkmFPjqCgxz6GA", udpVoicePacket.Guid);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4, 5 }, udpVoicePacket.AudioPart1Bytes);
            Assert.AreEqual(6, udpVoicePacket.AudioPart1Length);
            CollectionAssert.AreEqual(new double[] { 100 }, udpVoicePacket.Frequencies);
            Assert.AreEqual((int)1, udpVoicePacket.UnitId);
            CollectionAssert.AreEqual(new byte[] { 4 }, udpVoicePacket.Modulations);
            Assert.AreEqual((ulong)1, udpVoicePacket.PacketNumber);
            Assert.AreEqual((ushort)78, udpVoicePacket.PacketLength);
            Assert.AreEqual((byte)231, udpVoicePacket.RetransmissionCount);
            Assert.AreEqual("ufYS_WlLVkmFPjqCgxz6GA", udpVoicePacket.OriginalClientGuid);
        }
Пример #4
0
        public void DecodeInitialVoicePacket()
        {
            var encodedUdpVoicePacket = new byte[60] {
                60, 0, 6, 0, 10, 0, 0, 1, 2, 3,
                4, 5, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 89, 64, 4, 0, 1, 0, 0, 0,
                1, 0, 0, 0, 0, 0, 0, 0, 117, 102,
                89, 83, 95, 87, 108, 76, 86, 107, 109, 70,
                80, 106, 113, 67, 103, 120, 122, 54, 71, 65
            };

            var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedUdpVoicePacket);

            Assert.AreEqual("ufYS_WlLVkmFPjqCgxz6GA", udpVoicePacket.Guid);
            CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4, 5 }, udpVoicePacket.AudioPart1Bytes);
            Assert.AreEqual(6, udpVoicePacket.AudioPart1Length);
            CollectionAssert.AreEqual(new double[] { 100 }, udpVoicePacket.Frequencies);
            Assert.AreEqual((uint)1, udpVoicePacket.UnitId);
            CollectionAssert.AreEqual(new byte[] { 0 }, udpVoicePacket.Encryptions);
            CollectionAssert.AreEqual(new byte[] { 4 }, udpVoicePacket.Modulations);
            Assert.AreEqual((ulong)1, udpVoicePacket.PacketNumber);
            Assert.AreEqual((ushort)60, udpVoicePacket.PacketLength);
        }
        private void UdpAudioDecode()
        {
            try
            {
                while (!_stop)
                {
                    try
                    {
                        var encodedOpusAudio = new byte[0];
                        _encodedAudio.TryTake(out encodedOpusAudio, 100000, _stopFlag.Token);

                        var time = GetTickCount64(); //should add at the receive instead?

                        if ((encodedOpusAudio != null) && (encodedOpusAudio.Length > 36))
                        {
                            //  process
                            // check if we should play audio

                            var myClient = IsClientMetaDataValid(_guid);

                            if ((myClient != null) && _clientStateSingleton.DcsPlayerRadioInfo.IsCurrent())
                            {
                                //Decode bytes
                                var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedOpusAudio);

                                // check the radio
                                RadioReceivingState receivingState = null;
                                var receivingRadio =
                                    _clientStateSingleton.DcsPlayerRadioInfo.CanHearTransmission(
                                        udpVoicePacket.Frequency,
                                        (RadioInformation.Modulation)udpVoicePacket.Modulation,
                                        udpVoicePacket.UnitId, out receivingState);

                                //Check that we're not transmitting on this radio

                                double receivingPowerLossPercent = 0;
                                float  lineOfSightLoss           = 0;

                                if ((receivingRadio != null) && (receivingState != null)
                                    &&
                                    ((receivingRadio.modulation == RadioInformation.Modulation.INTERCOM)
                                     // INTERCOM Modulation is 2 so if its two dont bother checking LOS and Range
                                     ||
                                     (
                                         HasLineOfSight(udpVoicePacket, out lineOfSightLoss)
                                         &&
                                         InRange(udpVoicePacket, out receivingPowerLossPercent)
                                         &&
                                         !ShouldBlockRxAsTransmitting(receivingState.ReceivedOn)
                                     )
                                    )
                                    )
                                {
                                    //  RadioReceivingState[receivingState.ReceivedOn] = receivingState;

                                    //DECODE audio
                                    int len1;
                                    var decoded = _decoder.Decode(udpVoicePacket.AudioPart1Bytes,
                                                                  udpVoicePacket.AudioPart1Bytes.Length, out len1);


                                    if (len1 > 0)
                                    {
                                        // for some reason if this is removed then it lags?!
                                        //guess it makes a giant buffer and only uses a little?
                                        var tmp = new byte[len1];
                                        Buffer.BlockCopy(decoded, 0, tmp, 0, len1);

                                        //ALL GOOD!
                                        //create marker for bytes
                                        var audio = new ClientAudio
                                        {
                                            ClientGuid    = udpVoicePacket.Guid,
                                            PcmAudioShort = ConversionHelpers.ByteArrayToShortArray(tmp),
                                            //Convert to Shorts!
                                            ReceiveTime   = GetTickCount64(),
                                            Frequency     = udpVoicePacket.Frequency,
                                            Modulation    = udpVoicePacket.Modulation,
                                            Volume        = receivingRadio.volume,
                                            ReceivedRadio = receivingState.ReceivedOn,
                                            UnitId        = udpVoicePacket.UnitId,
                                            Encryption    = udpVoicePacket.Encryption,
                                            Decryptable   =
                                                (udpVoicePacket.Encryption == receivingRadio.encKey) &&
                                                receivingRadio.enc,
                                            // mark if we can decrypt it
                                            RadioReceivingState = receivingState,
                                            RecevingPower       =
                                                receivingPowerLossPercent,     //loss of 1.0 or greater is total loss
                                            LineOfSightLoss = lineOfSightLoss, // Loss of 1.0 or greater is total loss
                                            PacketNumber    = udpVoicePacket.PacketNumber
                                        };


                                        //handle effects
                                        var radioState = RadioReceivingState[audio.ReceivedRadio];

                                        if ((radioState == null) || radioState.PlayedEndOfTransmission ||
                                            !radioState.IsReceiving)
                                        {
                                            var decrytable = audio.Decryptable || (audio.Encryption == 0);

                                            //mark that we have decrpyted encrypted audio for sound effects
                                            if (decrytable && (audio.Encryption > 0))
                                            {
                                                _audioManager.PlaySoundEffectStartReceive(audio.ReceivedRadio,
                                                                                          true,
                                                                                          audio.Volume);
                                            }
                                            else
                                            {
                                                _audioManager.PlaySoundEffectStartReceive(audio.ReceivedRadio,
                                                                                          false,
                                                                                          audio.Volume);
                                            }
                                        }

                                        RadioReceivingState[audio.ReceivedRadio] = new RadioReceivingState
                                        {
                                            IsSecondary             = receivingState.IsSecondary,
                                            LastReceviedAt          = DateTime.Now.Ticks,
                                            PlayedEndOfTransmission = false,
                                            ReceivedOn = receivingState.ReceivedOn
                                        };

                                        _audioManager.AddClientAudio(audio);
                                    }
                                    else
                                    {
                                        Logger.Info("Failed to decode audio from Packet");
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Info("Failed to decode audio from Packet");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Logger.Info("Stopped DeJitter Buffer");
            }
        }
        private void UdpAudioDecode()
        {
            try
            {
                while (!_stop)
                {
                    try
                    {
                        var encodedOpusAudio = new byte[0];
                        _encodedAudio.TryTake(out encodedOpusAudio, 100000, _stopFlag.Token);

                        var time = DateTime.Now.Ticks; //should add at the receive instead?

                        if ((encodedOpusAudio != null) &&
                            (encodedOpusAudio.Length >=
                             (UDPVoicePacket.PacketHeaderLength + UDPVoicePacket.FixedPacketLength +
                              UDPVoicePacket.FrequencySegmentLength)))
                        {
                            //  process
                            // check if we should play audio

                            var myClient = IsClientMetaDataValid(_guid);

                            if ((myClient != null))
                            {
                                //Decode bytes
                                var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedOpusAudio);

                                if (udpVoicePacket != null)
                                {
                                    var vehicleId = -1;
                                    if (_clients.TryGetValue(udpVoicePacket.Guid, out var transmittingClient))
                                    {
                                        vehicleId = transmittingClient.GameState.vehicleId;
                                    }

                                    var globalFrequencies = _serverSettings.GlobalFrequencies;

                                    var frequencyCount = udpVoicePacket.Frequencies.Length;

                                    List <RadioReceivingPriority> radioReceivingPriorities =
                                        new List <RadioReceivingPriority>(frequencyCount);
                                    List <int> blockedRadios = CurrentlyBlockedRadios();

                                    // Parse frequencies into receiving radio priority for selection below
                                    for (var i = 0; i < frequencyCount; i++)
                                    {
                                        RadioReceivingState state = null;
                                        bool decryptable;

                                        //Check if Global
                                        bool globalFrequency = globalFrequencies.Contains(udpVoicePacket.Frequencies[i]);


                                        var radio = _clientStateSingleton.PlayerGameState.CanHearTransmission(
                                            udpVoicePacket.Frequencies[i],
                                            (RadioInformation.Modulation)udpVoicePacket.Modulations[i],
                                            udpVoicePacket.UnitId,
                                            vehicleId,
                                            blockedRadios,
                                            out state);

                                        float  losLoss = 0.0f;
                                        double receivPowerLossPercent = 0.0;

                                        if (radio != null && state != null)
                                        {
                                            if (
                                                radio.modulation == RadioInformation.Modulation.INTERCOM ||
                                                globalFrequency ||
                                                (!blockedRadios.Contains(state.ReceivedOn)
                                                )
                                                )
                                            {
                                                radioReceivingPriorities.Add(new RadioReceivingPriority()
                                                {
                                                    Frequency      = udpVoicePacket.Frequencies[i],
                                                    Modulation     = udpVoicePacket.Modulations[i],
                                                    ReceivingRadio = radio,
                                                    ReceivingState = state
                                                });
                                            }
                                        }
                                    }

                                    // Sort receiving radios to play audio on correct one
                                    radioReceivingPriorities.Sort(SortRadioReceivingPriorities);

                                    if (radioReceivingPriorities.Count > 0)
                                    {
                                        //ALL GOOD!
                                        //create marker for bytes
                                        for (int i = 0; i < radioReceivingPriorities.Count; i++)
                                        {
                                            var destinationRadio           = radioReceivingPriorities[i];
                                            var isSimultaneousTransmission = radioReceivingPriorities.Count > 1 && i > 0;

                                            var audio = new ClientAudio
                                            {
                                                ClientGuid   = udpVoicePacket.Guid,
                                                EncodedAudio = udpVoicePacket.AudioPart1Bytes,
                                                //Convert to Shorts!
                                                ReceiveTime   = DateTime.Now.Ticks,
                                                Frequency     = destinationRadio.Frequency,
                                                Modulation    = destinationRadio.Modulation,
                                                Volume        = destinationRadio.ReceivingRadio.volume,
                                                ReceivedRadio = destinationRadio.ReceivingState.ReceivedOn,
                                                UnitId        = udpVoicePacket.UnitId,

                                                RadioReceivingState = destinationRadio.ReceivingState,
                                                PacketNumber        = udpVoicePacket.PacketNumber,
                                                OriginalClientGuid  = udpVoicePacket.OriginalClientGuid
                                            };


                                            //handle effects
                                            var radioState = _radioReceivingState[audio.ReceivedRadio];

                                            if (!isSimultaneousTransmission &&
                                                (radioState == null || radioState.PlayedEndOfTransmission ||
                                                 !radioState.IsReceiving))
                                            {
                                                _audioManager.PlaySoundEffectStartReceive(audio.ReceivedRadio,
                                                                                          false,
                                                                                          audio.Volume, (RadioInformation.Modulation)audio.Modulation);
                                            }

                                            var transmitterName = "";
                                            if (_serverSettings.GetSettingAsBool(ServerSettingsKeys.SHOW_TRANSMITTER_NAME) &&
                                                _globalSettings.GetClientSettingBool(GlobalSettingsKeys.ShowTransmitterName) &&
                                                transmittingClient != null)

                                            {
                                                transmitterName = transmittingClient.Name;
                                            }

                                            var newRadioReceivingState = new RadioReceivingState
                                            {
                                                IsSecondary             = destinationRadio.ReceivingState.IsSecondary,
                                                LastReceivedAt          = DateTime.Now.Ticks,
                                                PlayedEndOfTransmission = false,
                                                ReceivedOn = destinationRadio.ReceivingState.ReceivedOn,
                                                SentBy     = transmitterName
                                            };

                                            _radioReceivingState[audio.ReceivedRadio] = newRadioReceivingState;

                                            // Only play actual audio once
                                            if (i == 0)
                                            {
                                                _audioManager.AddClientAudio(audio);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!_stop)
                        {
                            Logger.Info(ex, "Failed to decode audio from Packet");
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Logger.Info("Stopped DeJitter Buffer");
            }
        }
Пример #7
0
        private void UdpAudioDecode()
        {
            try
            {
                while (!_stop)
                {
                    try
                    {
                        var encodedOpusAudio = new byte[0];
                        _encodedAudio.TryTake(out encodedOpusAudio, 100000, _stopFlag.Token);

                        var time = DateTime.Now.Ticks; //should add at the receive instead?

                        if ((encodedOpusAudio != null) &&
                            (encodedOpusAudio.Length >=
                             (UDPVoicePacket.PacketHeaderLength + UDPVoicePacket.FixedPacketLength +
                              UDPVoicePacket.FrequencySegmentLength)))
                        {
                            //  process
                            // check if we should play audio

                            var myClient = IsClientMetaDataValid(_guid);

                            if ((myClient != null) && _clientStateSingleton.DcsPlayerRadioInfo.IsCurrent())
                            {
                                //Decode bytes
                                var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedOpusAudio);

                                if (udpVoicePacket != null && udpVoicePacket.Modulations[0] != 4)
                                {
                                    var globalFrequencies = _serverSettings.GlobalFrequencies;

                                    var frequencyCount = udpVoicePacket.Frequencies.Length;

                                    List <RadioReceivingPriority> radioReceivingPriorities =
                                        new List <RadioReceivingPriority>(frequencyCount);
                                    List <int> blockedRadios = CurrentlyBlockedRadios();

                                    // Parse frequencies into receiving radio priority for selection below
                                    for (var i = 0; i < frequencyCount; i++)
                                    {
                                        RadioReceivingState state = null;
                                        bool decryptable;

                                        //Check if Global
                                        bool globalFrequency = globalFrequencies.Contains(udpVoicePacket.Frequencies[i]);

                                        if (globalFrequency)
                                        {
                                            //remove encryption for global
                                            udpVoicePacket.Encryptions[i] = 0;
                                        }

                                        var radio = _clientStateSingleton.DcsPlayerRadioInfo.CanHearTransmission(
                                            udpVoicePacket.Frequencies[i],
                                            (RadioInformation.Modulation)udpVoicePacket.Modulations[i],
                                            udpVoicePacket.Encryptions[i],
                                            udpVoicePacket.UnitId,
                                            blockedRadios,
                                            out state,
                                            out decryptable);

                                        float  losLoss = 0.0f;
                                        double receivPowerLossPercent = 0.0;

                                        if (radio != null && state != null)
                                        {
                                            if (
                                                radio.modulation == RadioInformation.Modulation.INTERCOM ||
                                                globalFrequency ||
                                                (
                                                    HasLineOfSight(udpVoicePacket, out losLoss) &&
                                                    InRange(udpVoicePacket.Guid, udpVoicePacket.Frequencies[i],
                                                            out receivPowerLossPercent) &&
                                                    !blockedRadios.Contains(state.ReceivedOn)
                                                )
                                                )
                                            {
                                                decryptable =
                                                    (udpVoicePacket.Encryptions[i] == 0) ||
                                                    (udpVoicePacket.Encryptions[i] == radio.encKey && radio.enc);

                                                radioReceivingPriorities.Add(new RadioReceivingPriority()
                                                {
                                                    Decryptable               = decryptable,
                                                    Encryption                = udpVoicePacket.Encryptions[i],
                                                    Frequency                 = udpVoicePacket.Frequencies[i],
                                                    LineOfSightLoss           = losLoss,
                                                    Modulation                = udpVoicePacket.Modulations[i],
                                                    ReceivingPowerLossPercent = receivPowerLossPercent,
                                                    ReceivingRadio            = radio,
                                                    ReceivingState            = state
                                                });
                                            }
                                        }
                                    }

                                    // Sort receiving radios to play audio on correct one
                                    radioReceivingPriorities.Sort(SortRadioReceivingPriorities);

                                    if (radioReceivingPriorities.Count > 0)
                                    {
                                        //ALL GOOD!
                                        //create marker for bytes
                                        for (int i = 0; i < radioReceivingPriorities.Count; i++)
                                        {
                                            var destinationRadio           = radioReceivingPriorities[i];
                                            var isSimultaneousTransmission = radioReceivingPriorities.Count > 1 && i > 0;

                                            var audio = new ClientAudio
                                            {
                                                ClientGuid   = udpVoicePacket.Guid,
                                                EncodedAudio = udpVoicePacket.AudioPart1Bytes,
                                                //Convert to Shorts!
                                                ReceiveTime   = DateTime.Now.Ticks,
                                                Frequency     = destinationRadio.Frequency,
                                                Modulation    = destinationRadio.Modulation,
                                                Volume        = destinationRadio.ReceivingRadio.volume,
                                                ReceivedRadio = destinationRadio.ReceivingState.ReceivedOn,
                                                UnitId        = udpVoicePacket.UnitId,
                                                Encryption    = destinationRadio.Encryption,
                                                Decryptable   = destinationRadio.Decryptable,
                                                // mark if we can decrypt it
                                                RadioReceivingState = destinationRadio.ReceivingState,
                                                RecevingPower       =
                                                    destinationRadio
                                                    .ReceivingPowerLossPercent,     //loss of 1.0 or greater is total loss
                                                LineOfSightLoss =
                                                    destinationRadio
                                                    .LineOfSightLoss,     // Loss of 1.0 or greater is total loss
                                                PacketNumber = udpVoicePacket.PacketNumber
                                            };


                                            //handle effects
                                            var radioState = RadioReceivingState[audio.ReceivedRadio];

                                            if (!isSimultaneousTransmission &&
                                                (radioState == null || radioState.PlayedEndOfTransmission ||
                                                 !radioState.IsReceiving))
                                            {
                                                var audioDecryptable = audio.Decryptable || (audio.Encryption == 0);

                                                //mark that we have decrpyted encrypted audio for sound effects
                                                if (audioDecryptable && (audio.Encryption > 0))
                                                {
                                                    _audioManager.PlaySoundEffectStartReceive(audio.ReceivedRadio,
                                                                                              true,
                                                                                              audio.Volume);
                                                }
                                                else
                                                {
                                                    _audioManager.PlaySoundEffectStartReceive(audio.ReceivedRadio,
                                                                                              false,
                                                                                              audio.Volume);
                                                }
                                            }

                                            RadioReceivingState[audio.ReceivedRadio] = new RadioReceivingState
                                            {
                                                IsSecondary             = destinationRadio.ReceivingState.IsSecondary,
                                                IsSimultaneous          = isSimultaneousTransmission,
                                                LastReceviedAt          = DateTime.Now.Ticks,
                                                PlayedEndOfTransmission = false,
                                                ReceivedOn = destinationRadio.ReceivingState.ReceivedOn
                                            };

                                            // Only play actual audio once
                                            if (i == 0)
                                            {
                                                _audioManager.AddClientAudio(audio);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!_stop)
                        {
                            Logger.Info(ex, "Failed to decode audio from Packet");
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Logger.Info("Stopped DeJitter Buffer");
            }
        }
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var byteBuffer = message as IByteBuffer;

            if (byteBuffer != null)
            {
                byte[] udpData = new byte[byteBuffer.ReadableBytes];
                byteBuffer.GetBytes(0, udpData);

                var decodedPacket = UDPVoicePacket.DecodeVoicePacket(udpData, false);

                SRClient srClient;
                if (_clientsList.TryGetValue(decodedPacket.Guid, out srClient))
                {
                    srClient.ClientChannelId = context.Channel.Id.AsShortText();

                    var spectatorAudioDisabled =
                        _serverSettings.GetGeneralSetting(ServerSettingsKeys.SPECTATORS_AUDIO_DISABLED).BoolValue;

                    if ((srClient.Coalition == 0) && spectatorAudioDisabled)
                    {
                        byteBuffer.Release();
                        return;
                    }
                    else
                    {
                        HashSet <string> matchingClients = new HashSet <string>();

                        for (int i = 0; i < decodedPacket.Frequencies.Length; i++)
                        {
                            // Magical ignore message 4 - just used for ping
                            if (decodedPacket.Modulations[0] == 4)
                            {
                                continue;
                            }

                            var coalitionSecurity =
                                _serverSettings.GetGeneralSetting(ServerSettingsKeys.COALITION_AUDIO_SECURITY).BoolValue;

                            foreach (KeyValuePair <string, SRClient> _client in _clientsList)
                            {
                                //dont send to receiver
                                if (_client.Value.ClientGuid != decodedPacket.Guid)
                                {
                                    //check frequencies
                                    if ((!coalitionSecurity || (_client.Value.Coalition == srClient.Coalition)))
                                    {
                                        var radioInfo = _client.Value.RadioInfo;

                                        if (radioInfo != null)
                                        {
                                            RadioReceivingState radioReceivingState = null;
                                            bool decryptable;
                                            var  receivingRadio = radioInfo.CanHearTransmission(decodedPacket.Frequencies[i],
                                                                                                (RadioInformation.Modulation)decodedPacket.Modulations[i],
                                                                                                decodedPacket.Encryptions[i],
                                                                                                decodedPacket.UnitId,
                                                                                                emptyBlockedRadios,
                                                                                                out radioReceivingState,
                                                                                                out decryptable);

                                            //only send if we can hear!
                                            if (receivingRadio != null && !matchingClients.Contains(_client.Value.ClientChannelId))
                                            {
                                                matchingClients.Add(_client.Value.ClientChannelId);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        //send to other connected clients
                        if (matchingClients.Count > 0)
                        {
                            group.WriteAndFlushAsync(message, new AllMatchingChannels(matchingClients));
                        }
                        else
                        {
                            byteBuffer.Release();
                        }
                    }
                }
                else
                {
                    byteBuffer.Release();
                }
            }
        }
Пример #9
0
        private void ProcessPackets()
        {
            while (!_stop)
            {
                try
                {
                    PendingPacket udpPacket = null;
                    _pendingProcessingPackets.TryTake(out udpPacket, 100000, _pendingProcessingCancellationToken.Token);

                    if (udpPacket != null)
                    {
                        //last 22 bytes are guid!
                        var guid = Encoding.ASCII.GetString(
                            udpPacket.RawBytes, udpPacket.RawBytes.Length - 22, 22);

                        if (_clientsList.ContainsKey(guid))
                        {
                            var client = _clientsList[guid];
                            client.VoipPort = udpPacket.ReceivedFrom;

                            var spectatorAudioDisabled =
                                _serverSettings.GetGeneralSetting(ServerSettingsKeys.SPECTATORS_AUDIO_DISABLED).BoolValue;

                            if ((client.Coalition == 0 && spectatorAudioDisabled) || client.Muted)
                            {
                                // IGNORE THE AUDIO
                            }
                            else
                            {
                                try
                                {
                                    //decode
                                    var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(udpPacket.RawBytes);

                                    if (udpVoicePacket != null)
                                    //magical ping ignore message 4 - its an empty voip packet to intialise VoIP if
                                    //someone doesnt transmit
                                    {
                                        var outgoingVoice = GenerateOutgoingPacket(udpVoicePacket, udpPacket, client);

                                        if (outgoingVoice != null)
                                        {
                                            //Add to the processing queue
                                            _outGoing.Add(outgoingVoice);

                                            //mark as transmitting for the UI
                                            double mainFrequency = udpVoicePacket.Frequencies.FirstOrDefault();
                                            // Only trigger transmitting frequency update for "proper" packets (excluding invalid frequencies and magic ping packets with modulation 4)
                                            if (mainFrequency > 0)
                                            {
                                                RadioInformation.Modulation mainModulation = (RadioInformation.Modulation)udpVoicePacket.Modulations[0];
                                                if (mainModulation == RadioInformation.Modulation.INTERCOM)
                                                {
                                                    client.TransmittingFrequency = "INTERCOM";
                                                }
                                                else
                                                {
                                                    client.TransmittingFrequency = $"{(mainFrequency / 1000000).ToString("0.000", CultureInfo.InvariantCulture)} {mainModulation}";
                                                }
                                                client.LastTransmissionReceived = DateTime.Now;
                                            }
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    //Hide for now, slows down loop to much....
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Info("Failed to Process UDP Packet: " + ex.Message);
                }
            }
        }
Пример #10
0
        private void UdpAudioDecode()
        {
            try
            {
                while (!_stop)
                {
                    try
                    {
                        var encodedOpusAudio = new byte[0];

                        try
                        {
                            _encodedAudio.TryTake(out encodedOpusAudio, 100000, _stopFlag.Token);
                        } catch (OperationCanceledException ex)
                        {
                            Logger.Debug(ex, $"{_mainClient.LogClientId}| Cancelled operating to get encoded audio");
                        }

                        if (encodedOpusAudio == null ||
                            encodedOpusAudio.Length <
                            UDPVoicePacket.PacketHeaderLength + UDPVoicePacket.FixedPacketLength +
                            UDPVoicePacket.FrequencySegmentLength)
                        {
                            continue;
                        }
                        //  process
                        // check if we should play audio

                        var myClient = IsClientMetaDataValid(_guid);

                        if (myClient == null)
                        {
                            continue;
                        }
                        //Decode bytes
                        var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedOpusAudio);

                        if (udpVoicePacket == null || (Modulation)udpVoicePacket.Modulations[0] != Modulation.AM &&
                            (Modulation)udpVoicePacket.Modulations[0] != Modulation.FM)
                        {
                            continue;
                        }
                        var globalFrequencies = _serverSettings.GlobalFrequencies;

                        var frequencyCount = udpVoicePacket.Frequencies.Length;

                        var radioReceivingPriorities =
                            new List <RadioReceivingPriority>(frequencyCount);
                        var blockedRadios = CurrentlyBlockedRadios();

                        // Parse frequencies into receiving radio priority for selection below
                        for (var i = 0; i < frequencyCount; i++)
                        {
                            //Check if Global
                            var globalFrequency = globalFrequencies.Contains(udpVoicePacket.Frequencies[i]);

                            if (globalFrequency)
                            {
                                //remove encryption for global
                                udpVoicePacket.Encryptions[i] = 0;
                            }

                            var radio = _mainClient.DcsPlayerRadioInfo.CanHearTransmission(
                                udpVoicePacket.Frequencies[i],
                                (Modulation)udpVoicePacket.Modulations[i],
                                udpVoicePacket.Encryptions[i],
                                udpVoicePacket.UnitId,
                                blockedRadios,
                                out var state,
                                out var decryptable);

                            var losLoss = 0.0f;
                            var receivPowerLossPercent = 0.0;

                            if (radio == null || state == null)
                            {
                                continue;
                            }
                            if (radio.modulation != Modulation.INTERCOM && !globalFrequency &&
                                (!HasLineOfSight(udpVoicePacket, out losLoss) || !InRange(udpVoicePacket.Guid,
                                                                                          udpVoicePacket.Frequencies[i],
                                                                                          out receivPowerLossPercent) || blockedRadios.Contains(state.ReceivedOn)))
                            {
                                continue;
                            }
                            decryptable =
                                udpVoicePacket.Encryptions[i] == 0 ||
                                udpVoicePacket.Encryptions[i] == radio.encKey && radio.enc;

                            radioReceivingPriorities.Add(new RadioReceivingPriority
                            {
                                Decryptable               = decryptable,
                                Encryption                = udpVoicePacket.Encryptions[i],
                                Frequency                 = udpVoicePacket.Frequencies[i],
                                LineOfSightLoss           = losLoss,
                                Modulation                = udpVoicePacket.Modulations[i],
                                ReceivingPowerLossPercent = receivPowerLossPercent,
                                ReceivingRadio            = radio,
                                ReceivingState            = state
                            });
                        }

                        // Sort receiving radios to play audio on correct one
                        radioReceivingPriorities.Sort(SortRadioReceivingPriorities);

                        if (radioReceivingPriorities.Count <= 0)
                        {
                            continue;
                        }
                        {
                            //ALL GOOD!
                            //create marker for bytes
                            for (var i = 0; i < radioReceivingPriorities.Count; i++)
                            {
                                var destinationRadio           = radioReceivingPriorities[i];
                                var isSimultaneousTransmission = radioReceivingPriorities.Count > 1 && i > 0;

                                var audio = new ClientAudio
                                {
                                    ClientGuid   = udpVoicePacket.Guid,
                                    EncodedAudio = udpVoicePacket.AudioPart1Bytes,
                                    //Convert to Shorts!
                                    ReceiveTime   = DateTime.Now.Ticks,
                                    Frequency     = destinationRadio.Frequency,
                                    Modulation    = destinationRadio.Modulation,
                                    Volume        = destinationRadio.ReceivingRadio.volume,
                                    ReceivedRadio = destinationRadio.ReceivingState.ReceivedOn,
                                    UnitId        = udpVoicePacket.UnitId,
                                    Encryption    = destinationRadio.Encryption,
                                    Decryptable   = destinationRadio.Decryptable,
                                    // mark if we can decrypt it
                                    RadioReceivingState = destinationRadio.ReceivingState,
                                    RecevingPower       =
                                        destinationRadio
                                        .ReceivingPowerLossPercent,     //loss of 1.0 or greater is total loss
                                    LineOfSightLoss =
                                        destinationRadio
                                        .LineOfSightLoss,     // Loss of 1.0 or greater is total loss
                                    PacketNumber = udpVoicePacket.PacketNumber
                                };

                                RadioReceivingState[audio.ReceivedRadio] = new RadioReceivingState
                                {
                                    IsSecondary             = destinationRadio.ReceivingState.IsSecondary,
                                    IsSimultaneous          = isSimultaneousTransmission,
                                    LastReceviedAt          = DateTime.Now.Ticks,
                                    PlayedEndOfTransmission = false,
                                    ReceivedOn = destinationRadio.ReceivingState.ReceivedOn
                                };

                                // Only play actual audio once
                                if (i == 0)
                                {
                                    _mainClient.AudioManager.AddClientAudio(audio);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!_stop)
                        {
                            Logger.Info(ex, $"{_mainClient.LogClientId}| Failed to decode audio from Packet");
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Logger.Info($"{_mainClient.LogClientId}| Stopped DeJitter Buffer");
            }
        }
        private void ProcessPackets()
        {
            while (!_stop)
            {
                try
                {
                    PendingPacket udpPacket = null;
                    _pendingProcessingPackets.TryTake(out udpPacket, 100000, _pendingProcessingCancellationToken.Token);

                    if (udpPacket != null)
                    {
                        //last 36 bytes are guid!
                        var guid = Encoding.ASCII.GetString(
                            udpPacket.RawBytes, udpPacket.RawBytes.Length - 22, 22);

                        if (_clientsList.ContainsKey(guid))
                        {
                            var client = _clientsList[guid];
                            client.VoipPort = udpPacket.ReceivedFrom;

                            var spectatorAudioDisabled =
                                _serverSettings.ServerSetting[(int)ServerSettingType.SPECTATORS_AUDIO_DISABLED];

                            if ((client.Coalition == 0) && spectatorAudioDisabled)
                            {
                                // IGNORE THE AUDIO
                            }
                            else
                            {
                                try
                                {
                                    //decode
                                    var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(udpPacket.RawBytes);

                                    if ((udpVoicePacket != null) && (udpVoicePacket.Modulation != 4))
                                    //magical ignore message 4
                                    {
                                        var outgoingVoice = GenerateOutgoingPacket(udpVoicePacket, udpPacket, client);

                                        if (outgoingVoice != null)
                                        {
                                            _outGoing.Add(outgoingVoice);
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    //Hide for now, slows down loop to much....
                                }
                            }
                        }
                        else
                        {
                            SRClient value;
                            _clientsList.TryRemove(guid, out value);
                            //  logger.Info("Removing  "+guid+" From UDP pool");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Info("Failed to Process UDP Packet: " + ex.Message);
                }
            }
        }
Пример #12
0
        private void UdpAudioDecode()
        {
            try
            {
                while (!_stop)
                {
                    try
                    {
                        var encodedOpusAudio = new byte[0];
                        _encodedAudio.TryTake(out encodedOpusAudio, 100000, _stopFlag.Token);

                        var time = GetTickCount64(); //should add at the receive instead?

                        if (encodedOpusAudio != null && encodedOpusAudio.Length > 36)
                        {
                            //  process
                            // check if we should play audio

                            var myClient = IsClientMetaDataValid(_guid);

                            if (myClient != null && RadioDCSSyncServer.DcsPlayerRadioInfo.IsCurrent())
                            {
                                //Decode bytes
                                var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedOpusAudio);

                                // check the radio
                                RadioReceivingState receivingState = null;
                                var receivingRadio =
                                    RadioDCSSyncServer.DcsPlayerRadioInfo.CanHearTransmission(udpVoicePacket.Frequency,
                                                                                              udpVoicePacket.Modulation,
                                                                                              udpVoicePacket.UnitId, out receivingState);

                                //Check that we're not transmitting on this radio

                                double receivingPower  = 0;
                                float  lineOfSightLoss = 0;

                                if (receivingRadio != null && receivingState != null
                                    &&
                                    (receivingRadio.modulation == 2
                                     // INTERCOM Modulation is 2 so if its two dont bother checking LOS and Range
                                     ||
                                     (
                                         HasLineOfSight(udpVoicePacket, out lineOfSightLoss)
                                         &&
                                         InRange(udpVoicePacket, out receivingPower)
                                         &&
                                         !ShouldBlockRxAsTransmitting(receivingState.ReceivedOn)
                                     )
                                    )
                                    )
                                {
                                    //  RadioReceivingState[receivingState.ReceivedOn] = receivingState;

                                    //DECODE audio
                                    int len1;
                                    var decoded = _decoder.Decode(udpVoicePacket.AudioPart1Bytes,
                                                                  udpVoicePacket.AudioPart1Bytes.Length, out len1);

                                    int len2;
                                    var decoded2 = _decoder.Decode(udpVoicePacket.AudioPart2Bytes,
                                                                   udpVoicePacket.AudioPart2Bytes.Length, out len2);

                                    if (len1 > 0 && len2 > 0)
                                    {
                                        // for some reason if this is removed then it lags?!
                                        //guess it makes a giant buffer and only uses a little?
                                        var tmp = new byte[len1 + len2];
                                        Buffer.BlockCopy(decoded, 0, tmp, 0, len1);
                                        Buffer.BlockCopy(decoded2, 0, tmp, len1, len2);

                                        //ALL GOOD!
                                        //create marker for bytes
                                        var audio = new ClientAudio
                                        {
                                            ClientGuid    = udpVoicePacket.Guid,
                                            PcmAudioShort = ConversionHelpers.ByteArrayToShortArray(tmp),
                                            //Convert to Shorts!
                                            ReceiveTime   = GetTickCount64(),
                                            Frequency     = udpVoicePacket.Frequency,
                                            Modulation    = udpVoicePacket.Modulation,
                                            Volume        = receivingRadio.volume,
                                            ReceivedRadio = receivingState.ReceivedOn,
                                            UnitId        = udpVoicePacket.UnitId,
                                            Encryption    = udpVoicePacket.Encryption,
                                            Decryptable   =
                                                udpVoicePacket.Encryption == receivingRadio.encKey && receivingRadio.enc,
                                            // mark if we can decrypt it
                                            RadioReceivingState = receivingState,
                                            RecevingPower       = receivingPower,
                                            LineOfSightLoss     = lineOfSightLoss // Loss of 1.0 or greater is total loss
                                        };

                                        //add to JitterBuffer!
                                        lock (_lock)
                                        {
                                            _jitterBuffer.AddAudio(audio);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Info("Failed Decoding");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Logger.Info("Stopped DeJitter Buffer");
            }
        }
Пример #13
0
        private void UdpAudioDecode()
        {
            try
            {
                while (!_stop)
                {
                    try
                    {
                        var encodedOpusAudio = new byte[0];
                        _encodedAudio.TryTake(out encodedOpusAudio, 100000, _stopFlag.Token);

                        var time = DateTime.Now.Ticks; //should add at the receive instead?

                        if ((encodedOpusAudio != null) &&
                            (encodedOpusAudio.Length >=
                             (UDPVoicePacket.PacketHeaderLength + UDPVoicePacket.FixedPacketLength +
                              UDPVoicePacket.FrequencySegmentLength)))
                        {
                            //  process
                            // check if we should play audio

                            var myClient = IsClientMetaDataValid(_guid);

                            if ((myClient != null) && _clientStateSingleton.DcsPlayerRadioInfo.IsCurrent())
                            {
                                //Decode bytes
                                var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(encodedOpusAudio);

                                if (udpVoicePacket != null)
                                {
                                    var globalFrequencies = _serverSettings.GlobalFrequencies;

                                    var frequencyCount = udpVoicePacket.Frequencies.Length;

                                    List <RadioReceivingPriority> radioReceivingPriorities =
                                        new List <RadioReceivingPriority>(frequencyCount);
                                    List <int> blockedRadios = CurrentlyBlockedRadios();

                                    var strictEncryption = _serverSettings.GetSettingAsBool(ServerSettingsKeys.STRICT_RADIO_ENCRYPTION);

                                    // Parse frequencies into receiving radio priority for selection below
                                    for (var i = 0; i < frequencyCount; i++)
                                    {
                                        RadioReceivingState state = null;
                                        bool decryptable;

                                        //Check if Global
                                        bool globalFrequency = globalFrequencies.Contains(udpVoicePacket.Frequencies[i]);

                                        if (globalFrequency)
                                        {
                                            //remove encryption for global
                                            udpVoicePacket.Encryptions[i] = 0;
                                        }

                                        var radio = _clientStateSingleton.DcsPlayerRadioInfo.CanHearTransmission(
                                            udpVoicePacket.Frequencies[i],
                                            (RadioInformation.Modulation)udpVoicePacket.Modulations[i],
                                            udpVoicePacket.Encryptions[i],
                                            strictEncryption,
                                            udpVoicePacket.UnitId,
                                            blockedRadios,
                                            out state,
                                            out decryptable);

                                        float  losLoss = 0.0f;
                                        double receivPowerLossPercent = 0.0;

                                        if (radio != null && state != null)
                                        {
                                            if (
                                                radio.modulation == RadioInformation.Modulation.INTERCOM ||
                                                radio.modulation == RadioInformation.Modulation.MIDS || // IGNORE LOS and Distance for MIDS - we assume a Link16 Network is in place
                                                globalFrequency ||
                                                (
                                                    HasLineOfSight(udpVoicePacket, out losLoss) &&
                                                    InRange(udpVoicePacket.Guid, udpVoicePacket.Frequencies[i],
                                                            out receivPowerLossPercent) &&
                                                    !blockedRadios.Contains(state.ReceivedOn)
                                                )
                                                )
                                            {
                                                // This is already done in CanHearTransmission!!
                                                //decryptable =
                                                //    (udpVoicePacket.Encryptions[i] == radio.encKey && radio.enc) ||
                                                //    (!strictEncryption && udpVoicePacket.Encryptions[i] == 0);

                                                radioReceivingPriorities.Add(new RadioReceivingPriority()
                                                {
                                                    Decryptable               = decryptable,
                                                    Encryption                = udpVoicePacket.Encryptions[i],
                                                    Frequency                 = udpVoicePacket.Frequencies[i],
                                                    LineOfSightLoss           = losLoss,
                                                    Modulation                = udpVoicePacket.Modulations[i],
                                                    ReceivingPowerLossPercent = receivPowerLossPercent,
                                                    ReceivingRadio            = radio,
                                                    ReceivingState            = state
                                                });
                                            }
                                        }
                                    }

                                    // Sort receiving radios to play audio on correct one
                                    radioReceivingPriorities.Sort(SortRadioReceivingPriorities);

                                    if (radioReceivingPriorities.Count > 0)
                                    {
                                        //ALL GOOD!
                                        //create marker for bytes
                                        for (int i = 0; i < radioReceivingPriorities.Count; i++)
                                        {
                                            var destinationRadio           = radioReceivingPriorities[i];
                                            var isSimultaneousTransmission = radioReceivingPriorities.Count > 1 && i > 0;

                                            var audio = new ClientAudio
                                            {
                                                ClientGuid   = udpVoicePacket.Guid,
                                                EncodedAudio = udpVoicePacket.AudioPart1Bytes,
                                                //Convert to Shorts!
                                                ReceiveTime   = DateTime.Now.Ticks,
                                                Frequency     = destinationRadio.Frequency,
                                                Modulation    = destinationRadio.Modulation,
                                                Volume        = destinationRadio.ReceivingRadio.volume,
                                                ReceivedRadio = destinationRadio.ReceivingState.ReceivedOn,
                                                UnitId        = udpVoicePacket.UnitId,
                                                Encryption    = destinationRadio.Encryption,
                                                Decryptable   = destinationRadio.Decryptable,
                                                // mark if we can decrypt it
                                                RadioReceivingState = destinationRadio.ReceivingState,
                                                RecevingPower       =
                                                    destinationRadio
                                                    .ReceivingPowerLossPercent,     //loss of 1.0 or greater is total loss
                                                LineOfSightLoss =
                                                    destinationRadio
                                                    .LineOfSightLoss,     // Loss of 1.0 or greater is total loss
                                                PacketNumber       = udpVoicePacket.PacketNumber,
                                                OriginalClientGuid = udpVoicePacket.OriginalClientGuid
                                            };


                                            //handle effects
                                            var radioState = _radioReceivingState[audio.ReceivedRadio];

                                            if (!isSimultaneousTransmission &&
                                                (radioState == null || radioState.PlayedEndOfTransmission ||
                                                 !radioState.IsReceiving))
                                            {
                                                var audioDecryptable = audio.Decryptable /* || (audio.Encryption == 0) <--- this has already been tested above */;

                                                //mark that we have decrypted encrypted audio for sound effects
                                                if (audioDecryptable && (audio.Encryption > 0))
                                                {
                                                    _audioManager.PlaySoundEffectStartReceive(audio.ReceivedRadio,
                                                                                              true,
                                                                                              audio.Volume, (Modulation)audio.Modulation);
                                                }
                                                else
                                                {
                                                    _audioManager.PlaySoundEffectStartReceive(audio.ReceivedRadio,
                                                                                              false,
                                                                                              audio.Volume, (Modulation)audio.Modulation);
                                                }
                                            }

                                            var transmitterName = "";
                                            if (_serverSettings.GetSettingAsBool(ServerSettingsKeys.SHOW_TRANSMITTER_NAME) &&
                                                _globalSettings.GetClientSettingBool(GlobalSettingsKeys.ShowTransmitterName) &&
                                                _clients.TryGetValue(udpVoicePacket.Guid, out var transmittingClient))

                                            {
                                                transmitterName = transmittingClient.Name;
                                            }

                                            var newRadioReceivingState = new RadioReceivingState
                                            {
                                                IsSecondary             = destinationRadio.ReceivingState.IsSecondary,
                                                IsSimultaneous          = isSimultaneousTransmission,
                                                LastReceviedAt          = DateTime.Now.Ticks,
                                                PlayedEndOfTransmission = false,
                                                ReceivedOn = destinationRadio.ReceivingState.ReceivedOn,
                                                SentBy     = transmitterName
                                            };

                                            _radioReceivingState[audio.ReceivedRadio] = newRadioReceivingState;

                                            if (i == 0)
                                            {
                                                bool overrideEffects = false;

                                                if (_serverSettings.GetSettingAsBool(ServerSettingsKeys
                                                                                     .RADIO_EFFECT_OVERRIDE))
                                                {
                                                    overrideEffects = _serverSettings.GlobalFrequencies.Contains(audio.Frequency);
                                                }

                                                _audioManager.AddClientAudio(audio, overrideEffects);
                                            }
                                        }

                                        //handle retransmission
                                        RetransmitAudio(udpVoicePacket, radioReceivingPriorities);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!_stop)
                        {
                            Logger.Info(ex, "Failed to decode audio from Packet");
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Logger.Info("Stopped DeJitter Buffer");
            }
        }
Пример #14
0
        public void Listen()
        {
            var port = _serverSettings.ServerListeningPort();

            _listener = new UdpClient();
            _listener.AllowNatTraversal(true);
            _listener.ExclusiveAddressUse = true;
            _listener.Client.Bind(new IPEndPoint(IPAddress.Any, _serverSettings.ServerListeningPort()));
            while (!_stop)
            {
                try
                {
                    var groupEP  = new IPEndPoint(IPAddress.Any, port);
                    var rawBytes = _listener.Receive(ref groupEP);
                    if (rawBytes != null && rawBytes.Length >= 22)
                    {
                        //WRAP IN REAL THREAD??
                        Task.Run(() =>
                        {
                            //last 36 bytes are guid!
                            var guid = Encoding.ASCII.GetString(
                                rawBytes, rawBytes.Length - 22, 22);

                            if (_clientsList.ContainsKey(guid))
                            {
                                var client      = _clientsList[guid];
                                client.VoipPort = groupEP;

                                var spectatorAudioDisabled =
                                    _serverSettings.ServerSetting[(int)ServerSettingType.SPECTATORS_AUDIO_DISABLED];

                                if (client.Coalition == 0 && spectatorAudioDisabled)
                                {
                                    // IGNORE THE AUDIO
                                }
                                else
                                {
                                    try
                                    {
                                        //decode
                                        var udpVoicePacket = UDPVoicePacket.DecodeVoicePacket(rawBytes);

                                        if (udpVoicePacket != null && udpVoicePacket.Modulation != 4)
                                        //magical ignore message 4
                                        {
                                            SendToOthers(rawBytes, client, udpVoicePacket);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        //Hide for now, slows down loop to much....
                                    }
                                }
                            }
                            else
                            {
                                SRClient value;
                                _clientsList.TryRemove(guid, out value);
                                //  logger.Info("Removing  "+guid+" From UDP pool");
                            }
                        });
                    }
                    else if (rawBytes != null && rawBytes.Length == 15 && rawBytes[0] == 1 && rawBytes[14] == 15)
                    {
                        try
                        {
                            //send back ping UDP
                            //   _listener.Send(rawBytes, rawBytes.Length, groupEP);
                        }
                        catch (Exception ex)
                        {
                            //dont log because it slows down thread too much...
                        }
                    }
                }
                catch (Exception e)
                {
                    //  logger.Error(e,"Error receving audio UDP for client " + e.Message);
                }
            }

            try
            {
                _listener.Close();
            }
            catch (Exception e)
            {
            }
        }