Beispiel #1
0
        static void _waveIn_DataAvailable(object sender, WaveInEventArgs e)
        {
            var recorderBytes  = e.Buffer.AsSpan(0, e.BytesRecorded);
            var recordedShorts = MemoryMarshal.Cast <byte, short>(recorderBytes);
            //_playBuffer.AddSamples(MemoryMarshal.Cast<short, byte>(recordedShorts).ToArray(), 0, e.BytesRecorded);
            //return;

            var soundBuffer = new short[recordedShorts.Length + _notEncodedBuffer.Length];

            _notEncodedBuffer.CopyTo(soundBuffer, 0);
            recordedShorts.CopyTo(soundBuffer.AsSpan(_notEncodedBuffer.Length));

            int segmentCount = soundBuffer.Length / ShortsPerSegment;

            var willNotEncoded = soundBuffer.AsSpan(segmentCount * ShortsPerSegment);

            _notEncodedBuffer = willNotEncoded.ToArray();

            for (int i = 0; i < segmentCount; i++)
            {
                var segment = soundBuffer.AsSpan(i * ShortsPerSegment, ShortsPerSegment);
                var buff    = _encoder.Encode(segment, segment.Length);
                _bytesSent += (ulong)buff.Length;
                var dec = _decoder.Decode(buff, segment.Length);
                _playBuffer.AddSamples(MemoryMarshal.Cast <short, byte>(dec).ToArray(), 0, dec.Length * 2);
            }
        }
Beispiel #2
0
        private void AudioPlayback()
        {
            Span <byte> buffer = stackalloc byte[512];

            short[] writeBuffer = new short[65536 * 2];

            using var player = Audio.CreatePlayer();
            int sampleRate = (int)player.Format.SampleRate;

            player.BeginPlayback();

            while (!this.endPlayback)
            {
                this.dsp.Read(buffer);
                int length;
                if (this.dsp.Is16Bit && this.dsp.IsStereo)
                {
                    length = LinearUpsampler.Resample16Stereo(dsp.SampleRate, sampleRate, MemoryMarshal.Cast <byte, short>(buffer), writeBuffer);
                }
                else if (this.dsp.Is16Bit)
                {
                    length = LinearUpsampler.Resample16Mono(dsp.SampleRate, sampleRate, MemoryMarshal.Cast <byte, short>(buffer), writeBuffer);
                }
                else if (this.dsp.IsStereo)
                {
                    length = LinearUpsampler.Resample8Stereo(dsp.SampleRate, sampleRate, buffer, writeBuffer);
                }
                else
                {
                    length = LinearUpsampler.Resample8Mono(dsp.SampleRate, sampleRate, buffer, writeBuffer);
                }

                Audio.WriteFullBuffer(player, writeBuffer.AsSpan(0, length));

                if (this.pausePlayback)
                {
                    player.StopPlayback();
                    while (this.pausePlayback)
                    {
                        Thread.Sleep(1);
                    }

                    player.BeginPlayback();
                }

                if (this.pauseDuration > 0)
                {
                    Array.Clear(writeBuffer, 0, writeBuffer.Length);
                    int count = this.pauseDuration / (1024 / 2) + 1;
                    for (int i = 0; i < count; i++)
                    {
                        Audio.WriteFullBuffer(player, writeBuffer.AsSpan(0, 1024));
                    }

                    this.pauseDuration = 0;
                    RaiseInterrupt();
                }
            }
        }
Beispiel #3
0
        public async Task TestSShortCompatibility(int length, bool bigTiff)
        {
            short[] refData = new short[length];
            new Random(42).NextBytes(MemoryMarshal.AsBytes(refData.AsSpan()));

            using Stream stream = await GenerateTiffAsync(bigTiff, async ifd =>
            {
                await ifd.WriteTagAsync((TiffTag) 0x1234, TiffValueCollection.UnsafeWrap(refData));
            });

            await using (TiffFileReader reader = await TiffFileReader.OpenAsync(stream, leaveOpen: true))
            {
                TiffImageFileDirectory ifd = await reader.ReadImageFileDirectoryAsync();

                TiffFieldReader fieldReader = await reader.CreateFieldReaderAsync();

                TiffImageFileDirectoryEntry entry = ifd.FindEntry((TiffTag)0x1234);
                Assert.Equal((TiffTag)0x1234, entry.Tag);

                // Byte
                await TestInvalidConversionAsync <byte>(fieldReader, entry, nameof(fieldReader.ReadByteFieldAsync), refData.Length);

                // SSbyte
                await TestInvalidConversionAsync <sbyte>(fieldReader, entry, nameof(fieldReader.ReadSByteFieldAsync), refData.Length);

                // Short
                await TestValidConversionAsync(fieldReader, entry, nameof(fieldReader.ReadShortFieldAsync), Array.ConvertAll(refData, v => (ushort)v));

                // SShort
                await TestValidConversionAsync(fieldReader, entry, nameof(fieldReader.ReadSShortFieldAsync), refData);

                // Long
                await TestInvalidConversionAsync <uint>(fieldReader, entry, nameof(fieldReader.ReadLongFieldAsync), refData.Length);

                // SLong
                await TestValidConversionAsync(fieldReader, entry, nameof(fieldReader.ReadSLongFieldAsync), Array.ConvertAll(refData, v => (int)v));

                // Float
                await TestInvalidConversionAsync <float>(fieldReader, entry, nameof(fieldReader.ReadFloatFieldAsync), refData.Length);

                // Double
                await TestInvalidConversionAsync <double>(fieldReader, entry, nameof(fieldReader.ReadDoubleFieldAsync), refData.Length);

                // Rational
                await TestInvalidConversionAsync <TiffRational>(fieldReader, entry, nameof(fieldReader.ReadRationalFieldAsync), refData.Length);

                // SRational
                await TestValidConversionAsync(fieldReader, entry, nameof(fieldReader.ReadSRationalFieldAsync), Array.ConvertAll(refData, v => new TiffSRational((int)v, 1)));
            }
        }
        private static void CopyResultVectorsToFilterMask(Vector <int>[] resultVectorList, Span <short> filterMask)
        {
            var remainderVectorCount = resultVectorList.Length % 2;
            var lastVectorGroupIndex = resultVectorList.Length - remainderVectorCount;

            for (var i = 0; i < lastVectorGroupIndex; i += 2)
            {
                //Avx2.LoadVector256()
                //Avx2.PackSignedSaturate()
                //Vector.Narrow(
                //    Vector.Narrow(resultVectorList[i], resultVectorList[i + 1]),
                //    Vector.Narrow(resultVectorList[i + 2], resultVectorList[i + 3])
                //).CopyTo(filterMask.Slice(i * Vector<int>.Count));
                Vector
                .Narrow(resultVectorList[i], resultVectorList[i + 1])
                .CopyTo(filterMask.Slice(i * Vector <int> .Count));
            }
            if (remainderVectorCount == 0)
            {
                return;
            }
            var remainderVectors = new Vector <int> [2];
            int j = 0;

            for (var i = lastVectorGroupIndex; i < resultVectorList.Length; i++)
            {
                remainderVectors[j++] = resultVectorList[i];
            }
            for (; j < 2; j++)
            {
                remainderVectors[j] = Vector <int> .Zero;
            }
            //var narrowedVector = Vector.Narrow(
            //        Vector.Narrow(remainderVectors[0], remainderVectors[1]),
            //        Vector.Narrow(remainderVectors[2], remainderVectors[3]));
            var narrowedVector = Vector.Narrow(remainderVectors[0], remainderVectors[1]);
            var tempByteArray  = new short[Vector <short> .Count];

            narrowedVector.CopyTo(tempByteArray);
            tempByteArray
            .AsSpan(0, Vector <int> .Count * remainderVectorCount)
            .CopyTo(filterMask.Slice(lastVectorGroupIndex * Vector <int> .Count));

            //var narrowedVector = Vector.Narrow(
            //    Vector.Narrow(new Vector<int>(-1), Vector<int>.Zero),
            //    Vector.Narrow(Vector<int>.Zero, Vector<int>.Zero));
            //Console.WriteLine("narrowed vector: {0}", narrowedVector);
        }
Beispiel #5
0
        public void EncodeDecode_WithData_DecodesToOriginal()
        {
            // arrange
            short[] audio   = Enumerable.Range(200, 160).Select(u => (short)u).ToArray();
            byte[]  encoded = new byte[320];

            // act
            _rawCodec.Encode(audio, encoded.AsSpan());
            var audioData = new AudioData();

            audioData.Data = encoded.AsSpan();
            short[] decoded = new short[160];
            _rawCodec.Decode(audioData, false, decoded);

            // assert
            SpanAssert.AreEqual(audio.AsSpan(), decoded.AsSpan());
        }
Beispiel #6
0
        /// <summary>
        /// Produces PCM samples from Opus encoded data.
        /// </summary>
        /// <param name="data">Opus encoded data to decode, null for dropped packet.</param>
        /// <returns>PCM audio samples.</returns>
        public ReadOnlySpan <short> Decode(ReadOnlySpan <byte> data, int frameSize)
        {
            CheckDisposed();

            var decoded = new short[MaxDataBytes];
            int length  = 0;

            if (data != null)
            {
                length = _api.opus_decode(_decoderState, data.ToArray(), data.Length, decoded, frameSize, 0);
            }
            else
            {
                length = _api.opus_decode(_decoderState, null, 0, decoded, frameSize, (IsForwardErrorCorrectionEnabled) ? 1 : 0);
            }

            if (length < 0)
            {
                throw new Exception("Decoding failed - " + ((Error)length).ToString());
            }

            return(decoded.AsSpan(0, length));
        }
        public void CopyTo_Roundtrip_MatchesOriginalInput(short[] values)
        {
            int    sizeOfArray = sizeof(short) * values.Length;
            IntPtr ptr         = Marshal.AllocCoTaskMem(sizeOfArray);

            try
            {
                Marshal.Copy(values, 0, ptr, values.Length);

                short[] array1 = new short[values.Length];
                Marshal.Copy(ptr, array1, 0, values.Length);
                Assert.Equal <short>(values, array1);

                Marshal.Copy(values, 2, ptr, values.Length - 4);
                short[] array2 = new short[values.Length];
                Marshal.Copy(ptr, array2, 2, values.Length - 4);
                Assert.Equal <short>(values.AsSpan(2, values.Length - 4).ToArray(), array2.AsSpan(2, values.Length - 4).ToArray());
            }
            finally
            {
                Marshal.FreeCoTaskMem(ptr);
            }
        }
Beispiel #8
0
        public void CopyRoundTrip_MatchesOriginalArray(short[] TestArray)
        {
            int    sizeOfArray = sizeof(short) * TestArray.Length;
            IntPtr ptr         = Marshal.AllocCoTaskMem(sizeOfArray);

            try
            {
                Marshal.Copy(TestArray, 0, ptr, TestArray.Length);

                short[] array1 = new short[TestArray.Length];
                Marshal.Copy(ptr, array1, 0, TestArray.Length);
                Assert.Equal <short>(TestArray, array1);

                Marshal.Copy(TestArray, 2, ptr, TestArray.Length - 4);
                short[] array2 = new short[TestArray.Length];
                Marshal.Copy(ptr, array2, 2, TestArray.Length - 4);
                Assert.Equal <short>(TestArray.AsSpan(2, TestArray.Length - 4).ToArray(), array2.AsSpan(2, TestArray.Length - 4).ToArray());
            }
            finally
            {
                Marshal.FreeCoTaskMem(ptr);
            }
        }