Class PASharedBufferSampler

java.lang.Object
ddf.minim.UGen
net.paulhertz.pixelaudio.sampler.PASharedBufferSampler
All Implemented Interfaces:
PASampler

public class PASharedBufferSampler extends ddf.minim.UGen implements PASampler
UGen-based sampler that plays multiple PASamplerVoice instances from a single shared mono buffer (channel 0 of a MultiChannelBuffer) which is an array of floating point samples over (-1.0..1.0).

Features:

  • Shared buffer (no duplication)
  • Polyphony with voice pooling
  • Looping (global default + per-voice)
  • ADSR per voice via ADSRParams
  • Oldest-first voice recycling, optional smooth stealing
  • Thread-safe triggering
  • Presets for noise reduction with MixProfile and PASamplerInstrumentPool cycleMixProfile().
Automatically patches to the provided AudioOutput.
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static enum 
    Mix-density normalization profiles for polyphonic sampler output, used to control noise and distortion.
    private static final class 
     

    Nested classes/interfaces inherited from class ddf.minim.UGen

    ddf.minim.UGen.InputType, ddf.minim.UGen.UGenInput
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    private float[]
    Mono source buffer, typically channel 0 from a MultiChannelBuffer.
    private int
    Cached source buffer length in samples.
    protected boolean
    Enables diagnostic voice-trigger logging when true.
    private boolean
    Default looping state for newly triggered voices.
    private float
    Master linear gain applied to mixed output.
    private int
    Maximum number of simultaneous voices.
    private float
    Smoothed mix-normalization gain.
     
    private final ddf.minim.AudioOutput
    Audio output this sampler is patched to.
    private float
    Sample rate of the source buffer in Hz.
    private long
    Absolute sample counter advanced by the audio callback.
    Sample-accurate scheduler for launching sampler voices.
    private boolean
    True to release stolen voices smoothly instead of stopping them immediately.
    private final List<PASamplerVoice>
    Voice pool used for polyphonic sample playback.
    private boolean
    True to wrap source-buffer reads for newly triggered voices.
  • Constructor Summary

    Constructors
    Constructor
    Description
    PASharedBufferSampler(ddf.minim.MultiChannelBuffer multiBuffer, float sampleRate, ddf.minim.AudioOutput out)
    Construct a sampler over a shared MultiChannelBuffer.
    PASharedBufferSampler(ddf.minim.MultiChannelBuffer multiBuffer, float playbackSampleRate, ddf.minim.AudioOutput out, int maxVoices)
    Constructs a sampler over a shared buffer with explicit polyphony.
    PASharedBufferSampler(ddf.minim.MultiChannelBuffer multiBuffer, ddf.minim.AudioOutput out)
    Constructs a sampler and infers playback sample rate from the output.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Clears pending scheduled starts without stopping active voices.
    private int
    computeEventSamples(int samplePos, int sampleLen, ADSRParams env, float pitch)
    Computes the expected rendered duration of a voice in samples.
    int
    Counts voices that are neither active nor releasing.
    void
    Advances to the next mix normalization profile.
    ddf.minim.AudioOutput
     
    Get a free voice, or recycle the oldest active one if at the polyphony limit.
    int
     
    long
    Returns the sampler-local audio-thread sample clock.
    float
     
    float
     
    int
     
     
     
    float
    Returns the current sample rate of this sampler.
    Read-only list of voices for GUI or debugging.
    boolean
     
    boolean
    Returns true if any currently active voice is looping.
    boolean
     
    boolean
    Reports whether new sampler voices wrap source-buffer reads at the buffer end.
    private int[]
    normalizeRange(int samplePos, int sampleLen)
    Validates and clamps a source-buffer playback range.
    int
    play(int samplePos, int sampleLen, float amplitude, ADSRParams env, float pitch, float pan)
    Plays a buffer region immediately.
    void
    Releases all voices through their envelopes.
    void
    setBuffer(float[] buffer)
    Replaces the sampler source buffer.
    void
    setBuffer(float[] buffer, float playbackSampleRate)
    Replaces the sampler source buffer and playback sample rate.
    void
    setGlobalLooping(boolean looping)
    Sets default looping for newly triggered voices.
    void
    setMasterGain(float linear)
    Sets master output gain.
    void
    setMasterGainDb(float db)
    Sets master output gain in decibels.
    void
    setMaxVoices(int maxVoices)
    Change maximum polyphony at runtime.
    void
    Sets the mix normalization profile.
    void
    setPlaybackSampleRate(float newRate)
    Updates the playback sample rate used for reading from the buffer.
    void
    setSmoothSteal(boolean smoothSteal)
    Enable/disable smooth stealing (release envelope) on voice recycle.
    void
    setWrapAround(boolean wrapAround)
    Sets whether newly triggered voices wrap source-buffer reads.
    (package private) static float
    softClipSoftsign(float x, float drive)
    Applies a softsign limiter to reduce overload without hard clipping.
    void
    startAfterDelaySamples(int samplePos, int sampleLen, float amplitude, ADSRParams env, float pitch, float pan, long delaySamples)
    Schedules a sampler voice to start after a sample delay from the current sampler clock.
    void
    startAtSampleTime(int samplePos, int sampleLen, float amplitude, ADSRParams env, float pitch, float pan, long startSample)
    Schedules a sampler voice to start at an absolute sample time.
    void
    Stops all voices immediately.
    protected void
    uGenerate(float[] channels)
    Required by Minim.UGen, core method for audio synthesis called by Minim.
    void
    Convenience: synchronize playback rate with AudioOutput's sample rate.

    Methods inherited from class ddf.minim.UGen

    addAudio, addControl, addControl, addInput, channelCount, channelCountChanged, getLastValues, patch, patch, patch, printInputs, removeInput, sampleRate, sampleRateChanged, setChannelCount, setSampleRate, tick, unpatch, unpatch

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • buffer

      private float[] buffer
      Mono source buffer, typically channel 0 from a MultiChannelBuffer.
    • bufferLen

      private int bufferLen
      Cached source buffer length in samples.
    • playbackSampleRate

      private float playbackSampleRate
      Sample rate of the source buffer in Hz.
    • out

      private final ddf.minim.AudioOutput out
      Audio output this sampler is patched to.
    • voices

      private final List<PASamplerVoice> voices
      Voice pool used for polyphonic sample playback.
    • maxVoices

      private int maxVoices
      Maximum number of simultaneous voices.
    • globalLooping

      private boolean globalLooping
      Default looping state for newly triggered voices.
    • wrapAround

      private boolean wrapAround
      True to wrap source-buffer reads for newly triggered voices.
    • smoothSteal

      private boolean smoothSteal
      True to release stolen voices smoothly instead of stopping them immediately.
    • mixNorm

      private float mixNorm
      Smoothed mix-normalization gain.
    • masterGain

      private volatile float masterGain
      Master linear gain applied to mixed output.
    • DEBUG

      protected boolean DEBUG
      Enables diagnostic voice-trigger logging when true.
    • scheduler

      Sample-accurate scheduler for launching sampler voices.
    • sampleCursor

      private long sampleCursor
      Absolute sample counter advanced by the audio callback.
    • mixProfile

      private volatile PASharedBufferSampler.MixProfile mixProfile
  • Constructor Details

    • PASharedBufferSampler

      public PASharedBufferSampler(ddf.minim.MultiChannelBuffer multiBuffer, float sampleRate, ddf.minim.AudioOutput out)
      Construct a sampler over a shared MultiChannelBuffer. Automatically patches to the provided AudioOutput.
      Parameters:
      multiBuffer - shared source buffer (mono or stereo)
      sampleRate - sample rate of the buffer
      out - target AudioOutput for playback
    • PASharedBufferSampler

      public PASharedBufferSampler(ddf.minim.MultiChannelBuffer multiBuffer, float playbackSampleRate, ddf.minim.AudioOutput out, int maxVoices)
      Constructs a sampler over a shared buffer with explicit polyphony.
      Parameters:
      multiBuffer - shared source buffer
      playbackSampleRate - sample rate of the source buffer in Hz
      out - target AudioOutput for playback
      maxVoices - maximum simultaneous voices
    • PASharedBufferSampler

      public PASharedBufferSampler(ddf.minim.MultiChannelBuffer multiBuffer, ddf.minim.AudioOutput out)
      Constructs a sampler and infers playback sample rate from the output.
      Parameters:
      multiBuffer - shared source buffer
      out - target AudioOutput for playback
  • Method Details

    • play

      public int play(int samplePos, int sampleLen, float amplitude, ADSRParams env, float pitch, float pan)
      Plays a buffer region immediately.

      The requested samplePos and sampleLen are normalized against the current source buffer before a voice is activated. This method starts playback from the calling thread's request as soon as the audio callback next renders this sampler; use startAtSampleTime(int, int, float, ADSRParams, float, float, long) when the launch must align to a specific sampler-clock sample.

      Specified by:
      play in interface PASampler
      Parameters:
      samplePos - source-buffer index to start playback
      sampleLen - requested source-buffer duration in samples
      amplitude - per-voice gain multiplier
      env - ADSR envelope parameters, or null for no voice envelope
      pitch - playback-rate multiplier
      pan - stereo pan position
      Returns:
      computed voice duration in output samples, or 0 if playback could not start
    • startAtSampleTime

      public void startAtSampleTime(int samplePos, int sampleLen, float amplitude, ADSRParams env, float pitch, float pan, long startSample)
      Schedules a sampler voice to start at an absolute sample time.

      startSample is measured on this sampler's local audio-thread clock, returned by getCurrentSampleTime(). The event is enqueued through AudioScheduler and activated inside uGenerate(float[]) when the clock reaches that sample.

      Specified by:
      startAtSampleTime in interface PASampler
      Parameters:
      samplePos - source-buffer index to start playback
      sampleLen - requested source-buffer duration in samples
      amplitude - per-voice gain multiplier
      env - ADSR envelope parameters, or null for no voice envelope
      pitch - playback-rate multiplier
      pan - stereo pan position
      startSample - absolute sample time on this sampler's local clock
    • startAfterDelaySamples

      public void startAfterDelaySamples(int samplePos, int sampleLen, float amplitude, ADSRParams env, float pitch, float pan, long delaySamples)
      Schedules a sampler voice to start after a sample delay from the current sampler clock.
      Specified by:
      startAfterDelaySamples in interface PASampler
      Parameters:
      samplePos - source-buffer index to start playback
      sampleLen - requested source-buffer duration in samples
      amplitude - per-voice gain multiplier
      env - ADSR envelope parameters, or null for no voice envelope
      pitch - playback-rate multiplier
      pan - stereo pan position
      delaySamples - delay from the current sampler clock, clamped to 0 or greater
    • getCurrentSampleTime

      public long getCurrentSampleTime()
      Returns the sampler-local audio-thread sample clock.

      The clock advances once for each uGenerate(float[]) call. It is suitable for scheduling future events on this sampler; applications that need multiple engines to align should choose one shared transport clock and convert all event times to that same absolute sample domain.

      Specified by:
      getCurrentSampleTime in interface PASampler
      Returns:
      current sampler-local sample cursor
    • clearScheduled

      public void clearScheduled()
      Clears pending scheduled starts without stopping active voices.
      Specified by:
      clearScheduled in interface PASampler
    • normalizeRange

      private int[] normalizeRange(int samplePos, int sampleLen)
      Validates and clamps a source-buffer playback range.
      Parameters:
      samplePos - requested start position in the source buffer
      sampleLen - requested playback length in source-buffer samples
      Returns:
      a two-element array where index 0 is the clamped start position and index 1 is the clamped length, or null when the request cannot produce playback
    • computeEventSamples

      private int computeEventSamples(int samplePos, int sampleLen, ADSRParams env, float pitch)
      Computes the expected rendered duration of a voice in samples.
      Parameters:
      samplePos - normalized source-buffer start position
      sampleLen - normalized source-buffer playback length
      env - ADSR envelope parameters
      pitch - playback-rate multiplier
      Returns:
      expected voice duration in samples, including release where applicable
    • getAvailableVoice

      private PASamplerVoice getAvailableVoice()
      Get a free voice, or recycle the oldest active one if at the polyphony limit.
    • uGenerate

      protected void uGenerate(float[] channels)
      Required by Minim.UGen, core method for audio synthesis called by Minim.

      Scheduled point events are processed first so voices that start at the current sampleCursor contribute to this output sample. The method then mixes active voices, applies constant-power panning, density normalization, and soft limiting, and finally advances the sampler-local clock by one sample.

      Specified by:
      uGenerate in class ddf.minim.UGen
    • softClipSoftsign

      static float softClipSoftsign(float x, float drive)
      Applies a softsign limiter to reduce overload without hard clipping.

      The input is first scaled by drive, then mapped through y / (1 + abs(y)). Small values stay close to linear, while large positive or negative values asymptotically approach -1 or 1.

      A drive value of 1.0 is basically neutral. Typical active values are in the range 1.2 to 1.6. 2.0 to 3.3 provides obvious compress, above 4.0 probably distorts. MixProfile provides :TRANSPARENT: 1.35, BALANCED: 1.60, PROTECTIVE: 1.25.

      Parameters:
      x - input sample
      drive - pre-limiter gain controlling how quickly the curve saturates
      Returns:
      softly limited sample
    • stopAll

      public void stopAll()
      Description copied from interface: PASampler
      Stops all voices immediately.
      Specified by:
      stopAll in interface PASampler
    • releaseAll

      public void releaseAll()
      Description copied from interface: PASampler
      Releases all voices through their envelopes.
      Specified by:
      releaseAll in interface PASampler
    • isLooping

      public boolean isLooping()
      Description copied from interface: PASampler
      Returns true if any currently active voice is looping.
      Specified by:
      isLooping in interface PASampler
      Returns:
      true if one or more voices are looping
    • setGlobalLooping

      public void setGlobalLooping(boolean looping)
      Sets default looping for newly triggered voices.
      Parameters:
      looping - true to loop newly triggered voices
    • isGlobalLooping

      public boolean isGlobalLooping()
      Returns:
      true when newly triggered voices loop by default
    • setWrapAround

      public void setWrapAround(boolean wrapAround)
      Sets whether newly triggered voices wrap source-buffer reads.
      Specified by:
      setWrapAround in interface PASampler
      Parameters:
      wrapAround - true to wrap reads that pass the end of the source buffer
    • isWrapAround

      public boolean isWrapAround()
      Description copied from interface: PASampler
      Reports whether new sampler voices wrap source-buffer reads at the buffer end.
      Specified by:
      isWrapAround in interface PASampler
      Returns:
      true when newly triggered voices wrap source-buffer reads
    • setSmoothSteal

      public void setSmoothSteal(boolean smoothSteal)
      Enable/disable smooth stealing (release envelope) on voice recycle.
      Parameters:
      smoothSteal - true to release stolen voices smoothly
    • isSmoothSteal

      public boolean isSmoothSteal()
      Returns:
      true when stolen voices release smoothly
    • setMaxVoices

      public void setMaxVoices(int maxVoices)
      Change maximum polyphony at runtime.
      Parameters:
      maxVoices - maximum simultaneous voices
    • getMaxVoices

      public int getMaxVoices()
      Returns:
      maximum simultaneous voices
    • getVoices

      public List<PASamplerVoice> getVoices()
      Read-only list of voices for GUI or debugging.
      Returns:
      unmodifiable voice list
    • setMasterGain

      public void setMasterGain(float linear)
      Sets master output gain.
      Parameters:
      linear - linear gain value
    • getMasterGain

      public float getMasterGain()
      Returns:
      master output gain as a linear value
    • setMasterGainDb

      public void setMasterGainDb(float db)
      Sets master output gain in decibels.
      Parameters:
      db - gain in decibels
    • getMasterGainDb

      public float getMasterGainDb()
      Returns:
      master output gain in decibels
    • setBuffer

      public void setBuffer(float[] buffer)
      Replaces the sampler source buffer.
      Specified by:
      setBuffer in interface PASampler
      Parameters:
      buffer - mono source sample buffer
    • setBuffer

      public void setBuffer(float[] buffer, float playbackSampleRate)
      Replaces the sampler source buffer and playback sample rate.
      Specified by:
      setBuffer in interface PASampler
      Parameters:
      buffer - mono source sample buffer
      playbackSampleRate - sample rate of the source buffer in Hz
    • countAvailableVoices

      public int countAvailableVoices()
      Counts voices that are neither active nor releasing.
      Returns:
      available voice count
    • setMixProfile

      public void setMixProfile(PASharedBufferSampler.MixProfile profile)
      Sets the mix normalization profile.
      Parameters:
      profile - mix profile to apply
    • getMixProfile

      public PASharedBufferSampler.MixProfile getMixProfile()
      Returns:
      active mix normalization profile
    • getMixProfileName

      public String getMixProfileName()
      Returns:
      active mix profile name
    • cycleMixProfile

      public void cycleMixProfile()
      Advances to the next mix normalization profile.
    • getPlaybackSampleRate

      public float getPlaybackSampleRate()
      Returns the current sample rate of this sampler.
      Returns:
      playback sample rate in Hz
    • setPlaybackSampleRate

      public void setPlaybackSampleRate(float newRate)
      Updates the playback sample rate used for reading from the buffer. Does not affect Minim's UGen sample rate.
      Specified by:
      setPlaybackSampleRate in interface PASampler
      Parameters:
      newRate - playback sample rate in Hz
    • updatePlaybackRateFromOutput

      public void updatePlaybackRateFromOutput()
      Convenience: synchronize playback rate with AudioOutput's sample rate. Useful if you want playback speed tied to system rate.
    • getBufferLength

      public int getBufferLength()
      Returns:
      source buffer length in samples
    • getAudioOutput

      public ddf.minim.AudioOutput getAudioOutput()
      Returns:
      target audio output