Ejemplo n.º 1
0
 public void Read(NetworkStream stream)
 {
     WindowId = (byte)stream.ReadByte();
     WindowType = (WindowTypes)stream.ReadByte();
     Title = StreamHelper.ReadString(stream);
     Slots = (byte)stream.ReadByte();
 }
        //===================================================================
        // イベントハンドラ
        //===================================================================
        //-------------------------------------------------------------------
        // *Changed/Checked/Unchecked以外
        //-------------------------------------------------------------------
        /// プロファイルを更新
        private void ModifyProfile(WindowTypes nextWindowType, UIntPtr nextTargetWindow)
        {
            App.Profile.Open();

            // Window
            switch (nextWindowType) {
              case WindowTypes.Normal: {
            App.Profile.Current.SetWindow(nextTargetWindow);
            break;
              }
              case WindowTypes.DXGI: {
            App.Profile.Current.SetWindowToDXGI();
            break;
              }
              case WindowTypes.Desktop: {
            App.Profile.Current.SetWindowToDesktop();
            break;
              }
              default: Debug.Fail("switch"); throw new System.ArgumentException();
            }
            App.Profile.Current.Fit = true;
            App.Profile.Current.ClearBackupParameters();
            App.Profile.Close();

            //-----------------------------------------------------------------
            // Notify self
            this.OnCurrentLayoutElementChanged();
            // Notify other controls
            Commands.AreaChanged.Execute(null, this);
            //-----------------------------------------------------------------
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Main constructor
        /// </summary>
        /// <param name="samplingRate"></param>
        /// <param name="frameDuration">In seconds</param>
        /// <param name="hopDuration">In seconds</param>
        /// <param name="modulationFftSize">In samples</param>
        /// <param name="modulationHopSize">In samples</param>
        /// <param name="fftSize">In samples</param>
        /// <param name="featuregram"></param>
        /// <param name="filterbank"></param>
        /// <param name="preEmphasis"></param>
        /// <param name="window"></param>
        public AmsExtractor(int samplingRate,
                            double frameDuration              = 0.0256 /*sec*/,
                            double hopDuration                = 0.010 /*sec*/,
                            int modulationFftSize             = 64,
                            int modulationHopSize             = 4,
                            int fftSize                       = 0,
                            IEnumerable <float[]> featuregram = null,
                            float[][] filterbank              = null,
                            double preEmphasis                = 0.0,
                            WindowTypes window                = WindowTypes.Rectangular)

            : base(samplingRate, frameDuration, hopDuration)
        {
            _modulationFftSize = modulationFftSize;
            _modulationHopSize = modulationHopSize;
            _modulationFft     = new Fft(_modulationFftSize);

            _featuregram = featuregram?.ToArray();

            if (featuregram != null)
            {
                _featureCount = _featuregram[0].Length * (_modulationFftSize / 2 + 1);
            }
            else
            {
                if (_filterbank == null)
                {
                    _fftSize = fftSize > FrameSize ? fftSize : MathUtils.NextPowerOfTwo(FrameSize);

                    _filterbank = FilterBanks.Triangular(_fftSize, samplingRate,
                                                         FilterBanks.MelBands(12, _fftSize, samplingRate, 100, 3200));
                }
                else
                {
                    _filterbank = filterbank;
                    _fftSize    = 2 * (filterbank[0].Length - 1);
                }

                _fft = new Fft(_fftSize);

                _featureCount = _filterbank.Length * (_modulationFftSize / 2 + 1);

                _window = window;
                if (_window != WindowTypes.Rectangular)
                {
                    _windowSamples = Window.OfType(_window, FrameSize);
                }

                _spectrum         = new float[_fftSize / 2 + 1];
                _filteredSpectrum = new float[_filterbank.Length];
                _block            = new float[_fftSize];
                _zeroblock        = new float[_fftSize];
            }

            _preEmphasis = (float)preEmphasis;

            _modBlock     = new float[_modulationFftSize];
            _zeroModblock = new float[_modulationFftSize];
            _modSpectrum  = new float[_modulationFftSize / 2 + 1];

            // feature descriptions

            int length;

            if (_featuregram != null)
            {
                length = _featuregram[0].Length;
            }
            else
            {
                length = _filterbank.Length;
            }

            _featureDescriptions = new List <string>();

            var modulationSamplingRate = (float)samplingRate / HopSize;
            var resolution             = modulationSamplingRate / _modulationFftSize;

            for (var fi = 0; fi < length; fi++)
            {
                for (var fj = 0; fj <= _modulationFftSize / 2; fj++)
                {
                    _featureDescriptions.Add(string.Format("band_{0}_mf_{1:F2}_Hz", fi + 1, fj * resolution));
                }
            }
        }
Ejemplo n.º 4
0
 //-------------------------------------------------------------------
 /// レイアウトタイプに合わせて適切なBrush/Penを設定する
 private void GetWindowTypesBrushes(
     WindowTypes currentWindowType, WindowTypes nextWindowType,
     out Brush border, out Brush background)
 {
     switch (nextWindowType) {
       case WindowTypes.Normal: {
     // 更に現在のTypeによって色を分ける
     switch (currentWindowType) {
       case WindowTypes.DXGI: {
     border = BrushesAndPens.CurrentDXGIBrush;
     background = BrushesAndPens.TransparentDXGIBrush;
     break;
       }
       case WindowTypes.Desktop: {
     border = BrushesAndPens.CurrentDesktopBrush;
     background = BrushesAndPens.TransparentDesktopBrush;
     break;
       }
       case WindowTypes.Normal: {
     border = BrushesAndPens.CurrentNormalBrush;
     background = BrushesAndPens.TransparentNormalBrush;
     break;
       }
       default: Debug.Fail("switch"); throw new System.ArgumentException();
     }
     break;
       }
       case WindowTypes.DXGI: {
     border = BrushesAndPens.CurrentDXGIBrush;
     background = BrushesAndPens.TransparentDXGIBrush;
     break;
       }
       case WindowTypes.Desktop: {
     border = BrushesAndPens.CurrentDesktopBrush;
     background = BrushesAndPens.TransparentDesktopBrush;
     break;
       }
       default: Debug.Fail("switch"); throw new System.ArgumentException();
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="samplingRate"></param>
        /// <param name="featureList"></param>
        /// <param name="frameDuration"></param>
        /// <param name="hopDuration"></param>
        /// <param name="fftSize"></param>
        /// <param name="parameters"></param>
        public SpectralFeaturesExtractor(int samplingRate,
                                         string featureList,
                                         double frameDuration = 0.0256 /*sec*/,
                                         double hopDuration   = 0.010 /*sec*/,
                                         int fftSize          = 0,
                                         float[] frequencies  = null,
                                         WindowTypes window   = WindowTypes.Hamming,
                                         IReadOnlyDictionary <string, object> parameters = null)

            : base(samplingRate, frameDuration, hopDuration)
        {
            if (featureList == "all" || featureList == "full")
            {
                featureList = FeatureSet;
            }

            var features = featureList.Split(',', '+', '-', ';', ':')
                           .Select(f => f.Trim().ToLower());

            _extractors = features.Select <string, Func <float[], float[], float> >(feature =>
            {
                switch (feature)
                {
                case "sc":
                case "centroid":
                    return(Spectral.Centroid);

                case "ss":
                case "spread":
                    return(Spectral.Spread);

                case "sfm":
                case "flatness":
                    if (parameters?.ContainsKey("minLevel") ?? false)
                    {
                        var minLevel = (float)parameters["minLevel"];
                        return((spectrum, freqs) => Spectral.Flatness(spectrum, minLevel));
                    }
                    else
                    {
                        return((spectrum, freqs) => Spectral.Flatness(spectrum));
                    }

                case "sn":
                case "noiseness":
                    if (parameters?.ContainsKey("noiseFrequency") ?? false)
                    {
                        var noiseFrequency = (float)parameters["noiseFrequency"];
                        return((spectrum, freqs) => Spectral.Noiseness(spectrum, freqs, noiseFrequency));
                    }
                    else
                    {
                        return((spectrum, freqs) => Spectral.Noiseness(spectrum, freqs));
                    }

                case "rolloff":
                    if (parameters?.ContainsKey("rolloffPercent") ?? false)
                    {
                        var rolloffPercent = (float)parameters["rolloffPercent"];
                        return((spectrum, freqs) => Spectral.Rolloff(spectrum, freqs, rolloffPercent));
                    }
                    else
                    {
                        return((spectrum, freqs) => Spectral.Rolloff(spectrum, freqs));
                    }

                case "crest":
                    return((spectrum, freqs) => Spectral.Crest(spectrum));

                case "entropy":
                case "ent":
                    return((spectrum, freqs) => Spectral.Entropy(spectrum));

                case "sd":
                case "decrease":
                    return((spectrum, freqs) => Spectral.Decrease(spectrum));

                case "c1":
                case "c2":
                case "c3":
                case "c4":
                case "c5":
                case "c6":
                    return((spectrum, freqs) => Spectral.Contrast(spectrum, freqs, int.Parse(feature.Substring(1))));

                default:
                    return((spectrum, freqs) => 0);
                }
            }).ToList();

            FeatureDescriptions = features.ToList();

            _fftSize = fftSize > FrameSize ? fftSize : MathUtils.NextPowerOfTwo(FrameSize);
            _fft     = new Fft(_fftSize);

            _window = window;
            if (_window != WindowTypes.Rectangular)
            {
                _windowSamples = Window.OfType(_window, FrameSize);
            }

            var resolution = (float)samplingRate / _fftSize;

            if (frequencies == null)
            {
                _frequencies = Enumerable.Range(0, _fftSize / 2 + 1)
                               .Select(f => f * resolution)
                               .ToArray();
            }
            else if (frequencies.Length == _fftSize / 2 + 1)
            {
                _frequencies = frequencies;
            }
            else
            {
                _frequencies = new float[frequencies.Length + 1];
                frequencies.FastCopyTo(_frequencies, frequencies.Length, 0, 1);
                _mappedSpectrum     = new float[_frequencies.Length];
                _frequencyPositions = new int[_frequencies.Length];

                for (var i = 1; i < _frequencies.Length; i++)
                {
                    _frequencyPositions[i] = (int)(_frequencies[i] / resolution) + 1;
                }
            }

            _parameters = parameters;

            // reserve memory for reusable blocks

            _spectrum  = new float[_fftSize / 2 + 1]; // buffer for magnitude spectrum
            _block     = new float[_fftSize];         // buffer for currently processed block
            _zeroblock = new float[_fftSize];         // just a buffer of zeros for quick memset
        }
 /// WindowタイプをDesktopにする
 public void SetWindowToDesktop()
 {
     this.additionalData.WindowType = WindowTypes.Desktop;
     this.rawData.Window = User32.GetDesktopWindow();
     this.additionalData.WindowCaption = "(Desktop)";
 }
    public override bool ButtonClicked(string name, SegmentEntity targetEntity)
    {
        if (name == "nextnetwork") // Increment network count
        {
            this.SelectedNetwork++;
            if (this.SelectedNetwork >= fcm.Networks.Count)
            {
                this.SelectedNetwork = 0;
            }
            NetworkSync.NetworkStatus = null;
            this.manager.RedrawWindow();
            return(true);
        }
        else if (name == "prevnetwork") // Decrement network count
        {
            this.SelectedNetwork--;
            if (this.SelectedNetwork < 0)
            {
                this.SelectedNetwork = fcm.Networks.Count - 1;
            }
            NetworkSync.NetworkStatus = null;
            this.manager.RedrawWindow();
            return(true);
        }
        else if (name == "nextstorage") // Increment storage count
        {
            this.SelectedStorage++;
            if (this.SelectedStorage >= fcm.StationInventories.Count)
            {
                this.SelectedStorage = 0;
            }
            this.manager.RedrawWindow();
            return(true);
        }
        else if (name == "prevstorage") // Decrement storage count
        {
            this.SelectedStorage--;
            if (this.SelectedStorage < 0)
            {
                this.SelectedStorage = fcm.StationInventories.Count - 1;
            }
            this.manager.RedrawWindow();
            return(true);
        }
        else if (name == "allnetworks")
        {
            if (this.CurrentWindow == WindowTypes.GlobalInventory)
            {
                this.CurrentWindow = WindowTypes.NetworkStatus;
            }
            else
            {
                this.CurrentWindow = WindowTypes.GlobalInventory;
            }
            this.manager.RedrawWindow();
            return(true);
        }
        else if (name == "tracknetworks")
        {
            if (this.CurrentWindow == WindowTypes.TrackNetworks)
            {
                this.CurrentWindow = WindowTypes.NetworkStatus;
            }
            else
            {
                this.CurrentWindow = WindowTypes.TrackNetworks;
            }
            this.manager.RedrawWindow();
            return(true);
        }
        else if (name == "selnetwork")
        {
            if (this.CurrentWindow == WindowTypes.NetworkSelection)
            {
                this.CurrentWindow = WindowTypes.NetworkStatus;
            }
            else
            {
                this.CurrentWindow = WindowTypes.NetworkSelection;
            }
            this.manager.RedrawWindow();
            return(true);
        }
        else if (name == "viewinventory")
        {
            if (this.CurrentWindow == WindowTypes.StorageInventory)
            {
                this.CurrentWindow = WindowTypes.NetworkStatus;
            }
            else
            {
                this.CurrentWindow = WindowTypes.StorageInventory;
            }
            this.manager.RedrawWindow();
            return(true);
        }
        else if (name.Contains("networknum"))
        {
            int slotNum = -1;
            int.TryParse(name.Replace("networknum", ""), out slotNum); //Get slot name as number

            if (slotNum > -1)                                          // valid slot
            {
                this.SelectedNetwork      = slotNum;
                NetworkSync.NetworkStatus = null;
                this.CurrentWindow        = WindowTypes.NetworkStatus;
                this.manager.RedrawWindow();
                return(true);
            }
        }
        else if (name.Contains("trackicon"))
        {
            int slotNum = -1;
            int.TryParse(name.Replace("trackicon", ""), out slotNum); //Get slot name as number

            if (slotNum > -1)                                         // valid slot
            {
                if (this.TrackNetworkDisplay == slotNum)
                {
                    this.TrackNetworkDisplay = -1;
                }
                else
                {
                    this.TrackNetworkDisplay = slotNum;
                }
                this.StationDisplay       = -1;
                this.CartDisplay          = -1;
                NetworkSync.TrackNetworks = null;
                this.manager.RedrawWindow();
                return(true);
            }
        }
        else if (name.Contains("stationicon"))
        {
            int slotNum = -1;
            int.TryParse(name.Replace("stationicon", ""), out slotNum); //Get slot name as number

            if (slotNum > -1)                                           // valid slot
            {
                if (this.StationDisplay == slotNum)
                {
                    this.StationDisplay = -1;
                }
                else
                {
                    this.StationDisplay = slotNum;
                }
                this.CartDisplay = -1;
                this.manager.ClearWindow();
                NetworkSync.TrackNetworks = null;
                this.manager.RedrawWindow();
                return(true);
            }
        }
        else if (name.Contains("carticon"))
        {
            int slotNum = -1;
            int.TryParse(name.Replace("carticon", ""), out slotNum); //Get slot name as number

            if (slotNum > -1)                                        // valid slot
            {
                if (this.CartDisplay == slotNum)
                {
                    this.CartDisplay = -1;
                }
                else
                {
                    this.CartDisplay = slotNum;
                }
                NetworkSync.TrackNetworks = null;
                this.manager.RedrawWindow();
                return(true);
            }
        }
        else if (name == "addcart")
        {
            int amount = 1;
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                amount = 10;
            }
            FreightCartWindow.SetCartAssignment(this.CurrentStation, this.CurrentStation.AssignedCarts + amount);
            this.manager.UpdateLabel("stationcarts" + this.StationDisplay.ToString(), "Carts: " + this.CurrentStation.AvailableCarts.ToString() + " / " + this.CurrentStation.AssignedCarts.ToString(), this.CurrentStation.AvailableCarts > this.CurrentStation.AssignedCarts ? Color.green : this.CurrentStation.AvailableCarts == this.CurrentStation.AssignedCarts ? Color.white : Color.red);
            return(true);
        }
        else if (name == "removecart")
        {
            int amount = 1;
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                amount = 10;
            }
            FreightCartWindow.SetCartAssignment(this.CurrentStation, this.CurrentStation.AssignedCarts - amount < 0 ? 0 : this.CurrentStation.AssignedCarts - amount);
            this.manager.UpdateLabel("stationcarts" + this.StationDisplay.ToString(), "Carts: " + this.CurrentStation.AvailableCarts.ToString() + " / " + this.CurrentStation.AssignedCarts.ToString(), this.CurrentStation.AvailableCarts > this.CurrentStation.AssignedCarts ? Color.green : this.CurrentStation.AvailableCarts == this.CurrentStation.AssignedCarts ? Color.white : Color.red);
            return(true);
        }
        else if (name == "ordername")
        {
            this.OrderByName = true;
            this.manager.RedrawWindow();
        }
        else if (name == "ordercount")
        {
            this.OrderByName = false;
            this.manager.RedrawWindow();
        }
        else if (name == "togglelayout")
        {
            this.CompactLayout = !this.CompactLayout;
            this.manager.RedrawWindow();
        }

        return(false);
    }
Ejemplo n.º 8
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="samplingRate"></param>
        /// <param name="featureCount"></param>
        /// <param name="frameDuration"></param>
        /// <param name="hopDuration"></param>
        /// <param name="filterbankSize"></param>
        /// <param name="lowFreq"></param>
        /// <param name="highFreq"></param>
        /// <param name="fftSize"></param>
        /// <param name="filterbank"></param>
        /// <param name="lifterSize"></param>
        /// <param name="preEmphasis"></param>
        /// <param name="includeEnergy"></param>
        /// <param name="dctType">"1", "1N", "2", "2N", "3", "3N", "4", "4N"</param>
        /// <param name="nonLinearity"></param>
        /// <param name="spectrumType"></param>
        /// <param name="window"></param>
        /// <param name="logFloor"></param>
        public MfccExtractor(int samplingRate,
                             int featureCount,
                             double frameDuration          = 0.0256 /*sec*/,
                             double hopDuration            = 0.010 /*sec*/,
                             int filterbankSize            = 24,
                             double lowFreq                = 0,
                             double highFreq               = 0,
                             int fftSize                   = 0,
                             float[][] filterbank          = null,
                             int lifterSize                = 0,
                             double preEmphasis            = 0,
                             bool includeEnergy            = false,
                             string dctType                = "2N",
                             NonLinearityType nonLinearity = NonLinearityType.Log10,
                             SpectrumType spectrumType     = SpectrumType.Power,
                             WindowTypes window            = WindowTypes.Hamming,
                             float logFloor                = float.Epsilon)

            : base(samplingRate, frameDuration, hopDuration, preEmphasis)
        {
            FeatureCount = featureCount;

            _lowFreq  = lowFreq;
            _highFreq = highFreq;

            if (filterbank == null)
            {
                _blockSize = fftSize > FrameSize ? fftSize : MathUtils.NextPowerOfTwo(FrameSize);

                var melBands = FilterBanks.MelBands(filterbankSize, _blockSize, SamplingRate, _lowFreq, _highFreq);
                FilterBank = FilterBanks.Triangular(_blockSize, SamplingRate, melBands, mapper: Scale.HerzToMel);   // HTK/Kaldi-style
            }
            else
            {
                FilterBank     = filterbank;
                filterbankSize = filterbank.Length;
                _blockSize     = 2 * (filterbank[0].Length - 1);

                Guard.AgainstExceedance(FrameSize, _blockSize, "frame size", "FFT size");
            }

            _fft = new RealFft(_blockSize);

            _window        = window;
            _windowSamples = Window.OfType(_window, FrameSize);

            _lifterSize   = lifterSize;
            _lifterCoeffs = _lifterSize > 0 ? Window.Liftering(FeatureCount, _lifterSize) : null;

            _includeEnergy = includeEnergy;

            // setup DCT: ============================================================================

            _dctType = dctType;
            switch (dctType[0])
            {
            case '1':
                _dct = new Dct1(filterbankSize);
                break;

            case '2':
                _dct = new Dct2(filterbankSize);
                break;

            case '3':
                _dct = new Dct3(filterbankSize);
                break;

            case '4':
                _dct = new Dct4(filterbankSize);
                break;

            default:
                throw new ArgumentException("Only DCT-1, 2, 3 and 4 are supported!");
            }

            if (dctType.Length > 1 && char.ToUpper(dctType[1]) == 'N')
            {
                _applyDct = mfccs => _dct.DirectNorm(_melSpectrum, mfccs);
            }
            else
            {
                _applyDct = mfccs => _dct.Direct(_melSpectrum, mfccs);
            }

            // setup spectrum post-processing: =======================================================

            _logFloor         = logFloor;
            _nonLinearityType = nonLinearity;
            switch (nonLinearity)
            {
            case NonLinearityType.Log10:
                _postProcessSpectrum = () => FilterBanks.ApplyAndLog10(FilterBank, _spectrum, _melSpectrum, _logFloor);
                break;

            case NonLinearityType.LogE:
                _postProcessSpectrum = () => FilterBanks.ApplyAndLog(FilterBank, _spectrum, _melSpectrum, _logFloor);
                break;

            case NonLinearityType.ToDecibel:
                _postProcessSpectrum = () => FilterBanks.ApplyAndToDecibel(FilterBank, _spectrum, _melSpectrum, _logFloor);
                break;

            case NonLinearityType.CubicRoot:
                _postProcessSpectrum = () => FilterBanks.ApplyAndPow(FilterBank, _spectrum, _melSpectrum, 0.33);
                break;

            default:
                _postProcessSpectrum = () => FilterBanks.Apply(FilterBank, _spectrum, _melSpectrum);
                break;
            }

            _spectrumType = spectrumType;
            switch (_spectrumType)
            {
            case SpectrumType.Magnitude:
                _getSpectrum = block => _fft.MagnitudeSpectrum(block, _spectrum, false);
                break;

            case SpectrumType.Power:
                _getSpectrum = block => _fft.PowerSpectrum(block, _spectrum, false);
                break;

            case SpectrumType.MagnitudeNormalized:
                _getSpectrum = block => _fft.MagnitudeSpectrum(block, _spectrum, true);
                break;

            case SpectrumType.PowerNormalized:
                _getSpectrum = block => _fft.PowerSpectrum(block, _spectrum, true);
                break;
            }

            // reserve memory for reusable blocks

            _spectrum    = new float[_blockSize / 2 + 1];
            _melSpectrum = new float[filterbankSize];
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Main constructor
        /// </summary>
        /// <param name="samplingRate"></param>
        /// <param name="featureCount"></param>
        /// <param name="frameDuration">Length of analysis window (in seconds)</param>
        /// <param name="hopDuration">Length of overlap (in seconds)</param>
        /// <param name="power"></param>
        /// <param name="lowFreq"></param>
        /// <param name="highFreq"></param>
        /// <param name="filterbankSize"></param>
        /// <param name="filterbank"></param>
        /// <param name="fftSize">Size of FFT (in samples)</param>
        /// <param name="preEmphasis"></param>
        /// <param name="window"></param>
        public SpnccExtractor(int samplingRate,
                              int featureCount,
                              double frameDuration = 0.0256 /*sec*/,
                              double hopDuration   = 0.010 /*sec*/,
                              int power            = 15,
                              double lowFreq       = 100,
                              double highFreq      = 6800,
                              int filterbankSize   = 40,
                              float[][] filterbank = null,
                              int fftSize          = 0,
                              double preEmphasis   = 0.0,
                              WindowTypes window   = WindowTypes.Hamming)

            : base(samplingRate, frameDuration, hopDuration)
        {
            FeatureCount = featureCount;

            _power = power;

            if (filterbank == null)
            {
                _fftSize        = fftSize > FrameSize ? fftSize : MathUtils.NextPowerOfTwo(FrameSize);
                _filterbankSize = filterbankSize;

                _lowFreq  = lowFreq;
                _highFreq = highFreq;

                FilterBank = FilterBanks.Erb(_filterbankSize, _fftSize, samplingRate, _lowFreq, _highFreq);

                // use power spectrum:

                foreach (var filter in FilterBank)
                {
                    for (var j = 0; j < filter.Length; j++)
                    {
                        var ps = filter[j] * filter[j];
                        filter[j] = ps;
                    }
                }
            }
            else
            {
                FilterBank      = filterbank;
                _filterbankSize = filterbank.Length;
                _fftSize        = 2 * (filterbank[0].Length - 1);
            }

            _fft = new Fft(_fftSize);
            _dct = new Dct2(_filterbankSize, FeatureCount);

            _preEmphasis = (float)preEmphasis;

            _window = window;
            if (_window != WindowTypes.Rectangular)
            {
                _windowSamples = Window.OfType(_window, FrameSize);
            }

            _block            = new float[_fftSize];
            _spectrum         = new float[_fftSize / 2 + 1];
            _filteredSpectrum = new float[_filterbankSize];
            _zeroblock        = new float[_fftSize];
        }
Ejemplo n.º 10
0
 public Window(int id, int parent, Rect newSize, WindowTypes type = WindowTypes.Text, NodeType nodeType = NodeType.Default)
 {
     ID = id; Parent = parent; Size = newSize; Text = ""; Type = type; NodeType = nodeType; Trigger = false; TriggerText = "";
 }
Ejemplo n.º 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="signal"></param>
        /// <param name="window"></param>
        public static void ApplyWindow(this DiscreteSignal signal, WindowTypes window, params object[] parameters)
        {
            var windowSamples = Window.OfType(window, signal.Length, parameters);

            signal.Samples.ApplyWindow(windowSamples);
        }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="samples"></param>
        /// <param name="window"></param>
        public static void ApplyWindow(this double[] samples, WindowTypes window, params object[] parameters)
        {
            var windowSamples = Window.OfType(window, samples.Length, parameters).ToDoubles();

            samples.ApplyWindow(windowSamples);
        }
Ejemplo n.º 13
0
 /// Windowタイプ別にScreen座標系での領域を返す
 public static ScreenRect GetWindowScreenRect(WindowTypes windowType, UIntPtr window)
 {
     var screenRect = Utilities.GetWindowRect(windowType, window);
     var screenPoint =
     Utilities.ClientToScreen(windowType, window, screenRect.X, screenRect.Y);
     return new ScreenRect(screenPoint.X, screenPoint.Y,
                   screenRect.Width, screenRect.Height);
 }
Ejemplo n.º 14
0
 //===================================================================
 // WindowType/Window別の機能
 //===================================================================
 /// WindowのClient座標系での領域を返す
 /// @warning windowType == Desktop時のみ、左上端がマイナス座標になる可能性がある
 /// @param windowType Windowタイプ
 /// @param window Windowハンドル
 /// @return WindowのClient座標系での領域(Desktopのみ左上端が(0,0)とは限らない)
 public static ClientRect GetWindowRect(WindowTypes windowType, UIntPtr window)
 {
     switch (windowType) {
       case WindowTypes.Normal: {
     Debug.Assert(Common.Utilities.IsWindowValid(window),
              "Invalid Window", "GetWindowRect");
     User32.RECT windowRect;
     User32.GetClientRect(window, out windowRect);
     return new ClientRect(0, 0, windowRect.Right, windowRect.Bottom);
       }
       case WindowTypes.DXGI: {
     return new ClientRect(0, 0,
     User32.GetSystemMetrics(User32.SM_CXVIRTUALSCREEN),
     User32.GetSystemMetrics(User32.SM_CYVIRTUALSCREEN));
       }
       case WindowTypes.Desktop: {
     return new ClientRect(
     User32.GetSystemMetrics(User32.SM_XVIRTUALSCREEN),
     User32.GetSystemMetrics(User32.SM_YVIRTUALSCREEN),
     User32.GetSystemMetrics(User32.SM_CXVIRTUALSCREEN),
     User32.GetSystemMetrics(User32.SM_CYVIRTUALSCREEN));
       }
       default: Debug.Fail("switch"); throw new System.ArgumentException();
     }
 }
Ejemplo n.º 15
0
 /// Client座標系の座標をWindowタイプ別にScreen座標系に変換する
 public static ScreenPoint ClientToScreen(WindowTypes windowType, UIntPtr window, int clientX, int clientY)
 {
     switch (windowType) {
       case WindowTypes.Normal: {
     Debug.Assert(Common.Utilities.IsWindowValid(window),
              "Invalid Window", "ClientToScreen");
     User32.POINT windowPoint = new User32.POINT { X = clientX, Y = clientY };
     User32.ClientToScreen(window, ref windowPoint);
     return new ScreenPoint(windowPoint.X, windowPoint.Y);
       }
       case WindowTypes.DXGI: {
     // VirtualScreen座標なので補正を戻す
     return new ScreenPoint(clientX + User32.GetSystemMetrics(User32.SM_XVIRTUALSCREEN),
                        clientY + User32.GetSystemMetrics(User32.SM_YVIRTUALSCREEN));
       }
       case WindowTypes.Desktop: {
     // Screen座標系なのでそのまま返す
     return new ScreenPoint(clientX, clientY);
       }
       default: Debug.Fail("switch"); throw new System.ArgumentException();
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="samplingRate"></param>
        /// <param name="featureCount"></param>
        /// <param name="filterbank"></param>
        /// <param name="frameDuration"></param>
        /// <param name="hopDuration"></param>
        /// <param name="preEmphasis"></param>
        /// <param name="nonLinearity"></param>
        /// <param name="spectrumType"></param>
        /// <param name="window"></param>
        /// <param name="logFloor"></param>
        public FilterbankExtractor(int samplingRate,
                                   int featureCount,
                                   float[][] filterbank,
                                   double frameDuration          = 0.0256 /*sec*/,
                                   double hopDuration            = 0.010 /*sec*/,
                                   double preEmphasis            = 0,
                                   NonLinearityType nonLinearity = NonLinearityType.None,
                                   SpectrumType spectrumType     = SpectrumType.Power,
                                   WindowTypes window            = WindowTypes.Hamming,
                                   float logFloor = float.Epsilon)

            : base(samplingRate, frameDuration, hopDuration, preEmphasis)
        {
            FeatureCount = featureCount;

            FilterBank = filterbank;

            _blockSize = 2 * (filterbank[0].Length - 1);

            Guard.AgainstExceedance(FrameSize, _blockSize, "frame size", "FFT size");

            _fft = new RealFft(_blockSize);

            _window        = window;
            _windowSamples = Window.OfType(_window, FrameSize);

            // setup spectrum post-processing: =======================================================

            _logFloor         = logFloor;
            _nonLinearityType = nonLinearity;
            switch (nonLinearity)
            {
            case NonLinearityType.Log10:
                _postProcessSpectrum = () => FilterBanks.ApplyAndLog10(FilterBank, _spectrum, _bandSpectrum, _logFloor);
                break;

            case NonLinearityType.LogE:
                _postProcessSpectrum = () => FilterBanks.ApplyAndLog(FilterBank, _spectrum, _bandSpectrum, _logFloor);
                break;

            case NonLinearityType.ToDecibel:
                _postProcessSpectrum = () => FilterBanks.ApplyAndToDecibel(FilterBank, _spectrum, _bandSpectrum, _logFloor);
                break;

            case NonLinearityType.CubicRoot:
                _postProcessSpectrum = () => FilterBanks.ApplyAndPow(FilterBank, _spectrum, _bandSpectrum, 0.33);
                break;

            default:
                _postProcessSpectrum = () => FilterBanks.Apply(FilterBank, _spectrum, _bandSpectrum);
                break;
            }

            _spectrumType = spectrumType;
            switch (_spectrumType)
            {
            case SpectrumType.Magnitude:
                _getSpectrum = block => _fft.MagnitudeSpectrum(block, _spectrum, false);
                break;

            case SpectrumType.Power:
                _getSpectrum = block => _fft.PowerSpectrum(block, _spectrum, false);
                break;

            case SpectrumType.MagnitudeNormalized:
                _getSpectrum = block => _fft.MagnitudeSpectrum(block, _spectrum, true);
                break;

            case SpectrumType.PowerNormalized:
                _getSpectrum = block => _fft.PowerSpectrum(block, _spectrum, true);
                break;
            }

            // reserve memory for reusable blocks

            _spectrum     = new float[_blockSize / 2 + 1];
            _bandSpectrum = new float[filterbank.Length];
        }
Ejemplo n.º 17
0
 /// <summary>
 /// FIR filter design using window method
 /// </summary>
 /// <param name="order">Filter order</param>
 /// <param name="frequencyResponse">Complex frequency response</param>
 /// <param name="window">Window</param>
 /// <returns>FIR filter kernel</returns>
 public static FirFilter Fir(int order, ComplexDiscreteSignal frequencyResponse, WindowTypes window = WindowTypes.Blackman)
 {
     return(Fir(order, frequencyResponse.Real, frequencyResponse.Imag, window));
 }
Ejemplo n.º 18
0
        public void Init(Point position, Size size, WindowTypes windowType)
        {
            IntPtr hInstance = processHandle.DangerousGetHandle();
            string szAppName = "ImGuiWindow~" + this.GetHashCode();

            this.wndclass.style         = 0x0002 /*CS_HREDRAW*/ | 0x0001 /*CS_VREDRAW*/ | 0x0020 /*CS_OWNDC*/;
            this.wndclass.lpfnWndProc   = WindowProc;
            this.wndclass.cbClsExtra    = 0;
            this.wndclass.cbWndExtra    = 0;
            this.wndclass.hInstance     = hInstance;
            this.wndclass.hIcon         = LoadIcon(IntPtr.Zero, new IntPtr(32512 /*IDI_APPLICATION*/));
            this.wndclass.hCursor       = LoadCursor(IntPtr.Zero, 32512 /*IDC_ARROW*/);
            this.wndclass.hbrBackground = IntPtr.Zero;// GetStockObject(0);
            this.wndclass.lpszMenuName  = null;
            this.wndclass.lpszClassName = szAppName;


            ushort atom = RegisterClass(ref this.wndclass);

            if (atom == 0)
            {
                throw new WindowCreateException(string.Format("RegisterClass error: {0}", Marshal.GetLastWin32Error()));
            }

            WindowStyles windowStyle;

            switch (windowType)
            {
            case WindowTypes.Regular:
                windowStyle = WindowStyles.WS_OVERLAPPEDWINDOW | WindowStyles.WS_VISIBLE;
                break;

            case WindowTypes.ToolBox:
                windowStyle = WindowStyles.WS_DLGFRAME;
                break;

            case WindowTypes.ToolTip:
                windowStyle = WindowStyles.WS_POPUP;
                break;

            case WindowTypes.Hidden:
                windowStyle = 0;
                break;

            default:
                windowStyle = WindowStyles.WS_OVERLAPPEDWINDOW;
                break;
            }

            // rect of the desired client area
            RECT rc = new RECT
            {
                left   = (int)position.X,
                top    = (int)position.Y,
                right  = (int)(position.X + size.Width),
                bottom = (int)(position.Y + size.Height)
            };

            if (!AdjustWindowRect(ref rc, (uint)windowStyle, false))
            {
                throw new WindowCreateException(string.Format("AdjustWindowRectEx fails, win32 error: {0}", Marshal.GetLastWin32Error()));
            }

            //now rc is the rect of the window

            IntPtr hwnd = CreateWindowEx(
                0 /*0x00000008*//*WS_EX_TOPMOST*/, // window style ex //HACK always on top
                new IntPtr(atom),                  // window class name
                "ImGuiWindow~",                    // window caption
                (uint)windowStyle,                 // window style
                rc.left,                           // initial x position
                rc.top,                            // initial y position
                rc.right - rc.left,                // initial x size
                rc.bottom - rc.top,                // initial y size
                IntPtr.Zero,                       // parent window handle
                IntPtr.Zero,                       // window menu handle
                hInstance,                         // program instance handle
                IntPtr.Zero);                      // creation parameters

            if (hwnd == IntPtr.Zero)
            {
                throw new WindowCreateException(string.Format("CreateWindowEx error: {0}", Marshal.GetLastWin32Error()));
            }

            this.hwnd = hwnd;
        }
Ejemplo n.º 19
0
        /// 現在編集中のレイアウト要素のクリッピング領域/Fitオプションを変更する
        private void CommonAreaSelect(bool changeWindowType      = false,
                                      WindowTypes nextWindowType = WindowTypes.Normal)
        {
            OnDragHereSetTargetWindow(null, EventArgs.Empty);

            if (!App.Profile.Current.IsWindowValid)
            {
                Debug.WriteLine("Invalid Window", "Area.CommonAreaSelect");
                return;
            }

            //-----------------------------------------------------------------
            // ダイアログの準備
            //-----------------------------------------------------------------
            var dialog = new AreaSelectWindow();

            // サイズ
            var screenRect = App.Profile.Current.ScreenClippingRectWithFit;

            dialog.Left   = screenRect.X;
            dialog.Top    = screenRect.Y;
            dialog.Width  = screenRect.Width;
            dialog.Height = screenRect.Height;

            // カラーの変更
            Brush border, background;

            this.GetWindowTypesBrushes(
                App.Profile.Current.WindowType, nextWindowType,
                out border, out background);
            dialog.WindowBorder.BorderBrush = border;
            dialog.WindowGrid.Background    = background;

            // ダイアログの表示
            var result = dialog.ShowDialog();

            if (!result.HasValue || !(bool)result)
            {
                return;
            }

            // 結果をScreenRectにまとめる
            var nextScreenRect = new ScreenRect(
                (int)dialog.Left, (int)dialog.Top, (int)dialog.Width, (int)dialog.Height);

            // Profile更新
            App.Profile.Open();
            if (changeWindowType)
            {
                switch (nextWindowType)
                {
                case WindowTypes.DXGI: {
                    App.Profile.Current.SetWindowToDXGI();
                    break;
                }

                case WindowTypes.Desktop: {
                    App.Profile.Current.SetWindowToDesktop();
                    break;
                }

                default: Debug.Fail("switch"); throw new System.ArgumentException();
                }
            }
            App.Profile.Current.SetClippingRectByScreenRect(nextScreenRect);
            App.Profile.Current.ClearBackupParameters();
            App.Profile.Close();

            //-----------------------------------------------------------------
            // Notify self
            this.OnCurrentLayoutElementChanged();
            // Notify other controls
            if (changeWindowType)
            {
                Commands.TargetWindowChanged.Execute(null, this);
            }
            else
            {
                // TargetWindowの更新は必要ないのでプレビューのみ更新
                Commands.CurrentLayoutElementVisualChanged.Execute(null, this);
            }
            //-----------------------------------------------------------------
        }
Ejemplo n.º 20
0
        /// <summary>
        ///     Gets the time samples for the specified window.
        /// </summary>
        /// <param name="type">The window type.</param>
        /// <param name="length">The length.</param>
        /// <returns></returns>
        public static IEnumerable <double> GetWindow(WindowTypes type, int length)
        {
            var hw = GetHalfWindow(type, (length >> 1) + 1).ToReadOnlyList();

            return(hw.Reverse().Concat(hw.GetPaddedRange(1, ((length + 1) >> 1) - 1)));
        }
Ejemplo n.º 21
0
        /// WindowタイプをNormalに+Windowハンドルを設定する
        /// @param window 設定するWindowハンドル
        public void SetWindow(UIntPtr window)
        {
            this.additionalData.WindowType = WindowTypes.Normal;
            this.rawData.Window = window;

            var windowCaption = "n/a";
            if (Common.Utilities.IsWindowValid(window)) {
              StringBuilder className = new StringBuilder(256);
              User32.GetClassName(window, className, 256);
              windowCaption = className.ToString();
            }
            this.additionalData.WindowCaption = windowCaption;
        }
Ejemplo n.º 22
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="Window" /> Class. The window will have its maximum at time 0.
 /// </summary>
 /// <param name="type">The window type.</param>
 /// <param name="length">The window length.</param>
 /// <param name="samplerate">The window samplerate.</param>
 /// <param name="mode">The window mode.</param>
 public Window(WindowTypes type, int length, double samplerate, WindowModes mode)
     : this(type, GetDefaultStart(mode, length), length, samplerate, mode)
 {
 }
Ejemplo n.º 23
0
 /// WindowタイプをDXGIにする
 public void SetWindowToDXGI()
 {
     this.additionalData.WindowType = WindowTypes.DXGI;
     this.rawData.Window = Utilities.DXGIWindow;
     this.additionalData.WindowCaption = "(DXGI)";
 }
Ejemplo n.º 24
0
        /// <summary>
        ///     Gets the positive half of a window function.
        /// </summary>
        /// <param name="type">The window type.</param>
        /// <param name="length">The length of the half window.</param>
        /// <returns></returns>
        /// <remarks>https://en.wikipedia.org/wiki/Window_function#A_list_of_window_functions</remarks>
        public static IEnumerable <double> GetHalfWindow(WindowTypes type, int length)
        {
            // first value is always 1
            yield return(1.0);

            switch (type)
            {
            case WindowTypes.Rectangular:
                for (var n = length - 1; n > 0; n--)
                {
                    yield return(1.0);
                }
                break;

            case WindowTypes.Hann:
                for (var n = length - 1; n > 0; n--)
                {
                    yield return(0.5 * (1 - Math.Cos(Math.PI * n / length)));
                }
                break;

            case WindowTypes.Hamming:
                for (var n = length - 1; n > 0; n--)
                {
                    yield return(0.54 - 0.46 * Math.Cos(Math.PI * n / length));
                }
                break;

            case WindowTypes.Triangular:
                for (var n = length - 1; n > 0; n--)
                {
                    yield return(1 - (double)(length - n) / length);
                }
                break;

            case WindowTypes.Welch:
                for (var n = length - 1; n > 0; n--)
                {
                    yield return(1 - Math.Pow((double)(length - n) / length, 2));
                }
                break;

            case WindowTypes.Blackman:
                for (var n = length - 1; n > 0; n--)
                {
                    yield return(0.42659 - 0.49656 * Math.Cos(Math.PI * n / length) + 0.076849 * Math.Cos(2 * Math.PI * n / length));
                }
                break;

            case WindowTypes.BlackmanHarris:
                for (var n = length - 1; n > 0; n--)
                {
                    yield return(0.35875 - 0.48829 * Math.Cos(Math.PI * n / length) + 0.14128 * Math.Cos(2 * Math.PI * n / length) -
                                 0.01168 * Math.Cos(3 * Math.PI * n / length));
                }
                break;

            case WindowTypes.KaiserAlpha2:
            {
                var denom = Dsp.ModBessel0(Math.PI * 2);
                for (var n = length - 1; n > 0; n--)
                {
                    yield return(Dsp.ModBessel0(Math.PI * 2 * Math.Sqrt(1 - Math.Pow((double)n / length - 1, 2))) / denom);
                }
            }
            break;

            case WindowTypes.KaiserAlpha3:
            {
                var denom = Dsp.ModBessel0(Math.PI * 3);
                for (var n = length - 1; n > 0; n--)
                {
                    yield return(Dsp.ModBessel0(Math.PI * 3 * Math.Sqrt(1 - Math.Pow((double)n / length - 1, 2))) / denom);
                }
            }
            break;
            }
        }
Ejemplo n.º 25
0
        /// 現在編集中のレイアウト要素のクリッピング領域/Fitオプションを変更する
        private void CommonAreaSelect(bool changeWindowType = false,
            WindowTypes nextWindowType = WindowTypes.Normal)
        {
            if (!App.Profile.Current.IsWindowValid) {
              Debug.WriteLine("Invalid Window", "Area.CommonAreaSelect");
              return;
            }

            //-----------------------------------------------------------------
            // ダイアログの準備
            //-----------------------------------------------------------------
            var dialog = new AreaSelectWindow();

            // サイズ
            var screenRect = App.Profile.Current.ScreenClippingRectWithFit;
            dialog.Left   = screenRect.X;
            dialog.Top    = screenRect.Y;
            dialog.Width  = screenRect.Width;
            dialog.Height = screenRect.Height;

            // カラーの変更
            Brush border, background;
            this.GetWindowTypesBrushes(
            App.Profile.Current.WindowType, nextWindowType,
            out border, out background);
            dialog.WindowBorder.BorderBrush = border;
            dialog.WindowGrid.Background = background;

            // ダイアログの表示
            var result = dialog.ShowDialog();
            if (!result.HasValue || !(bool)result) return;

            // 結果をScreenRectにまとめる
            var nextScreenRect = new ScreenRect(
            (int)dialog.Left, (int)dialog.Top, (int)dialog.Width, (int)dialog.Height);

            // Profile更新
            App.Profile.Open();
            if (changeWindowType) {
              switch (nextWindowType) {
            case WindowTypes.DXGI: {
              App.Profile.Current.SetWindowToDXGI();
              break;
            }
            case WindowTypes.Desktop: {
              App.Profile.Current.SetWindowToDesktop();
              break;
            }
            default: Debug.Fail("switch"); throw new System.ArgumentException();
              }
            }
            App.Profile.Current.SetClippingRectByScreenRect(nextScreenRect);
            App.Profile.Current.ClearBackupParameters();
            App.Profile.Close();

            //-----------------------------------------------------------------
            // Notify self
            this.OnCurrentLayoutElementChanged();
            // Notify other controls
            if (changeWindowType) {
              Commands.TargetWindowChanged.Execute(null, this);
            } else {
              // TargetWindowの更新は必要ないのでプレビューのみ更新
              Commands.CurrentLayoutElementVisualChanged.Execute(null, this);
            }
            //-----------------------------------------------------------------
        }
Ejemplo n.º 26
0
 internal Form(Point position, Size size, WindowTypes type)
     : this(position, size, "ImGui Form", type)
 {
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Opens a window.
 /// </summary>
 /// <param name="window">The type of window to open.</param>
 public static void OpenWindow(WindowTypes window)
 {
     OnWindowOpen?.Invoke(Properties.windows[(int)window]);
 }
Ejemplo n.º 28
0
 internal Form(Rect rect, string title, WindowTypes type)
     : this(rect.TopLeft, rect.Size, title, type)
 {
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="samplingRate"></param>
        /// <param name="featureList"></param>
        /// <param name="frameDuration"></param>
        /// <param name="hopDuration"></param>
        /// <param name="fftSize"></param>
        /// <param name="frequencyBands"></param>
        /// <param name="parameters"></param>
        public Mpeg7SpectralFeaturesExtractor(int samplingRate,
                                              string featureList,
                                              double frameDuration = 0.0256 /*sec*/,
                                              double hopDuration   = 0.010 /*sec*/,
                                              int fftSize          = 0,
                                              Tuple <double, double, double>[] frequencyBands = null,
                                              WindowTypes window = WindowTypes.Hamming,
                                              IReadOnlyDictionary <string, object> parameters = null)

            : base(samplingRate, frameDuration, hopDuration)
        {
            if (featureList == "all" || featureList == "full")
            {
                featureList = FeatureSet;
            }

            var features = featureList.Split(',', '+', '-', ';', ':')
                           .Select(f => f.Trim().ToLower());

            _extractors = features.Select <string, Func <float[], float[], float> >(feature =>
            {
                switch (feature)
                {
                case "sc":
                case "centroid":
                    return(Spectral.Centroid);

                case "ss":
                case "spread":
                    return(Spectral.Spread);

                case "sfm":
                case "flatness":
                    if (parameters?.ContainsKey("minLevel") ?? false)
                    {
                        var minLevel = (float)parameters["minLevel"];
                        return((spectrum, freqs) => Spectral.Flatness(spectrum, minLevel));
                    }
                    else
                    {
                        return((spectrum, freqs) => Spectral.Flatness(spectrum));
                    }

                case "sn":
                case "noiseness":
                    if (parameters?.ContainsKey("noiseFrequency") ?? false)
                    {
                        var noiseFrequency = (float)parameters["noiseFrequency"];
                        return((spectrum, freqs) => Spectral.Noiseness(spectrum, freqs, noiseFrequency));
                    }
                    else
                    {
                        return((spectrum, freqs) => Spectral.Noiseness(spectrum, freqs));
                    }

                case "rolloff":
                    if (parameters?.ContainsKey("rolloffPercent") ?? false)
                    {
                        var rolloffPercent = (float)parameters["rolloffPercent"];
                        return((spectrum, freqs) => Spectral.Rolloff(spectrum, freqs, rolloffPercent));
                    }
                    else
                    {
                        return((spectrum, freqs) => Spectral.Rolloff(spectrum, freqs));
                    }

                case "crest":
                    return((spectrum, freqs) => Spectral.Crest(spectrum));

                case "entropy":
                case "ent":
                    return((spectrum, freqs) => Spectral.Entropy(spectrum));

                case "sd":
                case "decrease":
                    return((spectrum, freqs) => Spectral.Decrease(spectrum));

                case "loud":
                case "loudness":
                    return((spectrum, freqs) => Perceptual.Loudness(spectrum));

                case "sharp":
                case "sharpness":
                    return((spectrum, freqs) => Perceptual.Sharpness(spectrum));

                default:
                    return((spectrum, freqs) => 0);
                }
            }).ToList();

            FeatureDescriptions = features.ToList();

            _fftSize = fftSize > FrameSize ? fftSize : MathUtils.NextPowerOfTwo(FrameSize);
            _fft     = new Fft(_fftSize);

            _window = window;
            if (_window != WindowTypes.Rectangular)
            {
                _windowSamples = Window.OfType(_window, FrameSize);
            }

            _frequencyBands = frequencyBands ?? FilterBanks.OctaveBands(6, _fftSize, samplingRate);
            _filterbank     = FilterBanks.Rectangular(_fftSize, samplingRate, _frequencyBands);

            var cfs = _frequencyBands.Select(b => b.Item2).ToList();

            // insert zero frequency so that it'll be ignored during calculations
            // just like in case of FFT spectrum (0th DC component)
            cfs.Insert(0, 0);
            _frequencies = cfs.ToFloats();

            _parameters = parameters;

            // reserve memory for reusable blocks

            _spectrum       = new float[_fftSize / 2 + 1];          // buffer for magnitude spectrum
            _mappedSpectrum = new float[_filterbank.Length + 1];    // buffer for total energies in bands
            _block          = new float[_fftSize];                  // buffer for currently processed block
            _zeroblock      = new float[_fftSize];                  // just a buffer of zeros for quick memset
        }
Ejemplo n.º 30
0
 private void windowsComboBox_SelectedIndexChanged(object sender, EventArgs e)
 {
     _windowType     = (WindowTypes)windowsComboBox.SelectedIndex;
     windowPlot.Line = Window.OfType(_windowType, 256);
 }
Ejemplo n.º 31
0
        /// <summary>
        /// FIR filter design using window method
        /// </summary>
        /// <param name="order">Filter order</param>
        /// <param name="magnitudeResponse">Magnitude response</param>
        /// <param name="phaseResponse">Phase response</param>
        /// <param name="window">Window</param>
        /// <returns>FIR filter kernel</returns>
        public static FirFilter Fir(int order, double[] magnitudeResponse, double[] phaseResponse = null, WindowTypes window = WindowTypes.Blackman)
        {
            if (order % 2 == 0)
            {
                throw new ArgumentException("The order of a filter must be an odd number!");
            }

            var fftSize = MathUtils.NextPowerOfTwo(magnitudeResponse.Length);

            var real = phaseResponse == null?
                       magnitudeResponse.PadZeros(fftSize) :
                           magnitudeResponse.Zip(phaseResponse, (m, p) => m * Math.Cos(p)).ToArray();

            var imag = phaseResponse == null ?
                       new double[fftSize] :
                       magnitudeResponse.Zip(phaseResponse, (m, p) => m * Math.Sin(p)).ToArray();

            var fft = new Fft64(fftSize);

            fft.Inverse(real, imag);

            var kernel = new double[order];

            var compensation = 2.0 / fftSize;
            var middle       = order / 2;

            for (var i = 0; i <= middle; i++)
            {
                kernel[i]          = real[middle - i] * compensation;
                kernel[i + middle] = real[i] * compensation;
            }

            kernel.ApplyWindow(window);

            return(new FirFilter(kernel));
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="samplingRate"></param>
        /// <param name="featureCount"></param>
        /// <param name="frameDuration"></param>
        /// <param name="hopDuration"></param>
        /// <param name="lpcOrder"></param>
        /// <param name="rasta"></param>
        /// <param name="filterbankSize"></param>
        /// <param name="lowFreq"></param>
        /// <param name="highFreq"></param>
        /// <param name="fftSize"></param>
        /// <param name="lifterSize"></param>
        /// <param name="preEmphasis"></param>
        /// <param name="window"></param>
        /// <param name="filterbank"></param>
        /// <param name="centerFrequencies"></param>
        public PlpExtractor(int samplingRate,
                            int featureCount,
                            double frameDuration       = 0.0256 /*sec*/,
                            double hopDuration         = 0.010 /*sec*/,
                            int lpcOrder               = 0,         // will be autocalculated as featureCount - 1
                            double rasta               = 0,
                            int filterbankSize         = 24,
                            double lowFreq             = 0,
                            double highFreq            = 0,
                            int fftSize                = 0,
                            int lifterSize             = 0,
                            double preEmphasis         = 0,
                            WindowTypes window         = WindowTypes.Hamming,
                            float[][] filterbank       = null,
                            double[] centerFrequencies = null)

            : base(samplingRate, frameDuration, hopDuration, preEmphasis)
        {
            FeatureCount = featureCount;

            // ================================ Prepare filter bank and center frequencies: ===========================================

            _lowFreq  = lowFreq;
            _highFreq = highFreq;

            if (filterbank == null)
            {
                _blockSize = fftSize > FrameSize ? fftSize : MathUtils.NextPowerOfTwo(FrameSize);

                var barkBands = FilterBanks.BarkBandsSlaney(filterbankSize, _blockSize, samplingRate, _lowFreq, _highFreq);
                FilterBank = FilterBanks.BarkBankSlaney(filterbankSize, _blockSize, samplingRate, _lowFreq, _highFreq);

                _centerFrequencies = barkBands.Select(b => b.Item2).ToArray();
            }
            else
            {
                FilterBank     = filterbank;
                filterbankSize = filterbank.Length;
                _blockSize     = 2 * (filterbank[0].Length - 1);

                Guard.AgainstExceedance(FrameSize, _blockSize, "frame size", "FFT size");

                if (centerFrequencies != null)
                {
                    _centerFrequencies = centerFrequencies;
                }
                else
                {
                    var herzResolution = (double)samplingRate / _blockSize;

                    // try to determine center frequencies automatically from filterbank weights:

                    _centerFrequencies = new double[filterbankSize];

                    for (var i = 0; i < filterbank.Length; i++)
                    {
                        var minPos = 0;
                        var maxPos = _blockSize / 2;

                        for (var j = 0; j < filterbank[i].Length; j++)
                        {
                            if (filterbank[i][j] > 0)
                            {
                                minPos = j;
                                break;
                            }
                        }
                        for (var j = minPos; j < filterbank[i].Length; j++)
                        {
                            if (filterbank[i][j] == 0)
                            {
                                maxPos = j;
                                break;
                            }
                        }

                        _centerFrequencies[i] = herzResolution * (maxPos + minPos) / 2;
                    }
                }
            }

            // ==================================== Compute equal loudness curve: =========================================

            _equalLoudnessCurve = new double[filterbankSize];

            for (var i = 0; i < _centerFrequencies.Length; i++)
            {
                var level2 = _centerFrequencies[i] * _centerFrequencies[i];

                _equalLoudnessCurve[i] = Math.Pow(level2 / (level2 + 1.6e5), 2) * ((level2 + 1.44e6) / (level2 + 9.61e6));
            }

            // ============================== Prepare RASTA filters (if necessary): =======================================

            _rasta = rasta;

            if (rasta > 0)
            {
                _rastaFilters = Enumerable.Range(0, filterbankSize)
                                .Select(f => new RastaFilter(rasta))
                                .ToArray();
            }

            // ============== Precompute IDFT table for obtaining autocorrelation coeffs from power spectrum: =============

            _lpcOrder = lpcOrder > 0 ? lpcOrder : FeatureCount - 1;

            _idftTable = new float[_lpcOrder + 1][];

            var bandCount = filterbankSize + 2;     // +2 duplicated edges
            var freq      = Math.PI / (bandCount - 1);

            for (var i = 0; i < _idftTable.Length; i++)
            {
                _idftTable[i] = new float[bandCount];

                _idftTable[i][0] = 1.0f;

                for (var j = 1; j < bandCount - 1; j++)
                {
                    _idftTable[i][j] = 2 * (float)Math.Cos(freq * i * j);
                }

                _idftTable[i][bandCount - 1] = (float)Math.Cos(freq * i * (bandCount - 1));
            }

            _lpc = new float[_lpcOrder + 1];
            _cc  = new float[bandCount];

            // =================================== Prepare everything else: ==============================

            _fft = new RealFft(_blockSize);

            _window        = window;
            _windowSamples = Window.OfType(_window, FrameSize);

            _lifterSize   = lifterSize;
            _lifterCoeffs = _lifterSize > 0 ? Window.Liftering(FeatureCount, _lifterSize) : null;

            _spectrum     = new float[_blockSize / 2 + 1];
            _bandSpectrum = new float[filterbankSize];
        }