コード例 #1
0
        protected BaseClient([NotNull] ICommsNetworkState network)
        {
            if (network == null)
            {
                throw new ArgumentNullException("network");
            }

            Log = Logs.Create(LogCategory.Network, GetType().Name);

            const int poolSize        = 32;
            const int byteBufferSize  = 1024;
            const int channelListSize = 8;
            var       byteArrayPool   = new ReadonlyLockedValue <Pool <byte[]> >(new Pool <byte[]>(poolSize, () => new byte[byteBufferSize]));
            var       channelListPool = new ConcurrentPool <List <RemoteChannel> >(poolSize, () => new List <RemoteChannel>(channelListSize));

            _sendQueue        = new SendQueue <TPeer>(this, byteArrayPool);
            _serverNegotiator = new ConnectionNegotiator <TPeer>(_sendQueue, network.PlayerName, network.CodecSettings);
            _lossSimulator    = new PacketDelaySimulator();

            _events = new EventQueue(byteArrayPool, channelListPool);
            _peers  = new SlaveClientCollection <TPeer>(_sendQueue, _serverNegotiator, _events, network.Rooms, network.PlayerName, network.CodecSettings);
            _peers.OnClientJoined        += OnAddedClient;
            _peers.OnClientIntroducedP2P += OnMetClient;

            _voiceReceiver = new VoiceReceiver <TPeer>(_serverNegotiator, _peers, _events, network.Rooms, channelListPool);
            _voiceSender   = new VoiceSender <TPeer>(_sendQueue, _serverNegotiator, _peers, _events, network.PlayerChannels, network.RoomChannels);

            _textReceiver = new TextReceiver <TPeer>(_events, network.Rooms, _peers);
            _textSender   = new TextSender <TPeer>(_sendQueue, _serverNegotiator, _peers);
        }
コード例 #2
0
        private BaseClient(string playerName, Rooms rooms, PlayerChannels playerChannels, RoomChannels roomChannels)
        {
            if (playerName == null)
            {
                throw new ArgumentNullException("playerName");
            }
            if (rooms == null)
            {
                throw new ArgumentNullException("rooms");
            }
            if (playerChannels == null)
            {
                throw new ArgumentNullException("playerChannels");
            }
            if (roomChannels == null)
            {
                throw new ArgumentNullException("roomChannels");
            }

            Log = Logs.Create(LogCategory.Network, GetType().Name);

            _playerName = playerName;

            _byteBufferPool = new ConcurrentPool <byte[]>(10, () => new byte[1024]);
            _queuedUnreliableTransmissions = new TransferBuffer <ArraySegment <byte> >(16);
            _queuedReliableTransmissions   = new TransferBuffer <ArraySegment <byte> >(16);
            _queuedEvents = new List <NetworkEvent>();

            _peers                = new PeerCollection(this);
            _channels             = new ChannelCollection(_peers.RoutingTable, playerChannels, roomChannels);
            _connectionNegotiator = new ConnectionNegotiator(this);
            _router               = new PacketRouter(this, _connectionNegotiator);
            _commsProcessor       = new CommsProcessor(this, _peers.RoutingTable, rooms, _channels);
            _roomsManager         = new RoomMembershipManager(this, _connectionNegotiator, rooms);
        }
コード例 #3
0
        /// <summary>
        /// Creates a new GeonamesParser using the provided IDictionary to map each Cities'
        /// string TZ Name to int TimeZone ids.
        /// </summary>
        public GeonamesParser(DataTable featureCodesDataTable, GeonamesDirectoryInfo directory)
        {
            Directory = directory;

            _geonamesFiles = directory.ValidGeonamesFiles;

            FEATURECODE_FILE_PATH = Environment.CurrentDirectory + @"\Resources\geonames_feature_codes.txt";

            _regex = new Regex(@"\t", RegexOptions.Compiled);

            _maxParallelism = Environment.ProcessorCount;

            // Assign a reusable buffer for each thread.
            _bufferPool = new ConcurrentPool <string[]>(_maxParallelism);

            // Allocate buffer pool.
            for (int i = 0; i < _maxParallelism; i++)
            {
                // Adding string[] with max number of City fields for size.
                _bufferPool.Push(new string[City.NUM_FIELDS]);
            }

            ParsedEntries = 0;

            if (null != featureCodesDataTable)
            {
                _featureCodesDataTable = featureCodesDataTable;
            }
            else
            {
                throw new ArgumentNullException("featureCodesDataTable");
            }
        }
コード例 #4
0
        [NotNull] private static DecoderPipeline GetOrCreateDecoderPipeline(FrameFormat format, [NotNull] IVolumeProvider volume)
        {
            if (volume == null)
            {
                throw new ArgumentNullException("volume");
            }

            ConcurrentPool <DecoderPipeline> pool;

            if (!FreePipelines.TryGetValue(format, out pool))
            {
                pool = new ConcurrentPool <DecoderPipeline>(3, () => {
                    var decoder = DecoderFactory.Create(format);

                    return(new DecoderPipeline(decoder, format.FrameSize, p =>
                    {
                        p.Reset();
                        Recycle(format, p);
                    }));
                });
                FreePipelines[format] = pool;
            }

            var pipeline = pool.Get();

            pipeline.Reset();

            pipeline.VolumeProvider = volume;

            return(pipeline);
        }
コード例 #5
0
        public DecoderPipeline([NotNull] IVoiceDecoder decoder, uint inputFrameSize, [NotNull] Action<DecoderPipeline> completionHandler, bool softClip = true)
        {
            if (decoder == null) throw new ArgumentNullException("decoder");
            if (completionHandler == null) throw new ArgumentNullException("completionHandler");

            _completionHandler = completionHandler;
            _inputBuffer = new TransferBuffer<VoicePacket>(32);

            // we need buffers to hold the encoded frames, but we have no idea how large an encoded frame is! These buffers are large enough...
            // ...to hold a frame with no compression whatsoever, so they should be large enough to hold the frame wehen it's opus compressed.
            _bytePool = new ConcurrentPool<byte[]>(12, () => new byte[inputFrameSize * decoder.Format.Channels * 4]);
            _channelListPool = new ConcurrentPool<List<RemoteChannel>>(12, () => new List<RemoteChannel>());

            _frameDuration = TimeSpan.FromSeconds((double)inputFrameSize / decoder.Format.SampleRate);
            _firstFrameArrival = null;
            _firstFrameSeq = 0;

            var source = new BufferedDecoder(decoder, inputFrameSize, decoder.Format, RecycleFrame);
            var ramped = new VolumeRampedFrameSource(source, this);
            var samples = new FrameToSampleConverter(ramped);

            ISampleSource toResampler = samples;
            if (softClip)
                toResampler = new SoftClipSampleSource(samples);

            var resampled = new Resampler(toResampler);

            _source = source;
            _output = resampled;
        }
コード例 #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputFormat">format of audio supplied to `Send`</param>
        /// <param name="inputFrameSize">Size of frames which will should be provided from `GetFrameBuffer`</param>
        /// <param name="intermediateFrameSize">Size of frames which should be passed into `PreprocessAudioFrame`</param>
        /// <param name="intermediateSampleRate">Sample rate which should be passed into `PreprocessAudioFrame`</param>
        /// <param name="outputFrameSize">Size of frames which will be provided sent to `SendSamplesToSubscribers`</param>
        /// <param name="outputSampleRate"></param>
        protected BasePreprocessingPipeline(WaveFormat inputFormat, int inputFrameSize, int intermediateFrameSize, int intermediateSampleRate, int outputFrameSize, int outputSampleRate)
        {
            if (inputFrameSize < 0)
            {
                throw new ArgumentOutOfRangeException("inputFrameSize", "Input frame size cannot be less than zero");
            }

            _inputFrameSize  = inputFrameSize;
            _outputFrameSize = outputFrameSize;
            _outputFormat    = new WaveFormat(1, outputSampleRate);

            //Create input system (source of empty buffers, queue of waiting input data)
            _inputBufferSource = new ConcurrentPool <float[]>(24, () => new float[inputFrameSize]);
            _inputQueue        = new TransferBuffer <float[]>(12);
            _emptyInputFrame   = new float[inputFrameSize];

            //Create resampler to resample input to intermediate rate
            _resamplerInput    = new BufferedSampleProvider(inputFormat, InputFrameSize * 4);
            _resampler         = new Resampler(_resamplerInput, 48000);
            _resampledOutput   = new SampleToFrameProvider(_resampler, (uint)OutputFrameSize);
            _intermediateFrame = new float[intermediateFrameSize];

            _threadEvent = new AutoResetEvent(false);
            _thread      = new DThread(ThreadEntry);
        }
コード例 #7
0
 public ChunkTaskManager()
 {
     requestPool        = new ConcurrentPool <ChunkTaskRequest>(() => { return(new ChunkTaskRequest()); });
     requests           = new ConcurrentPriorityQueue <ChunkTaskRequest>(new ChunkTaskRequestComparer());
     taskCallbackMethod = new ChunkTask.Callback(TaskCallback);
     activeRequests     = new Dictionary <ChunkTaskRequest, ChunkTaskRequest>(concurrencyLevel);
 }
コード例 #8
0
        public DecoderPipeline(IVoiceDecoder decoder, uint frameSize, Action <DecoderPipeline> completionHandler, bool softClip = true)
        {
            _completionHandler = completionHandler;
            _inputBuffer       = new TransferBuffer <EncodedAudio>();
            _bytePool          = new ConcurrentPool <byte[]>(12, () => new byte[frameSize * decoder.Format.Channels * 4]); // todo wrong frame size (although it should still be large enough)

            _frameDuration     = TimeSpan.FromSeconds((double)frameSize / decoder.Format.SampleRate);
            _firstFrameArrival = null;
            _firstFrameSeq     = 0;

            var source  = new BufferedDecoder(decoder, frameSize, decoder.Format, frame => _bytePool.Put(frame.Data.Array));
            var ramped  = new VolumeRampedFrameSource(source, this);
            var samples = new FrameToSampleConverter(ramped);

            ISampleSource toResampler = samples;

            if (softClip)
            {
                toResampler = new SoftClipSampleSource(samples);
            }

            var resampled = new Resampler(toResampler);

            _source = source;
            _output = resampled;
        }
コード例 #9
0
 public PeerVoiceReceiver(string remoteName, ushort localId, string localName, EventQueue events, Rooms listeningRooms, ConcurrentPool <List <RemoteChannel> > channelListPool)
 {
     _name                = remoteName;
     _localId             = localId;
     _localName           = localName;
     _events              = events;
     _localListeningRooms = listeningRooms;
     _channelListPool     = channelListPool;
 }
コード例 #10
0
ファイル: VoiceReceiver.cs プロジェクト: ChatVR/ChatVR-Mirror
        public VoiceReceiver(ISession session, IClientCollection <TPeer?> clients, EventQueue events, Rooms rooms, ConcurrentPool <List <RemoteChannel> > channelListPool)
        {
            _session         = session;
            _clients         = clients;
            _events          = events;
            _rooms           = rooms;
            _channelListPool = channelListPool;

            _events.OnEnqueuePlayerLeft += OnPlayerLeft;
        }
コード例 #11
0
ファイル: AsyncLockSet.cs プロジェクト: kotx/Stl.Fusion
 public AsyncLockSet(
     ReentryMode reentryMode,
     TaskCreationOptions taskCreationOptions,
     int concurrencyLevel, int capacity)
 {
     ReentryMode = reentryMode;
     _entries    = new ConcurrentDictionary <TKey, Entry>(concurrencyLevel, capacity);
     _lockPool   = new ConcurrentPool <AsyncLock>(
         () => new AsyncLock(ReentryMode, taskCreationOptions));
 }
コード例 #12
0
        public SendQueue([NotNull] IClient <TPeer> client, [NotNull] ConcurrentPool <byte[]> bytePool)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            if (bytePool == null)
            {
                throw new ArgumentNullException("bytePool");
            }

            _client         = client;
            _sendBufferPool = bytePool;
        }
コード例 #13
0
        public ScopedServicePool(IServiceProvider services,
                                 Func <TService, bool> canReuseHandler,
                                 int capacity)
        {
            IServiceScope PoolItemFactory()
            {
                var scope = services.CreateScope();
                var _     = scope.ServiceProvider.GetRequiredService <TService>();

                return(scope);
            }

            _canReuseHandler = canReuseHandler;
            _scopePool       = new ConcurrentPool <IServiceScope>(PoolItemFactory, capacity);
        }
コード例 #14
0
 public void WithPool(PoolType t)
 {
     if (t == poolType)
     {
         return;
     }
     poolType = t;
     if (t == PoolType.Sequence)
     {
         pool = new SequencePool();
     }
     else if (t == PoolType.Concurrent)
     {
         pool = new ConcurrentPool();
     }
 }
コード例 #15
0
    public static void Example()
    {
        var pool1 = new ConcurrentPool <MyObject>("Pool of MyObject");

        //var pool2 = new ConcurrentPool<MyObject>("Pool of MyObject", (x) => new MyObject());

        using (MyObject instance1 = pool1.Acquire())
        {
            // Do something with the instance
        }
        // The instance is released back to the pool

        MyObject instance2 = pool1.Acquire();

        // Do something with the instance
        instance2.TryRelease();
    }
コード例 #16
0
        public DecoderPipeline([NotNull] IVoiceDecoder decoder, uint inputFrameSize, [NotNull] Action <DecoderPipeline> completionHandler, string id, bool softClip = true)
        {
            if (decoder == null)
            {
                throw new ArgumentNullException("decoder");
            }
            if (completionHandler == null)
            {
                throw new ArgumentNullException("completionHandler");
            }

            _id = id;

            _completionHandler = completionHandler;
            _inputBuffer       = new TransferBuffer <VoicePacket>(32);

            // we need buffers to hold the encoded frames, but we have no idea how large an encoded frame is! These buffers are large enough...
            // ...to hold a frame with no compression whatsoever, so they should be large enough to hold the frame when it's opus compressed.
            _bytePool        = new ConcurrentPool <byte[]>(12, () => new byte[inputFrameSize * decoder.Format.Channels * 4]);
            _channelListPool = new ConcurrentPool <List <RemoteChannel> >(12, () => new List <RemoteChannel>());

            _frameDuration     = TimeSpan.FromSeconds((double)inputFrameSize / decoder.Format.SampleRate);
            _firstFrameArrival = null;
            _firstFrameSeq     = 0;

            // Buffer decoded packets and decode them on demand
            var source = new BufferedDecoder(decoder, inputFrameSize, decoder.Format, RecycleFrame);

            _source = source;

            // Every time the volume changes, change is smoothly over the course of a single frame
            var ramped = new VolumeRampedFrameSource(source, this);

            // Convert stream of fixed size frames into a stream of samples taken in arbitrary chunks
            var samples = new FrameToSampleConverter(ramped);

            // Monitor stream sync and adjust playback rate to stay close in sync
            _synchronizer = new SynchronizerSampleSource(samples, TimeSpan.FromSeconds(1));

            // Resample the data to the output rate
            var resampled = new Resampler(_synchronizer, this);

            // Chain a soft clip stage if necessary
            _output = softClip ? (ISampleSource) new SoftClipSampleSource(resampled) : resampled;
        }
コード例 #17
0
        [NotNull] private static ConcurrentPool <DecoderPipeline> GetPool(FrameFormat format)
        {
            ConcurrentPool <DecoderPipeline> pool;

            if (!Pools.TryGetValue(format, out pool))
            {
                pool = new ConcurrentPool <DecoderPipeline>(3, () => {
                    var decoder = DecoderFactory.Create(format);

                    var uuid = _nextPipelineId.ToString();
                    return(new DecoderPipeline(decoder, format.FrameSize, p => {
                        p.Reset();
                        Recycle(format, p);
                    }, uuid));
                });
                Pools[format] = pool;

                _nextPipelineId++;
            }

            return(pool);
        }
コード例 #18
0
ファイル: SessionIOCP.cs プロジェクト: Alx666/Netbase
        public SessionIOCP()
        {
            //TODO: optimize SocketAsyncEventArgs distribution
            m_hSendOps = new ConcurrentPool<SocketAsyncEventArgs>();
            m_hRecvOps = new ConcurrentPool<SocketAsyncEventArgs>();

            for (int i = 0; i < 10; i++)
            {
                SocketAsyncEventArgs hSendOp = new SocketAsyncEventArgs();
                hSendOp.Completed += OnSendCompleted;
                hSendOp.SetBuffer(new byte[BufferSize], 0, BufferSize);
                m_hSendOps.Recycle(hSendOp);

                SocketAsyncEventArgs hRecvOp = new SocketAsyncEventArgs();
                hRecvOp.Completed += OnRecvCompleted;
                hRecvOp.SetBuffer(new byte[BufferSize], 0, BufferSize);
                m_hRecvOps.Recycle(hRecvOp);
            }

            m_hRecvBuffer   = new byte[BufferSize];
            m_hMs           = new MemoryStream(m_hRecvBuffer);
            m_hReader       = new BinaryReader(m_hMs);
        }
コード例 #19
0
        public async Task ComputedPerformanceTest()
        {
            if (TestRunnerInfo.IsBuildAgent())
            {
                return; // Shouldn't run this test on build agents
            }
            var users                    = Services.GetRequiredService <IUserService>();
            var useImdb                  = Options.UseInMemoryDatabase;
            var opCountPerCore           = 2_000_000;
            var readersPerCore           = 4;
            var readerCount              = HardwareInfo.ProcessorCount * readersPerCore;
            var cachingIterationCount    = opCountPerCore / readersPerCore;
            var nonCachingIterationCount = cachingIterationCount / (useImdb ? 1000 : 10_000);

            var cachingProviderPool    = new ConcurrentPool <IUserService>(() => users);
            var nonCachingProviderPool = new ConcurrentPool <IUserService>(() => {
                var scope = Services.CreateScope();
                return(scope.ServiceProvider.GetRequiredService <UserService>());
                // No scope disposal, but it's fine for the test, I guess
            });

            var withoutSerialization = (Action <User>)(u => { });
            var withSerialization    = (Action <User>)(u => JsonConvert.SerializeObject(u));

            Out.WriteLine($"Database: {(useImdb ? "In-memory" : "Sqlite")}");
            Out.WriteLine("With Stl.Fusion:");
            await Test("Standard test", cachingProviderPool, withoutSerialization,
                       readerCount, cachingIterationCount);
            await Test("Standard test + serialization", cachingProviderPool, withSerialization,
                       readerCount, cachingIterationCount / 3);

            Out.WriteLine("Without Stl.Fusion:");
            await Test("Standard test", nonCachingProviderPool, withoutSerialization,
                       readerCount, nonCachingIterationCount);
            await Test("Standard test + serialization", nonCachingProviderPool, withSerialization,
                       readerCount, nonCachingIterationCount);
        }
コード例 #20
0
        public ChunkMeshManager(ChunkManager chunkManager, int concurrencyLevel, int updateBufferCountPerFrame)
        {
            if (chunkManager == null)
            {
                throw new ArgumentNullException("chunkManager");
            }

            this.chunkManager              = chunkManager;
            this.concurrencyLevel          = concurrencyLevel;
            this.updateBufferCountPerFrame = updateBufferCountPerFrame;

            buildVertexRequestPool = new ConcurrentPool <BuildVertexRequest>(() => { return(new BuildVertexRequest()); });
            buildVertexRequests    = new ConcurrentPriorityQueue <BuildVertexRequest>(new BuildVertexRequestComparer());
            updateBufferRequests   = new ConcurrentPriorityQueue <UpdateBufferRequest>(new UpdateBufferRequestComparer());
            vertexBuilderPool      = new ConcurrentPool <ChunkVertexBuilder>(() => { return(new ChunkVertexBuilder(this)); })
            {
                MaxCapacity = concurrencyLevel
            };
            buildVertexTask = new BuildVertexTask(this, OnBuildVertexTaskCallback);

            ChunkSize = chunkManager.ChunkSize;

            MeshSegments = new IntVector3
            {
                X = ChunkSize.X / MeshSize.X,
                Y = ChunkSize.Y / MeshSize.Y,
                Z = ChunkSize.Z / MeshSize.Z
            };

            var halfMeshSize = MeshSize;

            halfMeshSize.X /= 2;
            halfMeshSize.Y /= 2;
            halfMeshSize.Z /= 2;
            MeshOffset      = halfMeshSize.ToVector3();
        }
コード例 #21
0
ファイル: CommandPool.cs プロジェクト: willcraftia/TestBlocks
 public void Register(Type type, Func<PooledCommand> createFunction)
 {
     poolDictionary[type] = new ConcurrentPool<PooledCommand>(createFunction);
 }
コード例 #22
0
 public void Register(Type type, Func <PooledCommand> createFunction)
 {
     poolDictionary[type] = new ConcurrentPool <PooledCommand>(createFunction);
 }
コード例 #23
0
 public void Init()
 {
     poolOfRecycles = new ConcurrentPool<RecycleObj>("Pool of recycles");
 }
コード例 #24
0
 void PercussionDestroy()
 {
     CancelScheduledPercussion();
     audioSourcePool.Dispose();
     audioSourcePool = null;
 }