Crate fmod

Source
Expand description

fmod-oxide Safe rust bindings to the FMOD sound engine. This crate tries to be as rusty and low-cost as possible, without compromising on any APIs. Certain APIs, such as loading banks from a pointer, are marked as unsafe, but are still available for use.

Supports FMOD versions >2.0.2.28 and >2.0.3.07, and Windows/Linux/MacOS/HTML5 platforms.

Any newer patch-level FMOD versions should compile but might have missing features.

§Using this crate

Due to licensing restrictions this crate can’t bundle FMOD, so you’ll need to download a copy of FMOD yourself.

Make sure to download from FMOD Engine specifically. Download page screenshot

After downloading FMOD, you have to tell this crate where FMOD is located. If you’re on Windows and used the FMOD installer, you don’t have to worry about this.

The easiest way is to create a cargo config in your project’s root.

# `.cargo/config.toml`

[env]
FMOD_SYS_FMOD_DIRECTORY = { value = "<absolute install path here>" }

You can also specify a relative install path like so:

# `.cargo/config.toml`

[env]
FMOD_SYS_FMOD_DIRECTORY = { value = "<install path here>", relative = true }

(not recommended because rust-analyzer won’t know this) Alternatively, you can specify FMOD_SYS_FMOD_DIRECTORY when building your project:

FMOD_SYS_FMOD_DIRECTORY=<path> cargo run

§Cross compilation

This crate supports cross compilation and will look for a target-specific FMOD install.

The logic is quite basic at the moment, but it’ll check if <fmod install dir>/<target os> exists and use that.

If no target specific directory was found, it’ll default to <fmod install dir>

§Using with webassembly

Currently only wasm32-unknown-emscripten works well. wasm32-unknown-unknown also works in some capacity but you have to essentially reimplement parts of libc and emscripten.

Unfortunately wasm-bindgen doesn’t work without patches right now, so your milage may vary

The setup is roughly the same, except you’ll need to add some arguments to EMCC_FLAGS.

You can do this by editing .cargo/config.toml:

# `.cargo/config.toml`

[env]
EMCC_CFLAGS="-s EXPORTED_RUNTIME_METHODS=ccall,cwrap,setValue,getValue" # FMOD requires this

If you’re using wasm32-unknown-unknown, you’ll additionally need to add this until this issue is closed.

# `.cargo/config.toml`

[build]
rustflags="-Zwasm-c-abi=spec"

See web-examples/emscripten for a more detailed example.

§Memory management & Copy types

All FMOD objects are Copy, Clone, Send and Sync because it’s possible to have multiple references to the same object. (e.g. loading a bank and then retrieving it by its path) There are a lot of use-cases where you may want to fetch something (like a bank) and never use it again. Implementing Drop to automatically release things would go against that particular use-case, so this crate opts to have manual release() methods instead.

This crate does not currently guard against use-after-frees, however using most of FMOD’s types (especially FMOD Studio’s types) after calling release() is safe. I’m still not 100% sure of what is and isn’t safe and I’m actively trying to test this.

§String types

fmod-oxide aims to be as zero-cost as possible, and as such, it uses UTF-8 C strings from the lanyard crate as its string type. This means that all FMOD functions take a &Utf8CStr instead of a &str or &CStr. &Utf8CStr is pretty cheap to construct (and can even be done statically with the c! macro), so this should not be a problem

When FMOD returns a string, it will always return a Utf8CString (the owned version of Utf8CStr) because it’s difficult to encode lifetime requirements of FMOD strings.

This applies to structs like fmod::studio::AdvancedSettings which store C strings. Converting structs like AdvancedSettings to their FFI equivalents is done by reference as to not pass ownership of the string to FMOD

§Basic example

// System creation is unsafe and must be performed prior to any other FMOD operations.
let mut builder = unsafe { fmod::studio::SystemBuilder::new() }?;
let system = builder.build()?;

// Load a bank
let bank = system.load_bank_file("path/to/bank.bank", fmod::studio::LoadBankFlags::NORMAL)?;
// Query all events in the bank
for event in bank.get_event_list().unwrap() {
    println!("Event: {}", event.get_path()?);
}

// Releasing Systems is unsafe because it cannot be called concurrently, and all FMOD objects are rendered invalid.
unsafe { system.release() };

§Feature flags

  • thread-unsafe — Disable Send + Sync impls for FMOD’s types, making FMOD’s thread-unsafe API safer
  • studio (enabled by default) — Enables FMOD’s Studio API

Re-exports§

pub use fmod_sys as sys;
pub use core::effects::*;
pub use lanyard::*;

Modules§

core
The low-level FMOD core API.
coverageNowhere
How much of FMOD’s API fmod-oxide covers.
debug
Low level control over FMOD’s debug logging.
effects
file
Low level control over FMOD’s filesystem access.
memory
Low level control over how FMOD allocates memory.
studiostudio
The FMOD Studio API.
thread
Low level control over FMOD’s threads.

Structs§

AdvancedSettings
Advanced configuration settings.
AsyncCancelInfo
Information about cancelling a asynchronous file operation.
AsyncReadInfo
Information about a single asynchronous file operation.
AttenuationRange
Attenuation range parameter data structure.
Attributes3D
Structure describing a position, velocity and orientation.
Attributes3DMulti
3D attributes data structure for multiple listeners.
Channel
A source of audio signal that connects to the ChannelGroup mixing hierarchy.
ChannelControl
An interface that represents the shared APIs between Channel and ChannelGroup.
ChannelGroup
A submix in the mixing hierarchy akin to a bus that can contain both Channel and ChannelGroup objects.
ChannelMask
Flags that describe the speakers present in a given signal.
CpuUsage
Performance information for Core API functionality.
DriverState
Flags that provide additional information about a particular driver.
Dsp
A digital signal processor is one node within a graph that transforms input audio signals into an output stream.
DspAttributes3D
3D attributes data structure.
DspConnection
An interface that manages Digital Signal Processor (DSP) connections
DspMeteringInfo
DSP metering info.
DspParameterDescription
Base structure for DSP parameter descriptions.
DynamicResponsefmod_2_3
Dynamic response data structure.
ErrorCallbackInfo
Information describing an error that has occurred.
Fft
FFT parameter data structure.
FileBuffer
A mutable file buffer.
FloatMapping
Structure to define a mapping for a DSP unit’s float parameter.
Geometry
An interface that allows the setup and modification of geometry for occlusion.
Guid
Structure describing a globally unique identifier.
InitFlags
Configuration flags used when initializing the System object.
Mode
[Sound] description bitfields.
OverallGain
Overall gain parameter data structure.
PiecewiseLinearMapping
Structure to define a piecewise linear mapping.
Reverb3D
An interface that manages virtual 3D reverb spheres.
ReverbProperties
Structure defining a reverb environment.
Sidechain
Side chain parameter data structure.
Sound
Container for sample data that can be played on a Channel.
SoundBuilder
A builder for creating a Sound.
SoundGroup
An interface that manages Sound Groups.
SoundLock
A locked region of sound data.
SyncPoint
Named marker for a given point in time.
System
Management object from which all resources are created and played.
SystemBuilder
A builder for creating and initializing a System.
SystemCallbackMask
Tag
Tag data / metadata description.
ThreadAffinity
Bitfield for specifying the CPU core a given thread runs on.
Vector
Structure describing a point in 3D space.

Enums§

ChannelControlType
Enum used to distinguish between Channel and ChannelGroup in the ChannelControl callback.
ChannelOrder
Speaker ordering for multi-channel signals.
DspConnectionType
List of connection types between two DSP units.
DspParameterDataType
Data parameter types.
DspParameterType
DSP parameter types.
DspType
DSP types.
Error
An error that FMOD (or this crate) might return.
FloatMappingType
DSP float parameter mappings.
Instance
Identifier used to represent the different types of instance in the error callback.
OpenState
These values describe what state a sound is in after FMOD_NONBLOCKING has been used to open it.
OutputType
Built-in output types that can be used to run the mixer.
PluginType
Types of plug-in used to extend functionality.
PortType
Port types available for routing audio.
Resampler
List of interpolation types used for resampling.
SoundFormat
These definitions describe the native format of the hardware or software buffer that will be used.
SoundGroupBehavior
Values specifying behavior when a sound group’s max audible value is exceeded.
SoundType
Recognized audio formats that can be loaded into a Sound.
Speaker
Assigns an enumeration for a speaker index.
SpeakerMode
Speaker mode types.
TagData
List of tag data / metadata types.
TagType
List of tag data / metadata types that could be stored within a sound. These include id3 tags, metadata from netstreams and vorbis/asf data.
ThreadType
Named constants for threads created at runtime.
TimeUnit
Time types used for position or length.

Constants§

BUILD_NUMBER
The FMOD build number.
MAX_CHANNEL_WIDTH
Maximum number of channels per sample of audio supported by audio files, buffers, connections and Dsps.
MAX_LISTENERS
Maximum number of listeners supported.
MAX_REVERB_INSTANCES
The maximum number of global reverb instances.
MAX_SYSTEMS
Maximum number of System objects allowed.
VERSION
Current FMOD version number.

Traits§

ChannelControlCallback
Trait for this particular FMOD callback.
DspCallback
Trait for this particular FMOD callback.
FileSystem
The base trait for all filesystems.
FileSystemAsync
An async filesystem.
FileSystemSync
A synchronous filesystem.
NonBlockCallback
Callback to be called when a sound has finished loading, or a non blocking seek is occuring.
PcmCallback
Capture or provide sound data as it is decoded.
ReadableParameter
Trait for types that can be read from DSP parameters.
ReadableParameterIndex
Trait for types that can be turned into a readable parameter index.
RolloffCallback
Trait for this particular FMOD callback.
SystemCallback
Trait for this particular FMOD callback.
WritableParameter
Trait for types that can be written to DSP parameters.
WritableParameterIndex
Trait for types that can be turned into a writable parameter index.

Type Aliases§

Result
Shorthand for std::result::Result<T, Error>