fmod1 0.1.0

Rust wrapper for FMOD low-level API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
use std;
use num_derive::FromPrimitive;
use crate::{ll, fmod_result, vector, ChannelControl, ChannelGroup,
  ChannelGroupRef, Dsp, DspRef, Delay, Error, Mode, SoundRef, Timeunit};

/// A *weak* handle to a sound playing on a virtual channel.
///
/// If this channel is stolen by the priority system because another sound was
/// played and no other channels were free, all subsequent method calls on this
/// handle will return `Error::ChannelStolen`.
///
/// The handle will also return `Error::InvalidHandle` after the next call to
/// `system.update()` if (non-looping) playback has reached the end of the
/// sound, or if `channel.stop()` is called. Note that resetting the position
/// before calling `system.update()` will *not* prevent the channel handle from
/// being invalidated.
///
/// Note that the channel holds a weak reference to the sound that is playing.
/// If the channel handle is dropped, but the sound is still alive, the channel
/// will continue playing.
#[derive(Clone, Debug, PartialEq)]
pub struct Channel {
  inner     : Inner,
  sound_ref : SoundRef
}

// note this is a weak reference: there is no action when dropped
#[derive(Clone, PartialEq)]
struct Inner (*mut ll::FMOD_CHANNEL);

bitflags!{
  #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
  pub struct Channelmask : u32 {
    const FRONTLEFT     = ll::FMOD_CHANNELMASK_FRONT_LEFT;
    const FRONTRIGHT    = ll::FMOD_CHANNELMASK_FRONT_RIGHT;
    const FRONTCENTER   = ll::FMOD_CHANNELMASK_FRONT_CENTER;
    const LOWFREQUENCY  = ll::FMOD_CHANNELMASK_LOW_FREQUENCY;
    const SURROUNDLEFT  = ll::FMOD_CHANNELMASK_SURROUND_LEFT;
    const SURROUNDRIGHT = ll::FMOD_CHANNELMASK_SURROUND_RIGHT;
    const BACKLEFT      = ll::FMOD_CHANNELMASK_BACK_LEFT;
    const BACKRIGHT     = ll::FMOD_CHANNELMASK_BACK_RIGHT;
    const BACKCENTER    = ll::FMOD_CHANNELMASK_BACK_CENTER;
    const MONO          = ll::FMOD_CHANNELMASK_MONO;
    const STEREO        = ll::FMOD_CHANNELMASK_STEREO;
    const LRC           = ll::FMOD_CHANNELMASK_LRC;
    const QUAD          = ll::FMOD_CHANNELMASK_QUAD;
    const SURROUND      = ll::FMOD_CHANNELMASK_SURROUND;
    const _5POINT1      = ll::FMOD_CHANNELMASK_5POINT1;
    const _5POINT1REARS = ll::FMOD_CHANNELMASK_5POINT1_REARS;
    const _7POINT0      = ll::FMOD_CHANNELMASK_7POINT0;
    const _7POINT1      = ll::FMOD_CHANNELMASK_7POINT1;
  }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, FromPrimitive)]
#[derive(Default)]
pub enum Channelorder {
  #[default]
  Default    = ll::FMOD_CHANNELORDER_FMOD_CHANNELORDER_DEFAULT    as isize,
  Waveformat = ll::FMOD_CHANNELORDER_FMOD_CHANNELORDER_WAVEFORMAT as isize,
  Protools   = ll::FMOD_CHANNELORDER_FMOD_CHANNELORDER_PROTOOLS   as isize,
  Allmono    = ll::FMOD_CHANNELORDER_FMOD_CHANNELORDER_ALLMONO    as isize,
  Allstereo  = ll::FMOD_CHANNELORDER_FMOD_CHANNELORDER_ALLSTEREO  as isize,
  Alsa       = ll::FMOD_CHANNELORDER_FMOD_CHANNELORDER_ALSA       as isize,
  MAX        = ll::FMOD_CHANNELORDER_FMOD_CHANNELORDER_MAX        as isize
}

impl Channel {
  #[inline]
  pub const fn from_raw_parts (raw : *mut ll::FMOD_CHANNEL, sound_ref : SoundRef)
    -> Self
  {
    let inner = Inner (raw);
    Channel { inner, sound_ref }
  }

  /// Sound that the channel was assigned to play
  #[inline]
  pub fn sound_ref (&self) -> SoundRef {
    self.sound_ref.clone()
  }

  /// Retrieves the currently assigned channel group for the channel
  #[inline]
  pub fn get_channel_group (&self) -> Result <ChannelGroupRef, Error> {
    let mut raw = std::ptr::null_mut();
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetChannelGroup (self.inner.0, &mut raw))?;
    }
    let channel_group = ChannelGroup::from_raw_parts (raw, false,
      self.sound_ref.sound.system.clone());
    Ok (ChannelGroupRef { channel_group })
  }

  #[inline]
  pub fn get_frequency (&self) -> Result <f32, Error> {
    let mut frequency = 0.0;
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_GetFrequency (self.inner.0, &mut frequency)
      )?;
    }
    Ok (frequency)
  }

  /// Retrieves the internal channel index for a channel.
  ///
  /// Channel indices are in the range 0 to the `maxchannels` specified at
  /// System creation.
  #[inline]
  pub fn get_index (&self) -> Result <i32, Error> {
    let mut index = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetIndex (self.inner.0, &mut index))?;
    }
    Ok (index)
  }

  #[inline]
  pub fn get_loop_count (&self) -> Result <i32, Error> {
    let mut loopcount = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetLoopCount (self.inner.0, &mut loopcount))?;
    }
    Ok (loopcount)
  }

  #[inline]
  pub fn get_loop_points (&self,
    loopstarttype : Timeunit, loopendtype : Timeunit
  ) -> Result <(u32, u32), Error> {
    let mut loopstart = 0;
    let mut loopend   = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetLoopPoints (self.inner.0,
        &mut loopstart, loopstarttype.bits(),
        &mut loopend, loopendtype.bits())
      )?;
    }
    Ok ((loopstart, loopend))
  }

  #[inline]
  pub fn get_position (&self, timeunit : Timeunit) -> Result <u32, Error> {
    let mut position = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetPosition (self.inner.0,
        &mut position, timeunit.bits())
      )?;
    }
    Ok (position)
  }

  #[inline]
  pub fn get_priority (&self) -> Result <i32, Error> {
    let mut priority = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetPriority (self.inner.0, &mut priority))?;
    }
    Ok (priority)
  }

  #[inline]
  pub fn is_virtual (&self) -> Result <bool, Error> {
    let mut isvirtual = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_IsVirtual (self.inner.0, &mut isvirtual))?;
    }
    Ok (isvirtual != 0)
  }

  #[inline]
  pub fn set_frequency (&mut self, frequency : f32) -> Result <(), Error> {
    unsafe {
      fmod_result!(ll::FMOD_Channel_SetFrequency (self.inner.0, frequency))
    }
  }

  #[inline]
  pub fn set_position (&mut self, position : u32, postype : Timeunit)
    -> Result <(), Error>
  {
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_SetPosition (self.inner.0, position, postype.bits())
      )
    }
  }

}

impl ChannelControl for Channel {
  /// Add a DSP to the DSP chain at the given index. Index must be a position
  /// in the range $[0, numDSPs]$, or else one of the special indices:
  ///
  /// - `DspIndex::Head  == -1` -- head of the chain; always equal to 0
  /// - `DspIndex::Fader == -2` -- built-in fader DSP; initially 0
  /// - `DspIndex::Tail  == -3` -- tail of the chain; equal to $numDSPs-1$
  ///
  /// # Errors
  ///
  /// An `InvalidParam` error will be returned if `index > self.get_num_dsps()`.
  #[inline]
  fn add_dsp (&mut self, index : i32, dsp : &mut Dsp) -> Result <(), Error> {
    unsafe {
      fmod_result!(ll::FMOD_Channel_AddDSP (self.inner.0, index, dsp.raw()))?;
    }
    Ok (())
  }

  #[inline]
  fn add_fade_point (&mut self, dspclock : u64, volume : f32)
    -> Result <(), Error>
  {
    unsafe {
      fmod_result!(ll::FMOD_Channel_AddFadePoint (
        self.inner.0, dspclock, volume))
    }
  }

  #[inline]
  fn get_3d_attributes (&self) -> Result <([f32; 3], [f32; 3]), Error> {
    let mut pos = vector::to_ll ([0.0; 3]);
    let mut vel = vector::to_ll ([0.0; 3]);
    let mut alt_pan_pos = vector::to_ll ([0.0; 3]);  // unimplemented
    unsafe {
      fmod_result!(ll::FMOD_Channel_Get3DAttributes (self.inner.0,
        &mut pos, &mut vel, &mut alt_pan_pos)
      )?;
    }
    Ok ((vector::from_ll (pos), vector::from_ll (vel)))
  }

  #[inline]
  fn get_3d_cone_orientation (&self) -> Result <[f32; 3], Error> {
    let mut orientation = vector::to_ll ([0.0; 3]);
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_Get3DConeOrientation (self.inner.0, &mut orientation)
      )?;
    }
    Ok (vector::from_ll (orientation))
  }

  /// Retrieves the angles that define the `sound_ref` projection cone including the
  /// volume when outside the cone.
  ///
  /// Returns `(insideconeangle, outsideconeangle, outsidevolume)`.
  #[inline]
  fn get_3d_cone_settings (&self) -> Result <(f32, f32, f32), Error> {
    let mut insideconeangle  = 0.0;
    let mut outsideconeangle = 0.0;
    let mut outsidevolume    = 0.0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_Get3DConeSettings (self.inner.0,
        &mut insideconeangle, &mut outsideconeangle, &mut outsidevolume
      ))?;
    }
    Ok ((insideconeangle, outsideconeangle, outsidevolume))
  }

  fn get_3d_custom_rolloff (&self) -> Result <Vec <[f32; 3]>, Error> {
    let mut points = std::ptr::null_mut();
    let mut numpoints = 0;
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_Get3DCustomRolloff (self.inner.0,
          &mut points, &mut numpoints)
      )?;
    }
    debug_assert!(numpoints >= 0);
    #[expect(clippy::cast_sign_loss)]
    let mut curve = Vec::with_capacity (numpoints as usize);
    for i in 0..numpoints as isize {
      let point = unsafe {
        std::ptr::read (points.offset (i) as *const ll::FMOD_VECTOR)
      };
      curve.push (vector::from_ll (point));
    }
    Ok (curve)
  }

  /// Retrieve the settings for the 3D distance filter properties for a Channel
  /// or Channel Group.
  ///
  /// Returns `(custom, customlevel, centerfreq)`.
  #[inline]
  fn get_3d_distance_filter (&self) -> Result <(bool, f32, f32), Error> {
    let mut custom      = 0;
    let mut customlevel = 0.0;
    let mut centerfreq  = 0.0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_Get3DDistanceFilter (self.inner.0,
        &mut custom, &mut customlevel, &mut centerfreq)
      )?;
    }
    let custom = custom != 0;
    Ok ((custom, customlevel, centerfreq))
  }

  #[inline]
  fn get_3d_doppler_level (&self) -> Result <f32, Error> {
    let mut level = 0.0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_Get3DDopplerLevel (self.inner.0, &mut level))?;
    }
    Ok (level)
  }

  /// Retrieves the minimum and maximum audible distance
  #[inline]
  fn get_3d_min_max_distance (&self) -> Result <(f32, f32), Error> {
    let mut mindistance = 0.0;
    let mut maxdistance = 0.0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_Get3DMinMaxDistance (self.inner.0,
        &mut mindistance, &mut maxdistance)
      )?;
    }
    Ok ((mindistance, maxdistance))
  }

  /// Retrieves the occlusion factors.
  ///
  /// Returns `(directocclusion, reverbocclusion)`.
  #[inline]
  fn get_3d_occlusion (&self) -> Result <(f32, f32), Error> {
    let mut directocclusion = 0.0;
    let mut reverbocclusion = 0.0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_Get3DOcclusion (self.inner.0,
        &mut directocclusion, &mut reverbocclusion)
      )?;
    }
    Ok ((directocclusion, reverbocclusion))
  }

  /// Retrieves the spread of a 3D `sound_ref` in speaker space.
  ///
  /// Returns the speaker spread angle.
  #[inline]
  fn get_3d_spread (&self) -> Result <f32, Error> {
    let mut angle = 0.0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_Get3DSpread (self.inner.0, &mut angle))?;
    }
    Ok (angle)
  }

  #[inline]
  fn get_audibility (&self) -> Result <f32, Error> {
    let mut audibility = 0.0;
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_GetAudibility (self.inner.0, &mut audibility)
      )?;
    }
    Ok (audibility)
  }

  #[inline]
  fn get_delay (&self) -> Result <Delay, Error> {
    let mut dspclock_start = 0;
    let mut dspclock_end   = 0;
    let mut stopchannels   = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetDelay (self.inner.0,
        &mut dspclock_start,
        &mut dspclock_end,
        &mut stopchannels
      ))?;
    }
    let stopchannels = stopchannels != 0;
    Ok (Delay { dspclock_start, dspclock_end, stopchannels })
  }

  /// Retrieve the DSP unit at the specified index
  #[inline]
  fn get_dsp (&self, index : i32) -> Result <DspRef, Error> {
    let mut raw = std::ptr::null_mut();
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetDSP (self.inner.0, index, &mut raw))?;
    }
    let dsp =
      Dsp::from_raw_parts (raw, false, self.sound_ref.sound.system.clone());
    Ok (DspRef { dsp })
  }

  /// DSP clock value for the head DSP node
  #[inline]
  fn get_dsp_clock (&self) -> Result <u64, Error> {
    let mut dspclock = 0;
    let parentclock = std::ptr::null_mut();
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_GetDSPClock (self.inner.0, &mut dspclock, parentclock)
      )?;
    }
    Ok (dspclock)
  }

  /// DSP clock value for the tail DSP node
  #[inline]
  fn get_dsp_clock_parent (&self) -> Result <u64, Error> {
    let dspclock = std::ptr::null_mut();
    let mut parentclock = 0;
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_GetDSPClock (self.inner.0, dspclock, &mut parentclock)
      )?;
    }
    Ok (parentclock)
  }

  /// Retrieve the index in the DSP chain of the provided DSP
  #[inline]
  fn get_dsp_index (&self, dsp : &Dsp) -> Result <i32, Error> {
    let mut index = 0;
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_GetDSPIndex (self.inner.0, dsp.raw(), &mut index)
      )?;
    }
    Ok (index)
  }

  #[inline]
  fn get_low_pass_gain (&self) -> Result <f32, Error> {
    let mut gain = 0.0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetLowPassGain (self.inner.0, &mut gain))?;
    }
    Ok (gain)
  }

  #[inline]
  fn get_mode (&self) -> Result <Mode, Error> {
    let mut mode = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetMode (self.inner.0, &mut mode))?;
    }
    Ok (Mode::from_bits (mode).unwrap())
  }

  #[inline]
  fn get_mute (&self) -> Result <bool, Error> {
    let mut mute = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetMute (self.inner.0, &mut mute))?;
    }
    Ok (mute != 0)
  }

  /// Retrieves the number of DSP units in the DSP chain
  #[inline]
  fn get_num_dsps (&self) -> Result <u32, Error> {
    let mut num = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetNumDSPs (self.inner.0, &mut num))?;
    }
    debug_assert!(num >= 0);
    #[expect(clippy::cast_sign_loss)]
    Ok (num as u32)
  }

  #[inline]
  fn get_paused (&self) -> Result <bool, Error> {
    let mut paused = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetPaused (self.inner.0, &mut paused))?;
    }
    Ok (paused != 0)
  }

  /// Retrieves the wet level (or send level) for a particular reverb instance.
  ///
  /// Returns the send level for the signal to the reverb, from 0 (none) to 1.0
  /// (full).
  ///
  /// `instance` -- Index of the particular reverb instance to target, from 0 to
  /// `dsp::REVERB_MAXINSTANCES`.
  #[inline]
  fn get_reverb_properties (&self, instance : i32) -> Result <f32, Error> {
    let mut wet = 0.0;
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_GetReverbProperties (self.inner.0, instance, &mut wet)
      )?;
    }
    Ok (wet)
  }

  #[inline]
  fn get_volume (&self) -> Result <f32, Error> {
    let mut volume = 0.0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_GetVolume (self.inner.0, &mut volume))?;
    }
    Ok (volume)
  }

  #[inline]
  fn is_playing (&self) -> Result <bool, Error> {
    let mut isplaying = 0;
    unsafe {
      fmod_result!(ll::FMOD_Channel_IsPlaying (self.inner.0, &mut isplaying))?;
    }
    Ok (isplaying != 0)
  }

  #[inline]
  fn remove_dsp (&mut self, dsp : &mut Dsp) -> Result <(), Error> {
    unsafe {
      fmod_result!(ll::FMOD_Channel_RemoveDSP (self.inner.0, dsp.raw()))?;
    }
    Ok (())
  }

  #[inline]
  fn set_3d_attributes (&mut self, pos : [f32; 3], vel : [f32; 3])
    -> Result <(), Error>
  {
    let pos = vector::to_ll (pos);
    let vel = vector::to_ll (vel);
    // FMOD1.10: unimplemented
    const ALT_PAN_POS : ll::FMOD_VECTOR = vector::to_ll ([0.0; 3]);
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_Set3DAttributes (self.inner.0, &pos, &vel, &ALT_PAN_POS)
      )?;
    };
    Ok (())
  }

  #[inline]
  fn set_delay (&mut self,
    dspclock_start : u64, dspclock_end : u64, stopchannels : bool
  ) -> Result <(), Error> {
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_SetDelay (self.inner.0, dspclock_start, dspclock_end,
          stopchannels as i32))
    }
  }

  #[inline]
  fn set_fade_point_ramp (&mut self, dspclock : u64, volume : f32)
    -> Result <(), Error>
  {
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_SetFadePointRamp (self.inner.0, dspclock, volume))
    }
  }

  #[inline]
  fn set_mute (&mut self, mute : bool) -> Result <(), Error> {
    unsafe {
      fmod_result!(ll::FMOD_Channel_SetMute (self.inner.0, mute as i32))
    }
  }

  #[inline]
  fn set_paused (&mut self, paused : bool) -> Result <(), Error> {
    unsafe {
      fmod_result!(ll::FMOD_Channel_SetPaused (self.inner.0, paused as i32))
    }
  }

  #[inline]
  fn set_reverb_properties (&mut self, instance : i32, wet : f32)
    -> Result <(), Error>
  {
    unsafe {
      fmod_result!(
        ll::FMOD_Channel_SetReverbProperties (self.inner.0, instance, wet))
    }
  }

  #[inline]
  fn set_volume (&mut self, volume : f32) -> Result <(), Error> {
    unsafe {
      fmod_result!(ll::FMOD_Channel_SetVolume (self.inner.0, volume))
    }
  }

  #[inline]
  fn stop (&mut self) -> Result <(), Error> {
    unsafe {
      fmod_result!(ll::FMOD_Channel_Stop (self.inner.0))
    }
  }

}


impl Default for Channelmask {
  fn default() -> Self {
    Channelmask::empty()
  }
}

impl std::fmt::Debug for Inner {
  fn fmt (&self, f : &mut std::fmt::Formatter) -> std::fmt::Result {
    write!(f, "{:p}", self.0)
  }
}