GazeDecimatorFixedLength.cs 2.42 KB
Newer Older
1 2 3 4 5 6 7 8
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TrackerBridge.DSP
{
9
    public class GazeDecimatorFixedLength : IGazeFilter
10 11 12 13 14 15 16 17 18 19
    {
        private GazeData[] buffer;
        private Int32 currentValueIndex;
        private Single inputFrequency;
        private GazeData? output;
        private Single outputFrequency;

        private Object outputLock = new Object();
        private Object inputLock = new Object();

20 21
        public event EventHandler<GazeData> OutputAvailable;

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
        public Single InputFrequency {
            get { return inputFrequency; }
            set {
                inputFrequency = value;
                Reset();
            }
        }
        public GazeData? Output {
            get {
                lock (outputLock)
                {
                    GazeData? temp = null;
                    if (output.HasValue)
                    {
                        temp = output.Value;
                        output = null;

                    }
                    return temp;
                }
            }
        }
44

45 46 47 48 49 50 51 52
        public Single OutputFrequency {
            get { return outputFrequency; }
            set {
                outputFrequency = value;
                Reset();
            }
        }

53
        public GazeDecimatorFixedLength(Single outputFrequency, Single inputFrequency)
54 55 56 57 58 59 60 61 62 63 64
        {
            this.outputFrequency = outputFrequency;
            this.inputFrequency = inputFrequency;
            Reset();
        }

        public void Input(GazeData input)
        {
            lock (inputLock)
            {
                currentValueIndex = (currentValueIndex + 1) % buffer.Length;
65 66
            }
            buffer[currentValueIndex] = input;
67

68 69 70 71
            if (currentValueIndex == buffer.Length-1)
            {
                GazeData sum = buffer[0];
                for (Int32 index = 1; index < buffer.Length; index++)
72
                {
73 74 75 76 77 78 79
                    sum += buffer[index];
                }
                sum /= buffer.Length;

                lock (outputLock)
                {
                    output = sum;
80 81
                }
            }
82

83 84 85 86 87 88
        }

        public void Reset()
        {
            Int32 bufferLength = Convert.ToInt32(InputFrequency / OutputFrequency);
            buffer = new GazeData[bufferLength];
89
            currentValueIndex = -1;
90 91 92 93
            output = null;
        }
    }
}