Example #1
0
 public unsafe ComplexFilter(Complex[] kernel)
     : base(ComplexFilter.GetFFTSize(kernel.Length))
 {
     this._kernelBuffer = UnsafeBuffer.Create(this.FFTSize, sizeof (Complex));
       this._kernelPtr = (Complex*) (void*) this._kernelBuffer;
       this.SetKernel(kernel);
 }
 public void Process(Complex* iq, int length)
 {
     if (_autoBalanceIQ && length >= FFTBins)
     {
         RemoveDC(iq, length);
         _iqPtr = iq;
         EstimateImbalance();
         Adjust(iq, length, _phase, _gain);
     }
 }
Example #3
0
        static Fourier()
        {
            _lut = (Complex*) _lutBuffer;

            const double angle = TwoPi / MaxLutBins;

            for (var i = 0; i < LutSize; i++)
            {
                _lut[i] = Complex.FromAngle(angle * i).Conjugate();
            }
        }
Example #4
0
 public unsafe OverlapSaveProcessor(int fftSize)
 {
     this._fftSize = fftSize;
       this._halfSize = this._fftSize / 2;
       this._inputPos = this._halfSize;
       this._queuepBuffer = UnsafeBuffer.Create(this._fftSize, sizeof (Complex));
       this._queuePtr = (Complex*) (void*) this._queuepBuffer;
       this._fftBuffer = UnsafeBuffer.Create(this._fftSize, sizeof (Complex));
       this._fftPtr = (Complex*) (void*) this._fftBuffer;
       this._outputBuffer = UnsafeBuffer.Create(this._halfSize, sizeof (Complex));
       this._outputPtr = (Complex*) (void*) this._outputBuffer;
 }
Example #5
0
        private void PopulateGreen(Complex *ptr, int xSym, int ySym, int i, int j)
        {
            long shift = _layoutShiftFactor * (i * _ny2 + j);

            long shiftXSym  = _layoutShiftFactor * ((_nx2 - i) * _ny2 + j);
            long shiftYSym  = _layoutShiftFactor * (i * _ny2 + _ny2 - j);
            long shiftXYSym = _layoutShiftFactor * ((_nx2 - i) * _ny2 + _ny2 - j);

            var src = ptr + shift;

            UNM.Zaxpy(_length, xSym, src, _layoutStep, ptr + shiftXSym, _layoutStep);
            UNM.Zaxpy(_length, ySym, src, _layoutStep, ptr + shiftYSym, _layoutStep);
            UNM.Zaxpy(_length, xSym * ySym, src, _layoutStep, ptr + shiftXYSym, _layoutStep);
        }
Example #6
0
        private void InitFFTBuffers()
        {
            _iqBuffer          = UnsafeBuffer.Create(_fftBins, sizeof(Complex));
            _fftBuffer         = UnsafeBuffer.Create(_fftBins, sizeof(Complex));
            _fftWindow         = UnsafeBuffer.Create(_fftBins, sizeof(float));
            _fftSpectrum       = UnsafeBuffer.Create(_fftBins, sizeof(float));
            _scaledFFTSpectrum = UnsafeBuffer.Create(_fftBins, sizeof(byte));

            _iqPtr                = (Complex *)_iqBuffer;
            _fftPtr               = (Complex *)_fftBuffer;
            _fftWindowPtr         = (float *)_fftWindow;
            _fftSpectrumPtr       = (float *)_fftSpectrum;
            _scaledFFTSpectrumPtr = (byte *)_scaledFFTSpectrum;
        }
Example #7
0
        public SingleScalarSegment()
        {
            I1A = null;
            I2A = null;
            I3A = null;
            I4A = null;
            I5A = null;

            I1B = null;
            I2B = null;
            I3B = null;
            I4B = null;
            I5B = null;
        }
        private unsafe void Configure()
        {
            this._index = 0;
            this._sum   = 0f;
            this._averagingWindowLength = (int)((double)NoiseBlankerProcessor.AveragingWindow * 1E-06 * this._sampleRate);
            this._norm     = 1f / (float)this._averagingWindowLength;
            this._ratio    = ((float)(100 - this._threshold) * 0.1f + 1f) * this._norm;
            this._delay    = UnsafeBuffer.Create((2 * this._averagingWindowLength + 1) * 2, sizeof(Complex));
            this._delayPtr = (Complex *)(void *)this._delay;
            double num = Math.Min(Math.Max(this._pulseWidth * 1E-06 * this._sampleRate, 1.0), (double)this._averagingWindowLength);

            this._blankingWindowLength = (int)num;
            this._alpha = 1f / (float)this._blankingWindowLength;
        }
 public void Dispose()
 {
     if (m_iqBuffer != null)
     {
         m_iqBuffer.Dispose();
         m_iqBuffer    = null;
         m_iqBufferPtr = null;
     }
     if (m_gui != null)
     {
         m_gui.Dispose();
     }
     GC.SuppressFinalize(this);
 }
Example #10
0
        private void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // Free other state (managed objects)
                }
                UnmanagedMemory.Free(electric_field);
                electric_field = null;

                disposed = true;
            }
        }
        private unsafe void ReceiveSamples_sync()
        {
            lms_stream_meta_t meta = new lms_stream_meta_t();

            meta.timestamp          = 0;
            meta.flushPartialPacket = false;
            meta.waitForTimestamp   = false;

            while (_isStreaming)
            {
                if (_iqBuffer == null || _iqBuffer.Length != _readLength)
                {
                    _iqBuffer = UnsafeBuffer.Create((int)_readLength, sizeof(Complex));
                    _iqPtr    = (Complex *)_iqBuffer;
                    Thread.Sleep(100);
                }

                if (_samplesBuffer == null || _samplesBuffer.Length != (2 * _readLength))
                {
                    _samplesBuffer = UnsafeBuffer.Create((int)(2 * _readLength), sizeof(float));
                    _samplesPtr    = (float *)_samplesBuffer;
                    Thread.Sleep(100);
                }

                var ptrIq = _iqPtr;

                if (test_signal)
                {
                    SineWaveWithNoise(ptrIq, _readLength, phase_accumulator1, sine_freq1);
                    phase_accumulator1 = CosineWaveWithNoise(ptrIq, _readLength, phase_accumulator1, sine_freq1);
                }
                else
                {
                    NativeMethods.LMS_RecvStream(_stream, _samplesPtr, _readLength, ref meta, SampleTimeoutMs);

                    for (int i = 0; i < _readLength; i++)
                    {
                        ptrIq->Real = _samplesPtr[i * 2] / SpectrumOffset;
                        ptrIq->Imag = _samplesPtr[i * 2 + 1] / SpectrumOffset;
                        ptrIq++;
                    }
                }

                ComplexSamplesAvailable(_iqPtr, _iqBuffer.Length);
            }

            NativeMethods.LMS_StopStream(_stream);
            Close();
        }
Example #12
0
 internal ComplexFirFilterGeneric(Complex[] coeffs, int decimation)
 {
     VolkApi.WarnVolk();
     coeffsBuffer          = UnsafeBuffer.Create(coeffs.Length, out coeffsBufferPtr);
     insampBuffer          = UnsafeBuffer.Create(coeffs.Length * 2, out insampBufferPtr);
     insampBufferPtrOffset = insampBufferPtr + coeffs.Length;
     taps            = coeffs.Length;
     this.decimation = decimation;
     decimationIndex = 0;
     offset          = 0;
     for (int i = 0; i < coeffs.Length; i++)
     {
         coeffsBufferPtr[i] = coeffs[i];
     }
 }
Example #13
0
        public unsafe static void InverseTransform(Complex *samples, int length)
        {
            for (int i = 0; i < length; i++)
            {
                samples[i].Imag = 0f - samples[i].Imag;
            }
            Fourier.ForwardTransform(samples, length, false);
            float num = 1f / (float)length;

            for (int j = 0; j < length; j++)
            {
                samples[j].Real *= num;
                samples[j].Imag  = (0f - samples[j].Imag) * num;
            }
        }
Example #14
0
        public unsafe void _Work(Complex *input, float *output, int length)
        {
            if (tempLength != length)
            {
                temporaryBuffer = DataBuffer.Create(length, sizeof(Complex));
                tempPtr         = (Complex *)temporaryBuffer;
                tempLength      = length;
            }

            VMath.MultiplyByConjugate(ref tempPtr, &input[1], input, length);
            for (int i = 0; i < length; i++)
            {
                output[i] = (float)(Gain * Math.Atan2(tempPtr[i].imag, tempPtr[i].real));
            }
        }
Example #15
0
        Complex dotprod_halfband_4(Complex *a, float *b)
        {
            Complex sum = new Complex(0, 0);
            int     i;

            for (i = 0; i < 7; i += 2)
            {
                sum.Real += ((a[i].Real + a[14 - i].Real) * b[i]); //>> 15;
                sum.Imag += ((a[i].Imag + a[14 - i].Imag) * b[i]); //>> 15;
            }
            sum.Real += a[7].Real;
            sum.Imag += a[7].Imag;

            return(sum);
        }
Example #16
0
        Complex dotprod_32(Complex *a, float *b)
        {
            Complex sum = new Complex(0, 0);
            int     i;

            for (i = 1; i < 16; i++)
            {
                sum.Real += ((a[i].Real + a[32 - i].Real) * b[i * 2]); //>> 15;
                sum.Imag += ((a[i].Imag + a[32 - i].Imag) * b[i * 2]); //>> 15;
            }
            sum.Real += (a[i].Real * b[i * 2]);                        //>> 15
            sum.Imag += (a[i].Imag * b[i * 2]);                        //>> 15

            return(sum);
        }
Example #17
0
 public unsafe void process(Complex *input, float *output, int length)
 {
     for (int i = 0; i < length; i++)
     {
         Complex complex = input[i] * _lastIq.Conjugate();
         float   mod     = complex.Modulus();
         if (mod > 0f)
         {
             complex /= mod;
         }
         float argument = complex.Argument();
         output[i] = argument * _gain;
         _lastIq   = input[i];
     }
 }
Example #18
0
 public unsafe void Dispose()
 {
     this._coeffBuffer = null;
     this._queueBuffer = null;
     this._coeffPtr    = null;
     this._queuePtr    = null;
     this._segment     = null;
     this._segPtr      = null;
     this._kernel      = null;
     this._kerPtr      = null;
     this._overlap     = null;
     this._olaPtr      = null;
     this._tmpPtr      = null;
     GC.SuppressFinalize(this);
 }
        private void Configure()
        {
            _index = 0;
            _sum   = 0;
            _averagingWindowLength = (int)(AveragingWindow * 1e-6 * _sampleRate);
            _norm     = 1.0f / _averagingWindowLength;
            _ratio    = ((100 - _threshold) * 0.1f + 1) * _norm;
            _delay    = UnsafeBuffer.Create((2 * _averagingWindowLength + 1) * SizeFactor, sizeof(Complex));
            _delayPtr = (Complex *)_delay;

            var length = Math.Min(Math.Max(_pulseWidth * 1e-6 * _sampleRate, 1), _averagingWindowLength);

            _blankingWindowLength = (int)length;
            _alpha = 1.0f / _blankingWindowLength;
        }
Example #20
0
        public unsafe static void BackwardTransform(Complex *buffer, int length)
        {
            for (int i = 0; i < length; i++)
            {
                buffer[i].Imag = 0f - buffer[i].Imag;
            }
            Fourier.ForwardTransform(buffer, length, false);
            float num = 1f / (float)length;

            for (int j = 0; j < length; j++)
            {
                buffer[j].Real *= num;
                buffer[j].Imag  = (0f - buffer[j].Imag) * num;
            }
        }
Example #21
0
        /// <summary>
        /// Fills the current matrix with (pseudo-)random values from the specified interval.
        /// </summary>
        /// <param name="minReal">The minimum real value.</param>
        /// <param name="maxReal">The maximum real value.</param>
        /// <param name = "minImag">The minimum imaginary value.</param>
        /// <param name = "maxImag">The maximum imaginary value.</param>
        public unsafe void FillWithRandomValues(double minReal, double maxReal, double minImag, double maxImag)
        {
            var      rnd         = new Random();
            double   rangeReal   = maxReal - minReal;
            double   rangeImag   = maxImag - minImag;
            Complex *pThis       = this.Data;
            var      pThisDouble = (double *)pThis;
            int      complexSize = this.TotalSize * 2;

            for (int i = 0; i < complexSize; i += 2)
            {
                pThisDouble[i]     = rnd.NextDouble() * rangeReal + minReal;
                pThisDouble[i + 1] = rnd.NextDouble() * rangeImag + minImag;
            }
        }
Example #22
0
        public unsafe void updateData(Complex *c, int length)
        {
            FFTWComplex *id = (FFTWComplex *)_input;

            if (length != _bins)
            {
                Console.WriteLine("Warning! Reallocing SFFT!");
                realloc(length);
            }
            for (int i = 0; i < length; i++)
            {
                id[i].imag = c[i].imag;
                id[i].real = c[i].real;
            }
        }
        /// <summary>
        ///   Processes the filter.
        /// </summary>
        ///
        protected unsafe override void ProcessFilter(ComplexSignal sourceData, ComplexSignal destinationData)
        {
            int length = sourceData.Length;

            Complex *src = (Complex *)sourceData.Data.ToPointer();
            Complex *dst = (Complex *)destinationData.Data.ToPointer();

            for (int i = 0; i < length - 1; i++, src++, dst++)
            {
                double re = src[i + 1].Real - src[i].Real;

                // Retain only if difference is positive
                *dst = (re > 0) ? new Complex(re, 0) : Complex.Zero;
            }
        }
Example #24
0
 internal static extern unsafe void ZGEMM(
     int order,
     int transA,
     int transB,
     int m,
     int n,
     int k,
     Complex *alpha,
     Complex *a,
     int lda,
     Complex *b,
     int ldb,
     Complex *beta,
     Complex *c,
     int ldc);
Example #25
0
        public static unsafe void _DotProduct(out Complex result, Complex *input, float *taps, int length)
        {
            float[] res = { 0, 0 };

            float *iPtr = (float *)input;
            float *tPtr = taps;

            for (int i = 0; i < length; i++)
            {
                res[0] += ((*iPtr++) * (*tPtr));
                res[1] += ((*iPtr++) * (*tPtr++));
            }

            result = new Complex(res[0], res[1]);
        }
Example #26
0
        private void ProcessSamples(byte[] buffer, int actualLength)
        {
            const float scale24 = 1.0f / 2147483647.0f;
            const float scale16 = 1.0f / 32768.0f;

            var seq = (ushort)buffer[3] << 8 | buffer[2];

            if (seq != _nextSequence && _nextSequence != 0)
            {
                _lostPacketsCount++;
            }
            _nextSequence = (ushort)(seq + 1);

            if (!_is16Bit)
            {
                for (var i = 4; i < actualLength; i += 6)
                {
                    _workingSamplePtr->Imag = (float)((int)(buffer[i + 2] << 24 | buffer[i + 1] << 16 | buffer[i] << 8)) * scale24;
                    _workingSamplePtr->Real = (float)((int)(buffer[i + 5] << 24 | buffer[i + 4] << 16 | buffer[i + 3] << 8)) * scale24;
                    _workingSamplePtr++;
                    _sampleCount++;
                }

                if (_sampleCount >= 240 * 2)
                {
                    _callback(this, _sampleBufferPtr, _sampleCount);
                    _workingSamplePtr = (Complex *)_sampleBufferPtr;
                    _sampleCount      = 0;
                }
            }
            else
            {
                for (var i = 4; i < actualLength; i += 4)
                {
                    _workingSamplePtr->Imag = (float)((short)((buffer[i + 1] << 8) | buffer[i])) * scale16;
                    _workingSamplePtr->Real = (float)((short)((buffer[i + 3] << 8) | buffer[i + 2])) * scale16;
                    _workingSamplePtr++;
                    _sampleCount++;
                }

                if (_sampleCount >= 256 * 2)
                {
                    _callback(this, _sampleBufferPtr, _sampleCount);
                    _workingSamplePtr = (Complex *)_sampleBufferPtr;
                    _sampleCount      = 0;
                }
            }
        }
Example #27
0
        /// <summary>
        /// Processes the filter.
        /// </summary>
        ///
        protected override void ProcessFilter(ComplexSignal sourceData, ComplexSignal destinationData)
        {
            int samples = sourceData.Samples;

            unsafe
            {
                Complex *src  = (Complex *)sourceData.Data.ToPointer();
                Complex *dst  = (Complex *)destinationData.Data.ToPointer();
                Complex *comb = (Complex *)combSignal.Data.ToPointer();

                for (int i = 0; i < samples; i++, src++, dst++, comb++)
                {
                    *dst = new Complex((src[0] * comb[0]).Magnitude, 0);
                }
            }
        }
        private void CopyToBuffer(int start, int length, int layerSize, int nzSize, Complex *ptr)
        {
            var nz3 = 3 * Model.Nz;
            var dst = Pool.Plan3Nz.Buffer1Ptr;

            for (int i = 0; i < layerSize; i++)
            {
                long srcShift = nzSize * i + start;
                long dstShift = i * nz3;

                for (int k = 0; k < length; k++)
                {
                    dst[dstShift + k] = ptr[srcShift + k];
                }
            }
        }
        /// <summary>Gets a optimal workspace array length for the <c>zhetrf</c> function.
        /// </summary>
        /// <param name="n">The order of the matrix.</param>
        /// <param name="triangularMatrixType">A value indicating whether the upper or lower triangular part of matrix A is stored and how matrix A is factored.</param>
        /// <returns>The optimal workspace array length.</returns>
        /// <remarks>The parameter <paramref name="triangularMatrixType"/> should not have an impact of the calculation of the optimal length of the workspace array.</remarks>
        public int zhetrfQuery(int n, BLAS.TriangularMatrixType triangularMatrixType = BLAS.TriangularMatrixType.LowerTriangularMatrix)
        {
            var lwork = -1;
            var uplo  = LAPACK.GetUplo(triangularMatrixType);

            unsafe
            {
                Complex *work = stackalloc Complex[1];

                int info;
                _zhetrf(ref uplo, ref n, null, ref n, null, work, ref lwork, out info);
                CheckForError(info, "zhetrf");

                return(((int)work[0].Real) + 1);
            }
        }
Example #30
0
        public static void IFFT(Complex *input, Complex *output, Complex *scratchpad, int len)
        {
            var scale    = 1.0f / len;
            var scaleNeg = -scale;

            TVal *scratchPtr = (TVal *)scratchpad;
            TVal *inputPtr   = (TVal *)input;

            for (int i = 0; i < len * 2; i += 2)
            {
                scratchPtr[i]     = inputPtr[i] * scale;
                scratchPtr[i + 1] = inputPtr[i + 1] * scaleNeg;
            }

            FFT(scratchpad, output, scratchpad, len);
        }
Example #31
0
        void kiss_fftr(float *timedata, Complex *freqdata)
        {
            /* input buffer timedata is stored row-wise */
            int     k     = 0;
            int     ncfft = 0;
            Complex fpnk  = 0;
            Complex fpk   = 0;
            Complex f1k   = 0;
            Complex f2k   = 0;
            Complex tw    = 0;
            Complex tdc   = 0;

            /*perform the parallel fft of two real signals packed in real,imag*/
            kf_work(this.tmpbuf, (Complex *)timedata, 1, 1, factors);

            /* The real part of the DC element of the frequency spectrum in this.tmpbuf
             * contains the sum of the even-numbered elements of the input time sequence
             * The imag part is the sum of the odd-numbered elements
             *
             * The sum of tdc.r and tdc.i is the sum of the input time sequence.
             *      yielding DC of input time sequence
             * The difference of tdc.r - tdc.i is the sum of the input (dot product) [1,-1,1,-1...
             *      yielding Nyquist bin of input time sequence
             */

            tdc.Real             = this.tmpbuf[0].Real;
            tdc.Imag             = this.tmpbuf[0].Imag;
            freqdata[0].Real     = tdc.Real + tdc.Imag;
            freqdata[ncfft].Real = tdc.Real - tdc.Imag;
            freqdata[ncfft].Imag = freqdata[0].Imag = 0;

            for (k = 1; k <= ncfft / 2; ++k)
            {
                fpk       = this.tmpbuf[k];
                fpnk.Real = this.tmpbuf[ncfft - k].Real;
                fpnk.Imag = -this.tmpbuf[ncfft - k].Imag;

                C_ADD(&f1k, fpk, fpnk);
                C_SUB(&f2k, fpk, fpnk);
                C_MUL(&tw, f2k, this.super_twiddles[k - 1]);

                freqdata[k].Real         = (f1k.Real + tw.Real) / 2;
                freqdata[k].Imag         = (f1k.Imag + tw.Imag) / 2;
                freqdata[ncfft - k].Real = (f1k.Real - tw.Real) / 2;
                freqdata[ncfft - k].Imag = (tw.Imag - f1k.Imag) / 2;
            }
        }
Example #32
0
 private void FillIQ(Complex *iqPtr, int length)
 {
     if (_isPCM)
     {
         if (_blockAlign == 6)
         {
             const float scale = 1.0f / 8388607.0f;
             var         ptr   = (Int24 *)_tempPtr;
             for (var i = 0; i < length; i++)
             {
                 iqPtr->Real = *ptr++ *scale;
                 iqPtr->Imag = *ptr++ *scale;
                 iqPtr++;
             }
         }
         else if (_blockAlign == 4)
         {
             var ptr = (Int16 *)_tempPtr;
             for (var i = 0; i < length; i++)
             {
                 iqPtr->Real = _lut16[*ptr++ + 32768];
                 iqPtr->Imag = _lut16[*ptr++ + 32768];
                 iqPtr++;
             }
         }
         else if (_blockAlign == 2)
         {
             var ptr = _tempPtr;
             for (var i = 0; i < length; i++)
             {
                 iqPtr->Real = _lutu8[*ptr++];
                 iqPtr->Imag = _lutu8[*ptr++];
                 iqPtr++;
             }
         }
     }
     else
     {
         var ptr = (float *)_tempPtr;
         for (var i = 0; i < length; i++)
         {
             iqPtr->Real = *ptr++;
             iqPtr->Imag = *ptr++;
             iqPtr++;
         }
     }
 }
Example #33
0
        public unsafe Contour AutoCorrelation(bool normalize)
        {
            int     capacity = this.Count / 2;
            Contour contour  = new Contour(capacity);

            fixed(Complex *complexRef = ((Complex *)contour.array[0]))
            {
                Complex *complexPtr = complexRef;
                double   d          = 0.0;
                int      shift      = 0;

                while (true)
                {
                    bool flag = shift < capacity;
                    if (!flag)
                    {
                        if (normalize)
                        {
                            d          = Math.Sqrt(d);
                            complexPtr = complexRef;
                            shift      = 0;
                            while (true)
                            {
                                flag = shift < capacity;
                                if (!flag)
                                {
                                    break;
                                }
                                complexPtr[0] = new Complex(complexPtr->a / d, complexPtr->b / d);
                                complexPtr++;
                                shift++;
                            }
                        }
                        complexRef = ref null;
                        return(contour);
                    }
                    complexPtr[0] = this.Dot(this, shift);
                    double normaSquare = complexPtr.NormaSquare;
                    if (normaSquare > d)
                    {
                        d = normaSquare;
                    }
                    complexPtr++;
                    shift++;
                }
            }
        }
Example #34
0
 private unsafe void ProcessStandard(Complex *buffer, int length)
 {
     if (this._queueBuffer != null)
     {
         for (int i = 0; i < length; i++)
         {
             Complex *ptr = this._queuePtr + this._offset;
             *        ptr = buffer[i];
             this._acc.Real = 0f;
             this._acc.Imag = 0f;
             int      num  = this._queueSize;
             Complex *ptr2 = ptr;
             Complex *ptr3 = this._coeffPtr;
             if (num >= 4)
             {
                 do
                 {
                     Complex.Mul(ref this._acc, *ptr2, *ptr3);
                     Complex.Mul(ref this._tmp, ptr2[1], ptr3[1]);
                     Complex.Add(ref this._acc, this._tmp);
                     Complex.Mul(ref this._tmp, ptr2[2], ptr3[2]);
                     Complex.Add(ref this._acc, this._tmp);
                     Complex.Mul(ref this._tmp, ptr2[3], ptr3[3]);
                     Complex.Add(ref this._acc, this._tmp);
                     ptr2 += 4;
                     ptr3 += 4;
                 }while ((num -= 4) >= 4);
             }
             while (num-- > 0)
             {
                 ref Complex tmp    = ref this._tmp;
                 Complex *   intPtr = ptr2;
                 ptr2 = intPtr + 1;
                 Complex  c       = *intPtr;
                 Complex *intPtr2 = ptr3;
                 ptr3 = intPtr2 + 1;
                 Complex.Mul(ref tmp, c, *intPtr2);
                 Complex.Add(ref this._acc, this._tmp);
             }
             if (--this._offset < 0)
             {
                 this._offset = this._queueSize * 3;
                 Utils.Memcpy(this._queuePtr + this._offset + 1, this._queuePtr, (this._queueSize - 1) * sizeof(Complex));
             }
             buffer[i] = this._acc;
         }
     }
Example #35
0
        public FftProcessor(int fftSize)
        {            
            _fftSize = fftSize;
            _halfSize = fftSize / 2;
            _overlapSize = (int) Math.Ceiling(_fftSize * OverlapRatio);
            _fftBufferPos = _halfSize;

            _blendFactor = 1.0f / _overlapSize;

            _fftBuffer = UnsafeBuffer.Create(fftSize, sizeof(Complex));
            _fftBufferPtr = (Complex*)_fftBuffer;

            _outOverlapBuffer = UnsafeBuffer.Create(_overlapSize, sizeof(float));
            _outOverlapPtr = (float*) _outOverlapBuffer;

            _overlapBuffer = UnsafeBuffer.Create(fftSize / 2, sizeof(float));
            _overlapBufferPtr = (float*)_overlapBuffer;

            _sampleBuffer = UnsafeBuffer.Create(fftSize, sizeof(float));
            _sampleBufferPtr = (float*)_sampleBuffer;
            _sampleBufferHead = _halfSize;
        }
Example #36
0
 public unsafe OverlapAddProcessor(int fftSize)
 {
     this._fftSize = fftSize;
       this._halfSize = this._fftSize / 2;
       this._inputPos = this._halfSize;
       this._queuepBuffer = UnsafeBuffer.Create(this._fftSize, sizeof (Complex));
       this._queuePtr = (Complex*) (void*) this._queuepBuffer;
       this._windowBuffer = UnsafeBuffer.Create(this._fftSize, 4);
       this._windowPtr = (float*) (void*) this._windowBuffer;
       this._fftBuffer = UnsafeBuffer.Create(this._fftSize, sizeof (Complex));
       this._fftPtr = (Complex*) (void*) this._fftBuffer;
       this._outputBuffer = UnsafeBuffer.Create(this._halfSize, sizeof (Complex));
       this._outputPtr = (Complex*) (void*) this._outputBuffer;
       this._overlapBuffer = UnsafeBuffer.Create(this._halfSize, sizeof (Complex));
       this._overlapPtr = (Complex*) (void*) this._overlapBuffer;
       double num = Math.PI / 2.0 / (double) (this._halfSize - 1);
       for (int index = 0; index < this._halfSize; ++index)
       {
     double a = (double) index * num;
     this._windowPtr[index] = (float) Math.Sin(a);
     this._windowPtr[this._fftSize - 1 - index] = this._windowPtr[index];
       }
 }
 public unsafe OverlapCrossfadeProcessor(int fftSize, float crossFadingRatio = 0.0f)
 {
     this._fftSize = fftSize;
       this._halfSize = this._fftSize / 2;
       this._crossFadingSize = (int) ((double) this._halfSize * (double) crossFadingRatio);
       this._outputSize = this._halfSize - this._crossFadingSize;
       this._inputPos = this._halfSize + this._crossFadingSize;
       this._queuepBuffer = UnsafeBuffer.Create(this._fftSize, sizeof (Complex));
       this._queuePtr = (Complex*) (void*) this._queuepBuffer;
       this._windowBuffer = UnsafeBuffer.Create(this._crossFadingSize, 4);
       this._windowPtr = (float*) (void*) this._windowBuffer;
       this._fftBuffer = UnsafeBuffer.Create(this._fftSize, sizeof (Complex));
       this._fftPtr = (Complex*) (void*) this._fftBuffer;
       this._outputBuffer = UnsafeBuffer.Create(this._outputSize, sizeof (Complex));
       this._outputPtr = (Complex*) (void*) this._outputBuffer;
       this._crossFadingBuffer = UnsafeBuffer.Create(this._crossFadingSize, sizeof (Complex));
       this._crossFadingPtr = (Complex*) (void*) this._crossFadingBuffer;
       double num = Math.PI / 2.0 / (double) (this._crossFadingSize - 1);
       for (int index = 0; index < this._crossFadingSize; ++index)
       {
     double a = (double) index * num;
     this._windowPtr[index] = (float) Math.Pow(Math.Sin(a), 2.0);
       }
 }
Example #38
0
        private void DSPProc()
        {
            #region Prepare buffers

            if (_dspInBuffer == null || _dspInBuffer.Length != _inputBufferSize)
            {
                _dspInBuffer = UnsafeBuffer.Create(_inputBufferSize, sizeof(Complex));
                _dspInPtr = (Complex*) _dspInBuffer;
            }

            if (_dspOutBuffer == null || _dspOutBuffer.Length != _outputBufferSize)
            {
                _dspOutBuffer = UnsafeBuffer.Create(_outputBufferSize, sizeof(float));
                _dspOutPtr = (float*) _dspOutBuffer;
            }

            #endregion
            
            while (IsPlaying)
            {
                var total = 0;
                while (IsPlaying && total < _dspInBuffer.Length)
                {
                    var len = _dspInBuffer.Length - total;
                    total += _iqStream.Read(_dspInPtr, total, len); // Blocking read
                }

                ProcessIQHooks();

                ProcessIQ();

                ProcessAudioHooks();

                _audioStream.Write(_dspOutPtr, _dspOutBuffer.Length); // Blocking write
            }
        }
Example #39
0
 public unsafe void Dispose()
 {
     if (this._sampleBuffer == null)
     return;
       this._sampleBuffer.Dispose();
       this._sampleBufferPtr = (Complex*) null;
       this._workingSamplePtr = (Complex*) null;
 }
Example #40
0
 public static unsafe void StartHW(int freq)
 {
     if (ExtIO._dllHandle == IntPtr.Zero || ExtIO._startHW == null)
     return;
       ExtIO._iqBuffer = (UnsafeBuffer) null;
       ExtIO._iqPtr = (Complex*) null;
       int num = ExtIO._startHW(freq);
       if (num < 0)
     throw new Exception("ExtIO StartHW() returned " + (object) num);
       ExtIO._isHWStarted = true;
       ExtIO._sampleCount = num;
       ExtIO._iqBuffer = UnsafeBuffer.Create(ExtIO._sampleCount, sizeof (Complex));
       ExtIO._iqPtr = (Complex*) (void*) ExtIO._iqBuffer;
 }
        private void Configure()
        {
            _index = 0;
            _sum = 0;
            _averagingWindowLength = (int) (AveragingWindow * 1e-6 * _sampleRate);
            _norm = 1.0f / _averagingWindowLength;
            _ratio = ((100 - _threshold) * 0.1f + 1) * _norm;
            _delay = UnsafeBuffer.Create((2 * _averagingWindowLength + 1) * SizeFactor, sizeof(Complex));
            _delayPtr = (Complex*) _delay;

            var length = Math.Min(Math.Max(_pulseWidth * 1e-6 * _sampleRate, 1), _averagingWindowLength);
            _blankingWindowLength = (int) length;
            _alpha = 1.0f / _blankingWindowLength;
        }
Example #42
0
 private void RecieveSamples()
 {
     var recBuffer = new byte[_bufferSize];
     var recUnsafeBuffer = UnsafeBuffer.Create(recBuffer);
     var recPtr = (byte*) recUnsafeBuffer;
     _iqBuffer = UnsafeBuffer.Create(_bufferSize / 2, sizeof(Complex));
     _iqBufferPtr = (Complex*) _iqBuffer;
     var offs = 0;                        
     while (_s != null && _s.Connected)
     {
         try
         {
             var bytesRec = _s.Receive(recBuffer, offs, _bufferSize - offs, SocketFlags.None);
             var totalBytes = offs + bytesRec;
             offs = totalBytes % 2; //Need to correctly handle the hypothetical case where we somehow get an odd number of bytes
             ProcessSamples(recPtr, totalBytes - offs); //This might work.
             if (offs == 1)
             {
                 recPtr[0] = recPtr[totalBytes - 1];
             }
         }
         catch
         {
             Close();
             break;
         }
     }            
 }
Example #43
0
        private void InitFFTBuffers()
        {
            _iqBuffer = UnsafeBuffer.Create(_fftBins, sizeof(Complex));
            _fftBuffer = UnsafeBuffer.Create(_fftBins, sizeof(Complex));
            _fftWindow = UnsafeBuffer.Create(_fftBins, sizeof(float));
            _fftSpectrum = UnsafeBuffer.Create(_fftBins, sizeof(float));
            _scaledFFTSpectrum = UnsafeBuffer.Create(_fftBins, sizeof(byte));

            _iqPtr = (Complex*) _iqBuffer;
            _fftPtr = (Complex*) _fftBuffer;
            _fftWindowPtr = (float*) _fftWindow;
            _fftSpectrumPtr = (float*) _fftSpectrum;
            _scaledFFTSpectrumPtr = (byte*) _scaledFFTSpectrum;
        }
Example #44
0
 private unsafe void DuplexFiller(float* buffer, int frameCount)
 {
     if (this._dspInBuffer == null || this._dspInBuffer.Length != frameCount)
       {
     this._dspInBuffer = UnsafeBuffer.Create(frameCount, sizeof (Complex));
     this._dspInPtr = (Complex*) (void*) this._dspInBuffer;
       }
       if (this._dspOutBuffer == null || this._dspOutBuffer.Length != this._dspInBuffer.Length * 2)
       {
     this._dspOutBuffer = UnsafeBuffer.Create(this._dspInBuffer.Length * 2, 4);
     this._dspOutPtr = (float*) (void*) this._dspOutBuffer;
       }
       Utils.Memcpy((void*) this._dspInPtr, (void*) buffer, frameCount * sizeof (Complex));
       if (this._hookManager != null)
     this._hookManager.ProcessRawIQ(this._dspInPtr, frameCount);
       this.ProcessIQ();
       this.ScaleBuffer(this._dspOutPtr, this._dspOutBuffer.Length);
       Utils.Memcpy((void*) buffer, (void*) this._dspOutPtr, this._dspOutBuffer.Length * 4);
 }
Example #45
0
 private unsafe void ProcessSamples(byte[] buffer, int actualLength)
 {
     int num = (int) buffer[3] << 8 | (int) buffer[2];
       if (num != (int) this._nextSequence && (int) this._nextSequence != 0)
     ++this._lostPacketsCount;
       this._nextSequence = (ushort) (num + 1);
       if (!this._is16Bit)
       {
     int index = 4;
     while (index < actualLength)
     {
       this._workingSamplePtr->Imag = (float) ((int) buffer[index + 2] << 24 | (int) buffer[index + 1] << 16 | (int) buffer[index] << 8) * 4.656613E-10f;
       this._workingSamplePtr->Real = (float) ((int) buffer[index + 5] << 24 | (int) buffer[index + 4] << 16 | (int) buffer[index + 3] << 8) * 4.656613E-10f;
       ++this._workingSamplePtr;
       ++this._sampleCount;
       index += 6;
     }
     if (this._sampleCount < 480)
       return;
     this._callback((IFrontendController) this, this._sampleBufferPtr, this._sampleCount);
     this._workingSamplePtr = this._sampleBufferPtr;
     this._sampleCount = 0;
       }
       else
       {
     int index = 4;
     while (index < actualLength)
     {
       this._workingSamplePtr->Imag = (float) (short) ((int) buffer[index + 1] << 8 | (int) buffer[index]) * 3.051758E-05f;
       this._workingSamplePtr->Real = (float) (short) ((int) buffer[index + 3] << 8 | (int) buffer[index + 2]) * 3.051758E-05f;
       ++this._workingSamplePtr;
       ++this._sampleCount;
       index += 4;
     }
     if (this._sampleCount < 512)
       return;
     this._callback((IFrontendController) this, this._sampleBufferPtr, this._sampleCount);
     this._workingSamplePtr = this._sampleBufferPtr;
     this._sampleCount = 0;
       }
 }
Example #46
0
 private unsafe void Configure()
 {
     this._index = 0;
       this._sum = 0.0f;
       this._averagingWindowLength = (int) ((double) NoiseBlankerProcessor.AveragingWindow * 1E-06 * this._sampleRate);
       this._norm = 1f / (float) this._averagingWindowLength;
       this._ratio = (float) ((double) (100 - this._threshold) * 0.100000001490116 + 1.0) * this._norm;
       this._delay = UnsafeBuffer.Create((2 * this._averagingWindowLength + 1) * 2, sizeof (Complex));
       this._delayPtr = (Complex*) (void*) this._delay;
       this._blankingWindowLength = (int) Math.Min(Math.Max(this._pulseWidth * 1E-06 * this._sampleRate, 1.0), (double) this._averagingWindowLength);
       this._alpha = 1f / (float) this._blankingWindowLength;
 }
Example #47
0
 private unsafe void RecorderFiller(float* buffer, int frameCount)
 {
     if (this._iqInBuffer == null || this._iqInBuffer.Length != frameCount)
       {
     this._iqInBuffer = UnsafeBuffer.Create(frameCount, sizeof (Complex));
     this._iqInPtr = (Complex*) (void*) this._iqInBuffer;
       }
       Utils.Memcpy((void*) this._iqInPtr, (void*) buffer, frameCount * sizeof (Complex));
       if (this._hookManager != null)
     this._hookManager.ProcessRawIQ(this._iqInPtr, frameCount);
       if (this._iqStream.Length >= this._inputBufferSize * 4)
     return;
       this._iqStream.Write(this._iqInPtr, frameCount);
 }
Example #48
0
 public void Dispose()
 {
     if (_sampleBuffer != null)
     {
         _sampleBuffer.Dispose();
         _sampleBufferPtr = null;
         _workingSamplePtr = null;
     }
 }
Example #49
0
        public void Start(SDRSharp.Radio.SamplesAvailableDelegate callback)
        {
            _callback = callback;
            _hostName = _gui.Host;
            _port = _gui.Port;
            _is16Bit = _gui.Use16Bit;

            _lostPacketsCount = 0;
            _circularBufferHead = 0;
            _circularBufferTail = 0;
            _sampleCount = 0;

            _sampleBuffer = UnsafeBuffer.Create(256 * 2, sizeof(Complex));
            _sampleBufferPtr = (Complex*)_sampleBuffer;
            _workingSamplePtr = _sampleBufferPtr;

            _client = new SdrIpClient();
            _client.Connect(_hostName, _port);
            _client.Samplerate = _sampleRate;
            _client.Frequency = _frequency;
            _client.Use16Bit = _is16Bit;

            _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _udpSocket.ReceiveBufferSize = 65535;
            var remoteIpEndPoint = new IPEndPoint(IPAddress.Any, _port);
            _udpSocket.Bind(remoteIpEndPoint);
            _udpThread = new Thread(UdpReceiverThread);
            _udpThread.Priority = ThreadPriority.Highest;
            _udpThreadRunning = true;
            _udpThread.Start();

            _workerThread = new Thread(WorkerThread);
            _workerThreadRunning = true;
            _workerThread.Start();

            _client.StartStreaming();
            _tuneTimer.Start();

            Utils.SaveSetting("SDRIPHost", _hostName);
            Utils.SaveSetting("SDRIPPort", _port);
            Utils.SaveSetting("SDRIPRateIndex", _gui.SamepleRateIndex);
            Utils.SaveSetting("SDRIPFormatIndex", _gui.SampleFormatIndex);
        }
Example #50
0
        public void Stop()
        {
            _tuneTimer.Stop();

            _client.StopStreaming();
            _client.Disconnect();
            _client = null;
            if (_udpSocket != null)
            {
                _udpSocket.Close();
                _udpSocket = null;
            }
            _udpThreadRunning = false;
            if (_udpThread != null)
            {
                _udpThread.Join();
                _udpThread = null;
            }
            _workerThreadRunning = false;
            if (_workerThread != null)
            {
                _bufferEvt.Set();
                _workerThread.Join();
                _workerThread = null;
            }

            if (_sampleBuffer != null)
            {
                _sampleBuffer.Dispose();
                _sampleBufferPtr = null;
                _workingSamplePtr = null;
            }
        }
Example #51
0
 public unsafe void Start(SamplesAvailableDelegate callback)
 {
     this._callback = callback;
       this._hostName = this._gui.Host;
       this._port = this._gui.Port;
       this._is16Bit = this._gui.Use16Bit;
       this._lostPacketsCount = 0L;
       this._circularBufferHead = 0;
       this._circularBufferTail = 0;
       this._sampleCount = 0;
       this._sampleBuffer = UnsafeBuffer.Create(512, sizeof (Complex));
       this._sampleBufferPtr = (Complex*) (void*) this._sampleBuffer;
       this._workingSamplePtr = this._sampleBufferPtr;
       this._client = new SdrIpClient();
       this._client.Connect(this._hostName, this._port);
       this._client.Samplerate = this._sampleRate;
       this._client.Frequency = this._frequency;
       this._client.Use16Bit = this._is16Bit;
       this._udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
       this._udpSocket.ReceiveBufferSize = (int) ushort.MaxValue;
       this._udpSocket.Bind((EndPoint) new IPEndPoint(IPAddress.Any, this._port));
       this._udpThread = new Thread(new ThreadStart(this.UdpReceiverThread));
       this._udpThread.Priority = ThreadPriority.Highest;
       this._udpThreadRunning = true;
       this._udpThread.Start();
       this._workerThread = new Thread(new ThreadStart(this.WorkerThread));
       this._workerThreadRunning = true;
       this._workerThread.Start();
       this._client.StartStreaming();
       this._tuneTimer.Start();
       Utils.SaveSetting("SDRIPHost", this._hostName);
       Utils.SaveSetting("SDRIPPort", (object) this._port);
       Utils.SaveSetting("SDRIPRateIndex", (object) this._gui.SamepleRateIndex);
       Utils.SaveSetting("SDRIPFormatIndex", (object) this._gui.SampleFormatIndex);
 }
Example #52
0
 private unsafe void DSPProc()
 {
     if (this._dspInBuffer == null || this._dspInBuffer.Length != this._inputBufferSize)
       {
     this._dspInBuffer = UnsafeBuffer.Create(this._inputBufferSize, sizeof (Complex));
     this._dspInPtr = (Complex*) (void*) this._dspInBuffer;
       }
       if (this._dspOutBuffer == null || this._dspOutBuffer.Length != this._outputBufferSize)
       {
     this._dspOutBuffer = UnsafeBuffer.Create(this._outputBufferSize, 4);
     this._dspOutPtr = (float*) (void*) this._dspOutBuffer;
       }
       while (this.IsPlaying)
       {
     int ofs = 0;
     while (this.IsPlaying && ofs < this._dspInBuffer.Length)
     {
       int count = this._dspInBuffer.Length - ofs;
       ofs += this._iqStream.Read(this._dspInPtr, ofs, count);
     }
     this.ProcessIQ();
     this._audioStream.Write(this._dspOutPtr, this._dspOutBuffer.Length);
       }
 }
Example #53
0
 public unsafe void Stop()
 {
     this._tuneTimer.Stop();
       this._client.StopStreaming();
       this._client.Disconnect();
       this._client = (SdrIpClient) null;
       if (this._udpSocket != null)
       {
     this._udpSocket.Close();
     this._udpSocket = (Socket) null;
       }
       this._udpThreadRunning = false;
       if (this._udpThread != null)
       {
     this._udpThread.Join();
     this._udpThread = (Thread) null;
       }
       this._workerThreadRunning = false;
       if (this._workerThread != null)
       {
     this._bufferEvt.Set();
     this._workerThread.Join();
     this._workerThread = (Thread) null;
       }
       if (this._sampleBuffer == null)
     return;
       this._sampleBuffer.Dispose();
       this._sampleBufferPtr = (Complex*) null;
       this._workingSamplePtr = (Complex*) null;
 }
Example #54
0
        public static void StartHW(int freq)
        {
            if (_dllHandle == IntPtr.Zero || _startHW == null)
                return;

            _iqBuffer = null;
            _iqPtr = null;

            int result = _startHW(freq);
            if (result < 0)
                throw new Exception("ExtIO StartHW() returned " + result);
            
            _isHWStarted = true;
            _sampleCount = result;

            /* Allocate the sample buffers */
            /* We must do it here since we do not know the size until the hardware is started! */
            _iqBuffer = UnsafeBuffer.Create(_sampleCount, sizeof(Complex));
            _iqPtr = (Complex*) _iqBuffer;
        }
Example #55
0
 public void Dispose()
 {
     if (_iqBuffer != null)
     {
         _iqBuffer.Dispose();
         _iqBuffer = null;
         _iqBufferPtr = null;
     }
     if (_gui != null)
     {
         _gui.Dispose();                
     }
     GC.SuppressFinalize(this);
 }
Example #56
0
        public void Process(float* baseBand, int length)
        {
            #region Initialize buffers

            if (_rawBuffer == null || _rawBuffer.Length != length)
            {
                _rawBuffer = UnsafeBuffer.Create(length, sizeof(Complex));
                _rawPtr = (Complex*) _rawBuffer;
            }

            if (_magBuffer == null || _magBuffer.Length != length)
            {
                _magBuffer = UnsafeBuffer.Create(length, sizeof(float));
                _magPtr = (float*) _magBuffer;
            }

            if (_dataBuffer == null || _dataBuffer.Length != length)
            {
                _dataBuffer = UnsafeBuffer.Create(length, sizeof(float));
                _dataPtr = (float*) _dataBuffer;
            }

            #endregion

            // Downconvert
            for (var i = 0; i < length; i++)
            {
                _osc->Tick();
                _rawPtr[i] = _osc->Phase * baseBand[i];
            }

            // Decimate
            _decimator.Process(_rawPtr, length);
            length /= _decimationFactor;

            // Filter
            _baseBandFilter.Process(_rawPtr, length);

            // PLL
            for (var i = 0; i < length; i++)
            {
                _dataPtr[i] = _pll->Process(_rawPtr[i]).Imag;
            }

            //if (!_pll->IsLocked)
            //{
            //    _bitDecoder.Reset();
            //    return;
            //}

            // Matched filter
            _matchedFilter.Process(_dataPtr, length);

            // Recover signal energy to sustain the oscillation in the IIR
            for (var i = 0; i < length; i++)
            {
                _magPtr[i] = Math.Abs(_dataPtr[i]);
            }

            // Synchronize to RDS bitrate
            _syncFilter->Process(_magPtr, length);

            // Detect RDS bits
            for (int i = 0; i < length; i++)
            {
                var data = _dataPtr[i];
                var syncVal = _magPtr[i];
                var slope = syncVal - _lastSync;
                _lastSync = syncVal;
                if (slope < 0.0f && _lastSyncSlope * slope < 0.0f)
                {
                    bool bit = _lastData > 0;
                    _bitDecoder.Process(bit ^ _lastBit);
                    _lastBit = bit;
                }
                _lastData = data;
                _lastSyncSlope = slope;
            }
        }
Example #57
0
 private unsafe void InitFFTBuffers()
 {
     this._inputBuffer = UnsafeBuffer.Create(this._fftBins, 4);
       this._fftBuffer = UnsafeBuffer.Create(this._fftBins, sizeof (Complex));
       this._fftWindow = UnsafeBuffer.Create(this._fftBins, 4);
       this._fftSpectrum = UnsafeBuffer.Create(this._fftBins, 4);
       this._scaledFFTSpectrum = UnsafeBuffer.Create(this._fftBins, 1);
       this._inputPtr = (float*) (void*) this._inputBuffer;
       this._fftPtr = (Complex*) (void*) this._fftBuffer;
       this._fftWindowPtr = (float*) (void*) this._fftWindow;
       this._fftSpectrumPtr = (float*) (void*) this._fftSpectrum;
       this._scaledFFTSpectrumPtr = (byte*) (void*) this._scaledFFTSpectrum;
 }
Example #58
0
 public unsafe void Process(float* baseBand, int length)
 {
     if (this._rawBuffer == null || this._rawBuffer.Length != length)
       {
     this._rawBuffer = UnsafeBuffer.Create(length, sizeof (Complex));
     this._rawPtr = (Complex*) (void*) this._rawBuffer;
       }
       if (this._magBuffer == null || this._magBuffer.Length != length)
       {
     this._magBuffer = UnsafeBuffer.Create(length, 4);
     this._magPtr = (float*) (void*) this._magBuffer;
       }
       if (this._dataBuffer == null || this._dataBuffer.Length != length)
       {
     this._dataBuffer = UnsafeBuffer.Create(length, 4);
     this._dataPtr = (float*) (void*) this._dataBuffer;
       }
       for (int index = 0; index < length; ++index)
       {
     this._osc->Tick();
     this._rawPtr[index] = this._osc->Phase * baseBand[index];
       }
       this._decimator.Process(this._rawPtr, length);
       length /= this._decimationFactor;
       this._baseBandFilter.Process(this._rawPtr, length);
       for (int index = 0; index < length; ++index)
     this._dataPtr[index] = this._pll->Process(this._rawPtr[index]).Imag;
       this._matchedFilter.Process(this._dataPtr, length);
       for (int index = 0; index < length; ++index)
     this._magPtr[index] = Math.Abs(this._dataPtr[index]);
       this._syncFilter->Process(this._magPtr, length);
       for (int index = 0; index < length; ++index)
       {
     float num1 = this._dataPtr[index];
     float num2 = this._magPtr[index];
     float num3 = num2 - this._lastSync;
     this._lastSync = num2;
     if ((double) num3 < 0.0 && (double) this._lastSyncSlope * (double) num3 < 0.0)
     {
       bool flag = (double) this._lastData > 0.0;
       this._bitDecoder.Process(flag ^ this._lastBit);
       this._lastBit = flag;
     }
     this._lastData = num1;
     this._lastSyncSlope = num3;
       }
 }
Example #59
0
 private unsafe void ReceiveSamples_sync()
 {
     int status = 0;
     while (_isStreaming)
     {
         uint cur_len, new_len;
         lock (syncLock)
         {
             cur_len = new_len = _readLength;
         }
         if (_iqBuffer == null || _iqBuffer.Length != cur_len)
         {
             _iqBuffer = UnsafeBuffer.Create((int)cur_len, sizeof(Complex));
             _iqPtr = (Complex*)_iqBuffer;
         }
         if (_samplesBuffer == null || _samplesBuffer.Length != (2 * cur_len))
         {
             _samplesBuffer = UnsafeBuffer.Create((int)(2 * cur_len), sizeof(Int16));
             _samplesPtr = (Int16*)_samplesBuffer;
         }
         if ((status = NativeMethods.bladerf_sync_config(_dev, bladerf_module.BLADERF_MODULE_RX, bladerf_format.BLADERF_FORMAT_SC16_Q11, NumBuffers, cur_len, NumBuffers / 2, SampleTimeoutMs)) != 0)
             _isStreaming = false;
         while (status == 0 && cur_len == new_len)
         {
             try
             {
                 status = NativeMethods.bladerf_sync_rx(_dev, _samplesPtr, cur_len, IntPtr.Zero, SampleTimeoutMs);
                 if (status != 0)
                     throw new ApplicationException(String.Format("bladerf_rx() error. {0}", NativeMethods.bladerf_strerror(status)));
                 var ptrIq = _iqPtr;
                 var ptrSample = _samplesPtr;
                 for (int i = 0; i < cur_len; i++)
                 {
                     ptrIq->Imag = _lutPtr[*ptrSample & 0x0fff];
                     ptrSample++;
                     ptrIq->Real = _lutPtr[*ptrSample & 0x0fff];
                     ptrSample++;
                     ptrIq++;
                 }
                 ComplexSamplesAvailable(_iqPtr, _iqBuffer.Length);
             }
             catch
             {
                 break;
             }
             lock (syncLock)
             {
                 new_len = _readLength;
             }
         }
     }
 }
Example #60
0
        private void ProcessSamples(byte[] buffer, int actualLength)
        {
            const float scale24 = 1.0f / 2147483647.0f;
            const float scale16 = 1.0f / 32768.0f;

            var seq = (ushort)buffer[3] << 8 | buffer[2];
            if (seq != _nextSequence && _nextSequence != 0)
            {
                _lostPacketsCount++;
            }
            _nextSequence = (ushort)(seq + 1);

            if (!_is16Bit)
            {
                for (var i = 4; i < actualLength; i += 6)
                {
                    _workingSamplePtr->Imag = (float)((int)(buffer[i + 2] << 24 | buffer[i + 1] << 16 | buffer[i] << 8)) * scale24;
                    _workingSamplePtr->Real = (float)((int)(buffer[i + 5] << 24 | buffer[i + 4] << 16 | buffer[i + 3] << 8)) * scale24;
                    _workingSamplePtr++;
                    _sampleCount++;
                }

                if (_sampleCount >= 240 * 2)
                {
                    _callback(this, _sampleBufferPtr, _sampleCount);
                    _workingSamplePtr = (Complex*)_sampleBufferPtr;
                    _sampleCount = 0;
                }
            }
            else
            {
                for (var i = 4; i < actualLength; i += 4)
                {
                    _workingSamplePtr->Imag = (float)((short)((buffer[i + 1] << 8) | buffer[i])) * scale16;
                    _workingSamplePtr->Real = (float)((short)((buffer[i + 3] << 8) | buffer[i + 2])) * scale16;
                    _workingSamplePtr++;
                    _sampleCount++;
                }

                if (_sampleCount >= 256 * 2)
                {
                    _callback(this, _sampleBufferPtr, _sampleCount);
                    _workingSamplePtr = (Complex*)_sampleBufferPtr;
                    _sampleCount = 0;
                }
            }
        }