fundsp

fundsp

Rust音频DSP库 提供函数式合成和信号流分析

FunDSP是一个Rust音频数字信号处理库,专注于音频处理和合成。该库提供内联图形表示法描述音频处理网络,利用Rust的零成本抽象表达网络结构。FunDSP的信号流系统可为线性网络确定分析频率响应。库中包含音频组件、数学函数、实用工具和程序生成工具,适用于游戏音频处理、教育、音乐制作和DSP算法原型设计。

FunDSP数字信号处理音频处理音频合成RustGithub开源项目

FunDSP

Actions Status crates.io License

Audio Processing and Synthesis Library for Rust

FunDSP is an audio DSP (digital signal processing) library for audio processing and synthesis.

FunDSP features a powerful inline graph notation for describing audio processing networks. The notation taps into composable, zero-cost abstractions that express the structure of audio networks as Rust types.

Another innovative feature of FunDSP is its signal flow system, which can determine analytic frequency responses for any linear network.

FunDSP comes with a combinator environment containing a suite of audio components, math and utility functions and procedural generation tools.

Uses

  • Audio processing and synthesis for games and applications
  • Education
  • Music making
  • Sound hacking and audio golfing
  • Prototyping of DSP algorithms

Rust Audio Discord

To discuss FunDSP and other topics, come hang out with us at the Rust Audio Discord.

Related Projects

bevy_fundsp integrates FunDSP into the Bevy game engine.

midi_fundsp enables the easy creation of live synthesizer software using FunDSP for synthesis.

quartz is a visual programming and DSP playground with releases for Linux, Mac and Windows.

Installation

Add fundsp to your Cargo.toml as a dependency.

[dependencies] fundsp = "0.18.2"

The files feature is enabled by default. It adds support for loading of audio files into Wave objects via the Symphonia crate.

no_std Support

FunDSP supports no_std environments. To enable no_std, disable the feature std, which is enabled by default. The alloc crate is still needed for components that allocate memory.

Audio file reading and writing is not available in no_std.

[dependencies] fundsp = { version = "0.18.2", default-features = false }

Graph Notation

FunDSP Composable Graph Notation expresses audio networks in algebraic form, using graph operators. It was developed together with the functional environment to minimize the number of typed characters needed to accomplish common audio tasks.

Many common algorithms can be expressed in a natural form conducive to understanding. For example, an FM oscillator can be written simply (for some f and m) as:

sine_hz(f) * f * m + f >> sine()

The above expression defines an audio graph that is compiled into a stack allocated, inlined form using the powerful generic abstractions built into Rust. Connectivity errors are detected during compilation, saving development time.

Audio DSP Becomes a First-Class Citizen

With no macros needed, the FunDSP graph notation integrates audio DSP tightly into the Rust programming language as a first-class citizen. Native Rust operator precedences work in harmony with the notation, minimizing the number of parentheses needed.

FunDSP graph expressions offer even more economy in being generic over channel arities, which are encoded at the type level. A mono network can be expressed as a stereo network simply by replacing its mono generators and filters with stereo ones, the graph notation remaining the same.

Basics

Component Systems

There are two parallel component systems: the static AudioNode and the dynamic AudioUnit.


TraitDispatchAllocation StrategyConnectivity
AudioNodestatic, inlinedstackinput and output arity fixed at compile time
AudioUnitdynamic, object safeheapinput and output arity fixed after construction

All AudioNode and AudioUnit components use 32-bit floating point samples (f32).

The main property of a component in either system is that it is a processing node in a graph with a specific number of input and output connections, called its arity. Audio and control signals flow through input and output connections.

Both systems operate on signals synchronously as an infinite stream. The stream can be rewound to the start at any time using the reset method.

AudioNodes can be stack allocated for the most part. Some nodes may use the heap for audio buffers and the like.

The allocate method preallocates all needed memory. It should be called last before sending something into a real-time context. This is done automatically in the Net and Sequencer frontends.

The purpose of the AudioUnit system is to grant more flexibility in dynamic situations: decisions about input and output arities and contents can be deferred to runtime.

Conversions

AudioNodes are converted to the AudioUnit system using the wrapper type An, which implements AudioUnit. Opcodes in the preludes return nodes already wrapped.

AudioUnits can in turn be converted to AudioNode with the wrapper unit. In this case, the input and output arities must be provided as type-level constants U0, U1, ..., for example:

use fundsp::hacker32::*; // The number of inputs is zero and the number of outputs is one. let type_erased: An<Unit<U0, U1>> = unit::<U0, U1>(Box::new(white() >> lowpass_hz(5000.0, 1.0) >> highpass_hz(1000.0, 1.0)));

Processing

Processing samples is easy in both AudioNode and AudioUnit systems. The tick method is for processing single sample frames, while the process method processes whole blocks.

If maximum speed is important, then it is a good idea to use block processing, as it reduces function calling, processing setup and dynamic network overhead, and enables explicit SIMD support.

Mono samples can be retrieved with get_mono and filter_mono methods. The get_mono method returns the next sample from a generator that has no inputs and one or two outputs, while the filter_mono method filters the next sample from a node that has one input and one output:

let out_sample = node.get_mono(); let out_sample = node.filter_mono(sample);

Stereo samples can be retrieved with get_stereo and filter_stereo methods. The get_stereo method returns the next stereo sample pair from a generator that has no inputs and one or two outputs, while the filter_stereo method filters the next sample from a node that has two inputs and two outputs.

let (out_left_sample, out_right_sample) = node.get_stereo(); let (out_left_sample, out_right_sample) = node.filter_stereo(left_sample, right_sample);

Block Processing

The buffer module contains buffers for block processing. The buffers contain 32-bit float samples. There are two types of owned buffers: the static BufferArray and the dynamic BufferVec.

Buffers are always 64 samples long (MAX_BUFFER_SIZE), have an arbitrary number of channels, and are explicitly SIMD accelerated with the type f32x8 from the wide crate. The samples are laid out noninterleaved in a flat array.

BufferArray is an audio buffer backed by an array. The number of channels is a generic parameter which must be known at compile time. Using this buffer type it is possible to do block processing without allocating heap memory.

BufferVec is an audio buffer backed by a dynamic vector. The buffer is heap allocated. The number of channels can be decided at runtime.

use fundsp::hacker::*; // Create a stereo buffer on the stack. let mut buffer = BufferArray::<U2>::new(); // Declare stereo noise. let mut node = noise() | noise(); // Process 50 samples into the buffer. There are no inputs, so we can borrow an empty buffer. node.process(50, &BufferRef::empty(), &mut buffer.buffer_mut()); // Create another stereo buffer, this one on the heap. let mut filtered = BufferVec::new(2); // Declare stereo filter. let mut filter = lowpole_hz(3000.0) | lowpole_hz(3000.0); // Filter the 50 noise samples. filter.process(50, &buffer.buffer_ref(), &mut filtered.buffer_mut());

To call process automatically behind the scenes, use the BlockRateAdapter adapter component. However, it works only with generators, which are components with no inputs.

To access f32 values in a buffer, use methods with the f32 suffix, for example, at_f32 or channel_f32.

Sample Rate Independence

Of the signals flowing in graphs, some contain audio while others are controls of different kinds.

With control signals and parameters in general, we prefer to use natural units like Hz and seconds. It is useful to keep parameters independent of the sample rate, which we can then adjust as we like.

In addition to sample rate adjustments, natural units enable support for selective oversampling (with the oversample component) in nested sections that are easy to configure and modify.

Some low-level components ignore the sample rate by design, such as the single sample delay tick.

The default sample rate is 44.1 kHz. In both systems, the sample rate can be set for component A, and any children it may have, via A.set_sample_rate(sample_rate).

Audio Processing Environment

FunDSP preludes define convenient combinator environments for audio processing.

There are three name-level compatible versions of the prelude.

The default environment (fundsp::prelude) offers a generic interface.

The 64-bit hacker environment (fundsp::hacker) for audio hacking uses 64-bit internal state for components to maximize audio quality.

The 32-bit hacker environment (fundsp::hacker32) uses 32-bit internal state for components. It aims to offer maximum processing speed.

An application interfacing fundsp can mix and match preludes as needed. The aims of the environments are:

  • Minimize the number of characters needed to type to express an idiom.
  • Keep the syntax clean so that a subset of the hacker environment can be parsed straightforwardly as a high-level DSL for quick prototyping.
  • Make the syntax usable even to people with no prior exposure to programming.

Deterministic Pseudorandom Phase

FunDSP uses a deterministic pseudorandom phase system for audio generators. Generator phases are seeded from network structure and node location.

Thus, two identical networks sound identical separately but different when combined. This means that noise() | noise() is a stereo noise source, for example.

Pseudorandom phase is an attempt to decorrelate different channels of audio. It is also used to pick sample points for envelopes, contributing to a "warmer" sound.

Operators

Custom operators are available for combining audio components inline. In order of precedence, from highest to lowest:


ExpressionMeaningInputsOutputsNotes
-Anegate AaaNegates any number of outputs, even zero.
!Athru Aasame as inputsPasses through extra inputs.
A * Bmultiply A with Ba + ba = bAka amplification, or ring modulation when both are audio signals. Number of outputs in A and B must match.
A * constantmultiply AaaBroadcasts constant. Same applies to constant * A.
A + Bsum A and Ba + ba = bAka mixing. Number of outputs in A and B must match.
A + constantadd to AaaBroadcasts constant. Same applies to constant + A.
A - Bdifference of A and Ba + ba = bNumber of outputs in A and B must match.
A - constantsubtract from AaaBroadcasts constant. Same applies to constant - A.
A >> Bpipe A to BabAka chaining. Number of outputs in A must match number of inputs in B.
A & Bbus A and Ba = ba = bSum A and B. A and B must have identical connectivity.
A ^ Bbranch input to A and B in parallela = ba + bNumber of inputs in A and B must match.
A | Bstack A and B in parallela + ba + bConcatenates A and B inputs and outputs.

In the table, constant denotes an f32 value.

All operators are associative, except the left associative -.

An alternative to some operators are functions available in the preludes. Some of them have multiple combination versions; these work only for multiples of the same type of node, with statically (at compile time) set number of nodes.

The nodes are allocated inline in all functions, as are any inner buffers needed for block processing.

Operator FormFunction FormMultiple Combination Forms
!Athru(A)-
A * Bproduct(A, B)-
A + Bsum(A, B)sumi, sumf
A >> Bpipe(A, B)pipei, pipef
A & Bbus(A, B)busi, busf
A ^ Bbranch(A, B)branchi, branchf
A | Bstack(A, B)stacki, stackf

Operators Diagram

Each cyan dot in the diagram above can contain an arbitrary number of channels, including zero.

In the AudioNode system the number of channels is determined statically, at compile time, while in the AudioUnit system (using Net) the number of channels can be decided at runtime.

Broadcasting

Arithmetic operators are applied to outputs channelwise.

Arithmetic between two components never broadcasts channels: channel arities have to match always.

Direct arithmetic with f32 values, however, broadcasts to an arbitrary number of channels.

The negation operator broadcasts also: -A is equivalent with (0.0 - A).

For example, A * constant(2.0) and A >> mul(2.0) are equivalent and expect A to have one output. On the other hand, A * 2.0 works with any A, even with zero outputs.

Thru

The thru (!) operator is syntactic sugar for chaining filters with similar connectivity.

It adjusts output arity to match input arity and passes through any missing outputs to the next node. The missing outputs are parameters to the filter.

For example, while lowpass() is a 2nd order lowpass filter, !lowpass() >> lowpass() is a steeper 4th order lowpass filter with identical connectivity.

The thru operator is also available as a function: thru(A) is equivalent with !A.

Generators, Filters and Sinks

Components can be broadly classified into generators, filters and sinks. Generators have only outputs, while filters have both inputs and outputs.

Sinks are components with no

编辑推荐精选

扣子-AI办公

扣子-AI办公

职场AI,就用扣子

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成AI工具AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机AI图像热门
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

下拉加载更多