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

编辑推荐精选

Keevx

Keevx

AI数字人视频创作平台

Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。

即梦AI

即梦AI

一站式AI创作平台

提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作

扣子-AI办公

扣子-AI办公

AI办公助手,复杂任务高效处理

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

TRAE编程

TRAE编程

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

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

AI工具TraeAI IDE协作生产力转型热门
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

下拉加载更多