biquad-0.4.2/.cargo_vcs_info.json0000644000000001360000000000100123040ustar { "git": { "sha1": "c1363bece06853d25668728abeffe0133bf81630" }, "path_in_vcs": "" }biquad-0.4.2/.gitignore000064400000000000000000000000360072674642500131130ustar 00000000000000/target **/*.rs.bk Cargo.lock biquad-0.4.2/.travis.yml000064400000000000000000000005320072674642500132350ustar 00000000000000language: rust matrix: include: - rust: stable - rust: beta - rust: nightly before_install: set -e script: - cargo check - cargo test after_script: set +e cache: cargo before_cache: # Travis can't cache files that are not readable by "others" - chmod -R a+r $HOME/.cargo notifications: email: on_success: never biquad-0.4.2/CHANGELOG.md000064400000000000000000000025430072674642500127410ustar 00000000000000# Change Log All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ## [v0.4.2] - 2022-01-14 ### Fixed - Corrected first order low pass filter coefficients ## [v0.4.1] - 2021-04-22 ### Fixed ### Added * Reset state method added * Method to replace the coefficients and return the old coefficients instead of dropping them added ### Changes ## [v0.4.0] - 2021-01-16 ### Fixed * Broken links ### Added * The rest of the filters from the audio cookbook ## [v0.3.1] - 2020-04-10 ### Added * Bandpass filter added ## [v0.3.0] - 2019-07-23 ### Added * Now with `f64` support, waiting for `libm` support in `num-traits` to make it generic ### Changes ## [v0.2.0] First changelog. [Unreleased]: https://github.com/korken89/biquad-rs/compare/v0.4.2...master [v0.4.1]: https://github.com/korken89/biquad-rs/compare/v0.4.1...v0.4.2 [v0.4.1]: https://github.com/korken89/biquad-rs/compare/v0.4.0...v0.4.1 [v0.4.0]: https://github.com/korken89/biquad-rs/compare/v0.3.1...v0.4.0 [v0.3.1]: https://github.com/korken89/biquad-rs/compare/v0.3.0...v0.3.1 [v0.3.0]: https://github.com/korken89/biquad-rs/compare/v0.2.0...v0.3.0 [v0.2.0]: https://github.com/korken89/biquad-rs/compare/v0.1.0...v0.2.0 biquad-0.4.2/Cargo.toml0000644000000015610000000000100103050ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "biquad" version = "0.4.2" authors = ["Emil Fresk "] description = "A library for digital second order IIR filtrers, also known as biquads." readme = "README.md" keywords = ["biquad", "filter", "iir"] categories = ["embedded", "no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/korken89/biquad-rs" [dependencies.libm] version = "0.1.4" biquad-0.4.2/Cargo.toml.orig000064400000000000000000000006270072674642500140200ustar 00000000000000[package] name = "biquad" version = "0.4.2" authors = ["Emil Fresk "] description = "A library for digital second order IIR filtrers, also known as biquads." categories = ["embedded", "no-std"] keywords = ["biquad", "filter", "iir"] readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/korken89/biquad-rs" edition = "2018" [dependencies] libm = "0.1.4" biquad-0.4.2/LICENSE-APACHE000064400000000000000000000251370072674642500130600ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. biquad-0.4.2/LICENSE-MIT000064400000000000000000000020230072674642500125550ustar 00000000000000Copyright (c) 2018 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. biquad-0.4.2/README.md000064400000000000000000000037370072674642500124150ustar 00000000000000# `biquad` [![Build Status](https://www.travis-ci.org/korken89/biquad-rs.svg?branch=master)](https://www.travis-ci.org/korken89/biquad-rs) `biquad` is a `#![no_std]` library for creating first and second order IIR filters for signal processing based on [Biquads](https://en.wikipedia.org/wiki/Digital_biquad_filter). Both a Direct Form 1 (DF1) and Direct Form 2 Transposed (DF2T) implementation is available, where the DF1 is better used when the filter needs retuning online, as it has the property to introduce minimal artifacts under retuning, while the DF2T is best used for static filters as it has the least computational complexity and best numerical stability. This crate implements the biquads for `f32` and `f64`. ## Example ```rust fn main() { use biquad::*; // Cutoff and sampling frequencies let f0 = 10.hz(); let fs = 1.khz(); // Create coefficients for the biquads let coeffs = Coefficients::::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F32).unwrap(); // Create two different biquads let mut biquad1 = DirectForm1::::new(coeffs); let mut biquad2 = DirectForm2Transposed::::new(coeffs); let input_vec = vec![0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]; let mut output_vec1 = Vec::new(); let mut output_vec2 = Vec::new(); // Run for all the inputs for elem in input_vec { output_vec1.push(biquad1.run(elem)); output_vec2.push(biquad2.run(elem)); } } ``` # [Documentation](https://docs.rs/biquad) # License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. biquad-0.4.2/src/coefficients.rs000064400000000000000000000424040072674642500147260ustar 00000000000000//! # coefficients //! //! Module for generating filter coefficients for second order IIR biquads, where the coefficients //! form the following Z-domain transfer function: //! ```text //! b0 + b1 * z^-1 + b2 * z^-2 //! H(z) = -------------------------- //! 1 + a1 * z^-1 + a2 * z^-2 //! ``` //! //! The second orders filter are based on the //! [Audio EQ Cookbook](https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html), while the first order //! low pass filter is based on the following //! [Wikipedia article](https://en.wikipedia.org/wiki/Low-pass_filter#Discrete-time_realization). //! //! //! # Examples //! //! ``` //! fn main() { //! use biquad::*; //! //! // Cutoff frequency //! let f0 = 10.hz(); //! //! // Sampling frequency //! let fs = 1.khz(); //! //! // Create coefficients //! let coeffs = Coefficients::::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F32); //! } //! ``` //! //! # Errors //! //! `Coefficients::from_params(...)` can error if the cutoff frequency does not adhere to the //! [Nyquist Frequency](https://en.wikipedia.org/wiki/Nyquist_frequency), or if the Q value is //! negative. use crate::{frequency::Hertz, Errors}; // For some reason this is not detected properly #[allow(unused_imports)] use libm::{F32Ext, F64Ext}; /// Common Q value of the Butterworth low-pass filter pub const Q_BUTTERWORTH_F32: f32 = core::f32::consts::FRAC_1_SQRT_2; pub const Q_BUTTERWORTH_F64: f64 = core::f64::consts::FRAC_1_SQRT_2; /// The supported types of biquad coefficients. Note that single pole low pass filters are faster to /// retune, as all other filter types require evaluations of sin/cos functions /// The `LowShelf`, `HighShelf`, and `PeakingEQ` all have a gain value for its /// field, and represents the gain, in decibels, that the filter provides. #[derive(Clone, Copy, Debug)] pub enum Type { SinglePoleLowPassApprox, SinglePoleLowPass, LowPass, HighPass, BandPass, Notch, AllPass, LowShelf(DBGain), HighShelf(DBGain), PeakingEQ(DBGain), } /// Holder of the biquad coefficients, utilizes normalized form #[derive(Clone, Copy, Debug)] pub struct Coefficients { // Denominator coefficients pub a1: T, pub a2: T, // Nominator coefficients pub b0: T, pub b1: T, pub b2: T, } impl Coefficients { /// Creates coefficients based on the biquad filter type, sampling and cutoff frequency, and Q /// value. Note that the cutoff frequency must be smaller than half the sampling frequency and /// that Q may not be negative, this will result in an `Err()`. pub fn from_params( filter: Type, fs: Hertz, f0: Hertz, q_value: f32, ) -> Result, Errors> { if 2.0 * f0.hz() > fs.hz() { return Err(Errors::OutsideNyquist); } if q_value < 0.0 { return Err(Errors::NegativeQ); } let omega = 2.0 * core::f32::consts::PI * f0.hz() / fs.hz(); match filter { Type::SinglePoleLowPassApprox => { let alpha = omega / (omega + 1.0); Ok(Coefficients { a1: alpha - 1.0, a2: 0.0, b0: alpha, b1: 0.0, b2: 0.0, }) } Type::SinglePoleLowPass => { let omega_t = (omega / 2.0).tan(); let a0 = 1.0 + omega_t; Ok(Coefficients { a1: (omega_t - 1.0) / a0, a2: 0.0, b0: omega_t / a0, b1: omega_t / a0, b2: 0.0, }) } Type::LowPass => { // The code for omega_s/c and alpha is currently duplicated due to the single pole // low pass filter not needing it and when creating coefficients are commonly // assumed to be of low computational complexity. let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = (1.0 - omega_c) * 0.5; let b1 = 1.0 - omega_c; let b2 = (1.0 - omega_c) * 0.5; let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } Type::HighPass => { let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = (1.0 + omega_c) * 0.5; let b1 = -(1.0 + omega_c); let b2 = (1.0 + omega_c) * 0.5; let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } Type::BandPass => { let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = omega_s / 2.0; let b1 = 0.; let b2 = -(omega_s / 2.0); let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; let div = 1.0 / a0; Ok(Coefficients { a1: a1 * div, a2: a2 * div, b0: b0 * div, b1: b1 * div, b2: b2 * div, }) } Type::Notch => { let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = 1.0; let b1 = -2.0 * omega_c; let b2 = 1.0; let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } Type::AllPass => { let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = 1.0 - alpha; let b1 = -2.0 * omega_c; let b2 = 1.0 + alpha; let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } Type::LowShelf(db_gain) => { let a = 10.0f32.powf(db_gain / 40.0); let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = a * ((a + 1.0) - (a - 1.0) * omega_c + 2.0 * alpha * a.sqrt()); let b1 = 2.0 * a * ((a - 1.0) - (a + 1.0) * omega_c); let b2 = a * ((a + 1.0) - (a - 1.0) * omega_c - 2.0 * alpha * a.sqrt()); let a0 = (a + 1.0) + (a - 1.0) * omega_c + 2.0 * alpha * a.sqrt(); let a1 = -2.0 * ((a - 1.0) + (a + 1.0) * omega_c); let a2 = (a + 1.0) + (a - 1.0) * omega_c - 2.0 * alpha * a.sqrt(); Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } Type::HighShelf(db_gain) => { let a = 10.0f32.powf(db_gain / 40.0); let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = a * ((a + 1.0) + (a - 1.0) * omega_c + 2.0 * alpha * a.sqrt()); let b1 = -2.0 * a * ((a - 1.0) + (a + 1.0) * omega_c); let b2 = a * ((a + 1.0) + (a - 1.0) * omega_c - 2.0 * alpha * a.sqrt()); let a0 = (a + 1.0) - (a - 1.0) * omega_c + 2.0 * alpha * a.sqrt(); let a1 = 2.0 * ((a - 1.0) - (a + 1.0) * omega_c); let a2 = (a + 1.0) - (a - 1.0) * omega_c - 2.0 * alpha * a.sqrt(); Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } Type::PeakingEQ(db_gain) => { let a = 10.0f32.powf(db_gain / 40.0); let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = 1.0 + alpha * a; let b1 = -2.0 * omega_c; let b2 = 1.0 - alpha * a; let a0 = 1.0 + alpha / a; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha / a; Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } } } } impl Coefficients { /// Creates coefficients based on the biquad filter type, sampling and cutoff frequency, and Q /// value. Note that the cutoff frequency must be smaller than half the sampling frequency and /// that Q may not be negative, this will result in an `Err()`. pub fn from_params( filter: Type, fs: Hertz, f0: Hertz, q_value: f64, ) -> Result, Errors> { if 2.0 * f0.hz() > fs.hz() { return Err(Errors::OutsideNyquist); } if q_value < 0.0 { return Err(Errors::NegativeQ); } let omega = 2.0 * core::f64::consts::PI * f0.hz() / fs.hz(); match filter { Type::SinglePoleLowPassApprox => { let alpha = omega / (omega + 1.0); Ok(Coefficients { a1: alpha - 1.0, a2: 0.0, b0: alpha, b1: 0.0, b2: 0.0, }) } Type::SinglePoleLowPass => { let omega_t = (omega / 2.0).tan(); let a0 = 1.0 + omega_t; Ok(Coefficients { a1: (omega_t - 1.0) / a0, a2: 0.0, b0: omega_t / a0, b1: omega_t / a0, b2: 0.0, }) } Type::LowPass => { // The code for omega_s/c and alpha is currently duplicated due to the single pole // low pass filter not needing it and when creating coefficients are commonly // assumed to be of low computational complexity. let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = (1.0 - omega_c) * 0.5; let b1 = 1.0 - omega_c; let b2 = (1.0 - omega_c) * 0.5; let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; let div = 1.0 / a0; Ok(Coefficients { a1: a1 * div, a2: a2 * div, b0: b0 * div, b1: b1 * div, b2: b2 * div, }) } Type::HighPass => { let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = (1.0 + omega_c) * 0.5; let b1 = -(1.0 + omega_c); let b2 = (1.0 + omega_c) * 0.5; let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; let div = 1.0 / a0; Ok(Coefficients { a1: a1 * div, a2: a2 * div, b0: b0 * div, b1: b1 * div, b2: b2 * div, }) } Type::Notch => { let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = 1.0; let b1 = -2.0 * omega_c; let b2 = 1.0; let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; let div = 1.0 / a0; Ok(Coefficients { a1: a1 * div, a2: a2 * div, b0: b0 * div, b1: b1 * div, b2: b2 * div, }) } Type::BandPass => { let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = omega_s / 2.0; let b1 = 0.; let b2 = -(omega_s / 2.0); let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; let div = 1.0 / a0; Ok(Coefficients { a1: a1 * div, a2: a2 * div, b0: b0 * div, b1: b1 * div, b2: b2 * div, }) } Type::AllPass => { let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = 1.0 - alpha; let b1 = -2.0 * omega_c; let b2 = 1.0 + alpha; let a0 = 1.0 + alpha; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha; Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } Type::LowShelf(db_gain) => { let a = 10.0f64.powf(db_gain / 40.0); let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = a * ((a + 1.0) - (a - 1.0) * omega_c + 2.0 * alpha * a.sqrt()); let b1 = 2.0 * a * ((a - 1.0) - (a + 1.0) * omega_c); let b2 = a * ((a + 1.0) - (a - 1.0) * omega_c - 2.0 * alpha * a.sqrt()); let a0 = (a + 1.0) + (a - 1.0) * omega_c + 2.0 * alpha * a.sqrt(); let a1 = -2.0 * ((a - 1.0) + (a + 1.0) * omega_c); let a2 = (a + 1.0) + (a - 1.0) * omega_c - 2.0 * alpha * a.sqrt(); Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } Type::HighShelf(db_gain) => { let a = 10.0f64.powf(db_gain / 40.0); let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = a * ((a + 1.0) + (a - 1.0) * omega_c + 2.0 * alpha * a.sqrt()); let b1 = -2.0 * a * ((a - 1.0) + (a + 1.0) * omega_c); let b2 = a * ((a + 1.0) + (a - 1.0) * omega_c - 2.0 * alpha * a.sqrt()); let a0 = (a + 1.0) - (a - 1.0) * omega_c + 2.0 * alpha * a.sqrt(); let a1 = 2.0 * ((a - 1.0) - (a + 1.0) * omega_c); let a2 = (a + 1.0) - (a - 1.0) * omega_c - 2.0 * alpha * a.sqrt(); Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } Type::PeakingEQ(db_gain) => { let a = 10.0f64.powf(db_gain / 40.0); let omega_s = omega.sin(); let omega_c = omega.cos(); let alpha = omega_s / (2.0 * q_value); let b0 = 1.0 + alpha * a; let b1 = -2.0 * omega_c; let b2 = 1.0 - alpha * a; let a0 = 1.0 + alpha / a; let a1 = -2.0 * omega_c; let a2 = 1.0 - alpha / a; Ok(Coefficients { a1: a1 / a0, a2: a2 / a0, b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, }) } } } } biquad-0.4.2/src/frequency.rs000064400000000000000000000121150072674642500142620ustar 00000000000000//! # frequency //! //! A helper module for creating type-safe frequencies, while also allowing to create frequencies //! from float and integer literals. //! //! # Examples //! //! ```ignore //! fn main() { //! use biquad::frequency::*; //! //! // Integer literals //! let one_hz = 1.hz(); //! let one_khz = 1.khz(); //! let one_mhz = 1.mhz(); //! //! // Float literals //! let one_hz = 1.0.dt(); //! let ten_hz = 0.1.dt(); //! } //! ``` //! //! # Errors //! //! `Hertz::from_hz(...)` will error if the frequency is negative. //! //! # Panics //! //! `x.hz()`, `x.khz()`, `x.mhz()`, `x.dt()` will panic for `f32` if they are negative. //! use crate::Errors; /// Base type for frequency, everything is based on Hertz #[derive(PartialOrd, PartialEq, Debug, Copy, Clone)] pub struct Hertz(T); /// Used to implement conversions to the Hertz struct pub trait ToHertz { /// From hertz fn hz(self) -> Hertz; /// From kilohertz fn khz(self) -> Hertz; /// From megahertz fn mhz(self) -> Hertz; /// From delta time (in seconds) fn dt(self) -> Hertz; } // ----------------------------------------------- // f32 implementation // ----------------------------------------------- impl ToHertz for f32 { fn hz(self) -> Hertz { Hertz::::from_hz(self).unwrap() } fn khz(self) -> Hertz { Hertz::::from_hz(self * 1_000.0).unwrap() } fn mhz(self) -> Hertz { Hertz::::from_hz(self * 1_000_000.0).unwrap() } fn dt(self) -> Hertz { Hertz::::from_hz(1.0 / self).unwrap() } } impl ToHertz for u32 { fn hz(self) -> Hertz { Hertz::::from_hz(self as f32).unwrap() } fn khz(self) -> Hertz { Hertz::::from_hz((self * 1_000) as f32).unwrap() } fn mhz(self) -> Hertz { Hertz::::from_hz((self * 1_000_000) as f32).unwrap() } fn dt(self) -> Hertz { Hertz::::from_hz(1 as f32 / self as f32).unwrap() } } impl ToHertz for i32 { fn hz(self) -> Hertz { Hertz::::from_hz(self as f32).unwrap() } fn khz(self) -> Hertz { Hertz::::from_hz((self * 1_000) as f32).unwrap() } fn mhz(self) -> Hertz { Hertz::::from_hz((self * 1_000_000) as f32).unwrap() } fn dt(self) -> Hertz { Hertz::::from_hz(1 as f32 / self as f32).unwrap() } } impl Hertz { pub fn from_hz(hz: f32) -> Result { if hz > 0.0 { Ok(Hertz(hz)) } else { Err(Errors::NegativeFrequency) } } pub fn from_dt(dt: f32) -> Result { if dt > 0.0 { Ok(Hertz(1.0 / dt)) } else { Err(Errors::NegativeFrequency) } } pub fn hz(self) -> f32 { self.0 } } // ----------------------------------------------- // f64 implementation // ----------------------------------------------- impl ToHertz for f64 { fn hz(self) -> Hertz { Hertz::::from_hz(self).unwrap() } fn khz(self) -> Hertz { Hertz::::from_hz(self * 1_000.0).unwrap() } fn mhz(self) -> Hertz { Hertz::::from_hz(self * 1_000_000.0).unwrap() } fn dt(self) -> Hertz { Hertz::::from_hz(1.0 / self).unwrap() } } impl ToHertz for f32 { fn hz(self) -> Hertz { Hertz::::from_hz(self as f64).unwrap() } fn khz(self) -> Hertz { Hertz::::from_hz(self as f64 * 1_000.0).unwrap() } fn mhz(self) -> Hertz { Hertz::::from_hz(self as f64 * 1_000_000.0).unwrap() } fn dt(self) -> Hertz { Hertz::::from_hz(1.0 / self as f64).unwrap() } } impl ToHertz for u32 { fn hz(self) -> Hertz { Hertz::::from_hz(self as f64).unwrap() } fn khz(self) -> Hertz { Hertz::::from_hz((self * 1_000) as f64).unwrap() } fn mhz(self) -> Hertz { Hertz::::from_hz((self * 1_000_000) as f64).unwrap() } fn dt(self) -> Hertz { Hertz::::from_hz(1 as f64 / self as f64).unwrap() } } impl ToHertz for i32 { fn hz(self) -> Hertz { Hertz::::from_hz(self as f64).unwrap() } fn khz(self) -> Hertz { Hertz::::from_hz((self * 1_000) as f64).unwrap() } fn mhz(self) -> Hertz { Hertz::::from_hz((self * 1_000_000) as f64).unwrap() } fn dt(self) -> Hertz { Hertz::::from_hz(1 as f64 / self as f64).unwrap() } } impl Hertz { pub fn from_hz(hz: f64) -> Result { if hz > 0.0 { Ok(Hertz(hz)) } else { Err(Errors::NegativeFrequency) } } pub fn from_dt(dt: f64) -> Result { if dt > 0.0 { Ok(Hertz(1.0 / dt)) } else { Err(Errors::NegativeFrequency) } } pub fn hz(self) -> f64 { self.0 } } biquad-0.4.2/src/lib.rs000064400000000000000000000311320072674642500130270ustar 00000000000000//! # biquad //! //! `biquad` is a library for creating second order IIR filters for signal processing based on //! [Biquads](https://en.wikipedia.org/wiki/Digital_biquad_filter). Both a //! Direct Form 1 (DF1) and Direct Form 2 Transposed (DF2T) implementation is //! available, where the DF1 is better used when the filter needs retuning //! online, as it has the property to introduce minimal artifacts under retuning, //! while the DF2T is best used for static filters as it has the least //! computational complexity and best numerical stability. //! //! # Examples //! //! ``` //! fn main() { //! use biquad::*; //! //! // Cutoff and sampling frequencies //! let f0 = 10.hz(); //! let fs = 1.khz(); //! //! // Create coefficients for the biquads //! let coeffs = Coefficients::::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F32).unwrap(); //! //! // Create two different biquads //! let mut biquad1 = DirectForm1::::new(coeffs); //! let mut biquad2 = DirectForm2Transposed::::new(coeffs); //! //! let input_vec = vec![0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]; //! let mut output_vec1 = Vec::new(); //! let mut output_vec2 = Vec::new(); //! //! // Run for all the inputs //! for elem in input_vec { //! output_vec1.push(biquad1.run(elem)); //! output_vec2.push(biquad2.run(elem)); //! } //! } //! ``` //! //! # Errors //! //! `Coefficients::from_params(...)` can error if the cutoff frequency does not adhere to the //! [Nyquist Frequency](https://en.wikipedia.org/wiki/Nyquist_frequency), or if the Q value is //! negative. //! //! `Hertz::from_hz(...)` and `Hertz::from_dt(...)` will error if the frequency is negative. //! //! # Panics //! //! `x.hz()`, `x.khz()`, `x.mhz()`, `x.dt()` will panic for `f32`/`f64` if they are negative. //! #![no_std] pub mod coefficients; pub mod frequency; pub use crate::coefficients::*; pub use crate::frequency::*; /// The required functions of a biquad implementation pub trait Biquad { /// A single iteration of a biquad, applying the filtering on the input fn run(&mut self, input: T) -> T; /// Updating of coefficients fn update_coefficients(&mut self, new_coefficients: Coefficients); /// Updating coefficients and returning the old ones. This is useful to avoid deallocating on the audio thread, since /// the `Coefficients` can then be sent to another thread for deallocation. fn replace_coefficients(&mut self, new_coefficients: Coefficients) -> Coefficients; /// Set the internal state of the biquad to 0 without allocation. fn reset_state(&mut self); } /// Possible errors #[derive(Copy, Clone, Debug, PartialEq)] pub enum Errors { OutsideNyquist, NegativeQ, NegativeFrequency, } /// Internal states and coefficients of the Direct Form 1 form #[derive(Copy, Clone, Debug)] pub struct DirectForm1 { y1: T, y2: T, x1: T, x2: T, coeffs: Coefficients, } /// Internal states and coefficients of the Direct Form 2 Transposed form #[derive(Copy, Clone, Debug)] pub struct DirectForm2Transposed { pub s1: T, pub s2: T, coeffs: Coefficients, } impl DirectForm1 { /// Creates a Direct Form 1 biquad from a set of filter coefficients pub fn new(coefficients: Coefficients) -> Self { DirectForm1 { y1: 0.0_f32, y2: 0.0_f32, x1: 0.0_f32, x2: 0.0_f32, coeffs: coefficients, } } } impl Biquad for DirectForm1 { fn run(&mut self, input: f32) -> f32 { let out = self.coeffs.b0 * input + self.coeffs.b1 * self.x1 + self.coeffs.b2 * self.x2 - self.coeffs.a1 * self.y1 - self.coeffs.a2 * self.y2; self.x2 = self.x1; self.x1 = input; self.y2 = self.y1; self.y1 = out; out } fn update_coefficients(&mut self, new_coefficients: Coefficients) { self.coeffs = new_coefficients; } fn replace_coefficients(&mut self, new_coefficients: Coefficients) -> Coefficients { core::mem::replace(&mut self.coeffs, new_coefficients) } fn reset_state(&mut self) { self.x1 = 0.; self.x2 = 0.; self.y1 = 0.; self.y2 = 0.; } } impl DirectForm1 { /// Creates a Direct Form 1 biquad from a set of filter coefficients pub fn new(coefficients: Coefficients) -> Self { DirectForm1 { y1: 0.0_f64, y2: 0.0_f64, x1: 0.0_f64, x2: 0.0_f64, coeffs: coefficients, } } } impl Biquad for DirectForm1 { fn run(&mut self, input: f64) -> f64 { let out = self.coeffs.b0 * input + self.coeffs.b1 * self.x1 + self.coeffs.b2 * self.x2 - self.coeffs.a1 * self.y1 - self.coeffs.a2 * self.y2; self.x2 = self.x1; self.x1 = input; self.y2 = self.y1; self.y1 = out; out } fn update_coefficients(&mut self, new_coefficients: Coefficients) { self.coeffs = new_coefficients; } fn replace_coefficients(&mut self, new_coefficients: Coefficients) -> Coefficients { core::mem::replace(&mut self.coeffs, new_coefficients) } fn reset_state(&mut self) { self.x1 = 0.; self.x2 = 0.; self.y1 = 0.; self.y2 = 0.; } } impl DirectForm2Transposed { /// Creates a Direct Form 2 Transposed biquad from a set of filter coefficients pub fn new(coefficients: Coefficients) -> Self { DirectForm2Transposed { s1: 0.0_f32, s2: 0.0_f32, coeffs: coefficients, } } } impl Biquad for DirectForm2Transposed { fn run(&mut self, input: f32) -> f32 { let out = self.s1 + self.coeffs.b0 * input; self.s1 = self.s2 + self.coeffs.b1 * input - self.coeffs.a1 * out; self.s2 = self.coeffs.b2 * input - self.coeffs.a2 * out; out } fn update_coefficients(&mut self, new_coefficients: Coefficients) { self.coeffs = new_coefficients; } fn replace_coefficients(&mut self, new_coefficients: Coefficients) -> Coefficients { core::mem::replace(&mut self.coeffs, new_coefficients) } fn reset_state(&mut self) { self.s1 = 0.; self.s2 = 0.; } } impl DirectForm2Transposed { /// Creates a Direct Form 2 Transposed biquad from a set of filter coefficients pub fn new(coefficients: Coefficients) -> Self { DirectForm2Transposed { s1: 0.0_f64, s2: 0.0_f64, coeffs: coefficients, } } } impl Biquad for DirectForm2Transposed { fn run(&mut self, input: f64) -> f64 { let out = self.s1 + self.coeffs.b0 * input; self.s1 = self.s2 + self.coeffs.b1 * input - self.coeffs.a1 * out; self.s2 = self.coeffs.b2 * input - self.coeffs.a2 * out; out } fn update_coefficients(&mut self, new_coefficients: Coefficients) { self.coeffs = new_coefficients; } fn replace_coefficients(&mut self, new_coefficients: Coefficients) -> Coefficients { core::mem::replace(&mut self.coeffs, new_coefficients) } fn reset_state(&mut self) { self.s1 = 0.; self.s2 = 0.; } } #[cfg(test)] #[macro_use] extern crate std; #[cfg(test)] mod tests { use crate::*; #[test] fn test_frequency_f32() { let f1 = 10.hz(); let f2 = 10.khz(); let f3 = 10.mhz(); let f4 = 10.dt(); assert_eq!(f1, Hertz::::from_hz(10.).unwrap()); assert_eq!(f2, Hertz::::from_hz(10000.).unwrap()); assert_eq!(f3, Hertz::::from_hz(10000000.).unwrap()); assert_eq!(f4, Hertz::::from_hz(0.1).unwrap()); assert!(f1 < f2); assert!(f3 > f2); assert!(f1 == f1); assert!(f1 != f2); } #[test] fn test_frequency_f64() { let f1 = 10.hz(); let f2 = 10.khz(); let f3 = 10.mhz(); let f4 = 10.dt(); assert_eq!(f1, Hertz::::from_hz(10.).unwrap()); assert_eq!(f2, Hertz::::from_hz(10000.).unwrap()); assert_eq!(f3, Hertz::::from_hz(10000000.).unwrap()); assert_eq!(f4, Hertz::::from_hz(0.1).unwrap()); assert!(f1 < f2); assert!(f3 > f2); assert!(f1 == f1); assert!(f1 != f2); } #[test] #[should_panic] fn test_frequency_panic() { let _f1 = (-10.0).hz(); } #[test] fn test_hertz_from_f32() { assert_eq!( Hertz::::from_dt(1.0).unwrap(), Hertz::::from_hz(1.0).unwrap() ); } #[test] fn test_hertz_from_f64() { assert_eq!( Hertz::::from_dt(1.0).unwrap(), Hertz::::from_hz(1.0).unwrap() ); } #[test] fn test_coefficients_normal_f32() { let f0 = 10.hz(); let fs = 1.khz(); let coeffs = Coefficients::::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F32); match coeffs { Ok(_) => {} Err(_) => { panic!("Coefficients creation failed!"); } } } #[test] fn test_coefficients_normal_f64() { let f0 = 10.hz(); let fs = 1.khz(); let coeffs = Coefficients::::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F64); match coeffs { Ok(_) => {} Err(_) => { panic!("Coefficients creation failed!"); } } } #[test] fn test_coefficients_fail_flipped_frequencies_f32() { let f0 = 10.hz(); let fs = 1.khz(); let coeffs = Coefficients::::from_params(Type::LowPass, f0, fs, Q_BUTTERWORTH_F32); match coeffs { Ok(_) => { panic!("Should not come here"); } Err(e) => { assert_eq!(e, Errors::OutsideNyquist); } } } #[test] fn test_coefficients_fail_flipped_frequencies_f64() { let f0 = 10.hz(); let fs = 1.khz(); let coeffs = Coefficients::::from_params(Type::LowPass, f0, fs, Q_BUTTERWORTH_F64); match coeffs { Ok(_) => { panic!("Should not come here"); } Err(e) => { assert_eq!(e, Errors::OutsideNyquist); } } } #[test] fn test_coefficients_fail_negative_q_f32() { let f0 = 10.hz(); let fs = 1.khz(); let coeffs = Coefficients::::from_params(Type::LowPass, fs, f0, -1.0); match coeffs { Ok(_) => { panic!("Should not come here"); } Err(e) => { assert_eq!(e, Errors::NegativeQ); } } } #[test] fn test_coefficients_fail_negative_q_f64() { let f0 = 10.hz(); let fs = 1.khz(); let coeffs = Coefficients::::from_params(Type::LowPass, fs, f0, -1.0); match coeffs { Ok(_) => { panic!("Should not come here"); } Err(e) => { assert_eq!(e, Errors::NegativeQ); } } } #[test] fn test_biquad_zeros_f32() { use std::vec::Vec; //use std::vec::Vec::*; let f0 = 10.hz(); let fs = 1.khz(); let coeffs = Coefficients::::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F32).unwrap(); let mut biquad1 = DirectForm1::::new(coeffs); let mut biquad2 = DirectForm2Transposed::::new(coeffs); let input_vec = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; let mut output_vec1 = Vec::new(); let mut output_vec2 = Vec::new(); for elem in input_vec { output_vec1.push(biquad1.run(elem)); output_vec2.push(biquad2.run(elem)); } } #[test] fn test_biquad_zeros_f64() { use std::vec::Vec; //use std::vec::Vec::*; let f0 = 10.hz(); let fs = 1.khz(); let coeffs = Coefficients::::from_params(Type::LowPass, fs, f0, Q_BUTTERWORTH_F64).unwrap(); let mut biquad1 = DirectForm1::::new(coeffs); let mut biquad2 = DirectForm2Transposed::::new(coeffs); let input_vec = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; let mut output_vec1 = Vec::new(); let mut output_vec2 = Vec::new(); for elem in input_vec { output_vec1.push(biquad1.run(elem)); output_vec2.push(biquad2.run(elem)); } } }