f@5: /*
f@5:
f@16: Copyright (C) 2002 James McCartney.
f@5: Copyright (C) 2016 Queen Mary University of London
f@16: Author: Fiore Martin, based on Supercollider's (http://supercollider.github.io) TGrains code and Ross Bencina's "Implementing Real-Time Granular Synthesis"
f@5:
f@5: This file is part of Collidoscope.
f@5:
f@5: Collidoscope is free software: you can redistribute it and/or modify
f@5: it under the terms of the GNU General Public License as published by
f@5: the Free Software Foundation, either version 3 of the License, or
f@5: (at your option) any later version.
f@5:
f@5: This program is distributed in the hope that it will be useful,
f@5: but WITHOUT ANY WARRANTY; without even the implied warranty of
f@5: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
f@5: GNU General Public License for more details.
f@5:
f@5: You should have received a copy of the GNU General Public License
f@5: along with this program. If not, see .
f@5: */
f@5:
f@0: #pragma once
f@0:
f@0: #include
f@0: #include
f@0:
f@0: #include "EnvASR.h"
f@0:
f@0:
f@0: namespace collidoscope {
f@0:
f@0: using std::size_t;
f@0:
f@3: /**
f@3: * The very core of the Collidoscope audio engine: the granular synthesizer.
f@16: * Based on SuperCollider's TGrains and Ross Bencina's "Implementing Real-Time Granular Synthesis"
f@3: *
f@3: * It implements Collidoscope's selection-based approach to granular synthesis.
f@3: * A grain is basically a selection of a recorded sample of audio.
f@16: * Grains are played in a loop: they are re-triggered each time they reach the end of the selection.
f@16: * However, if the duration coefficient is greater than one, a new grain is re-triggered before the previous one is done,
f@16: * the grains start to overlap with each other and create the typical eerie sound of grnular synthesis.
f@3: * Also every time a new grain is triggered, it is offset of a few samples from the initial position to make the timbre more interesting.
f@3: *
f@3: *
f@3: * PGranular uses a linear ASR envelope with 10 milliseconds attack and 50 milliseconds release.
f@3: *
f@3: * Note that PGranular is header based and only depends on std library and on "EnvASR.h" (also header based).
f@3: * This means you can embedd it in two your project just by copying these two files over.
f@3: *
f@3: * Template arguments:
f@3: * T: type of the audio samples (normally float or double)
f@3: * RandOffsetFunc: type of the callable passed as argument to the contructor
f@3: * TriggerCallbackFunc: type of the callable passed as argument to the contructor
f@3: *
f@3: */
f@0: template
f@0: class PGranular
f@0: {
f@0:
f@0: public:
f@0: static const size_t kMaxGrains = 32;
f@0: static const size_t kMinGrainsDuration = 640;
f@0:
f@0: static inline T interpolateLin( double xn, double xn_1, double decimal )
f@0: {
f@0: /* weighted sum interpolation */
f@0: return static_cast ((1 - decimal) * xn + decimal * xn_1);
f@0: }
f@0:
f@3: /**
f@3: * A single grain of the granular synthesis
f@3: */
f@0: struct PGrain
f@0: {
f@0: double phase; // read pointer to mBuffer of this grain
f@0: double rate; // rate of the grain. e.g. rate = 2 the grain will play twice as fast
f@16: bool alive; // whether this grain is alive. Not alive means it has been processed and can be replaced by another grain
f@0: size_t age; // age of this grain in samples
f@0: size_t duration; // duration of this grain in samples. minimum = 4
f@0:
f@3: double b1; // hann envelope from Ross Becina's "Implementing real time Granular Synthesis"
f@0: double y1;
f@0: double y2;
f@0: };
f@0:
f@0:
f@0:
f@3: /**
f@3: * Constructor.
f@3: *
f@3: * \param buffer a pointer to an array of T that contains the original sample that will be granulized
f@3: * \param bufferLen length of buffer in samples
f@16: * \rand function of type size_t ()(void) that is called back each time a new grain is generated. The returned value is used
f@3: * to offset the starting sample of the grain. This adds more colour to the sound especially with small selections.
f@16: * \triggerCallback function of type void ()(char, int) that is called back each time a new grain is generated.
f@16: * The function is passed the character 't' as first parameter when a new grain is triggered and the characted 'e' when the synth becomes idle (no sound).
f@16: * \ID id of this PGrain. Passed to the triggerCallback function as second parameter to identify this PGranular as the caller.
f@3: */
f@0: PGranular( const T* buffer, size_t bufferLen, size_t sampleRate, RandOffsetFunc & rand, TriggerCallbackFunc & triggerCallback, int ID ) :
f@0: mBuffer( buffer ),
f@0: mBufferLen( bufferLen ),
f@0: mNumAliveGrains( 0 ),
f@0: mGrainsRate( 1.0 ),
f@0: mTrigger( 0 ),
f@0: mTriggerRate( 0 ), // start silent
f@0: mGrainsStart( 0 ),
f@0: mGrainsDuration( kMinGrainsDuration ),
f@0: mGrainsDurationCoeff( 1 ),
f@0: mRand( rand ),
f@0: mTriggerCallback( triggerCallback ),
f@0: mEnvASR( 1.0f, 0.01f, 0.05f, sampleRate ),
f@0: mAttenuation( T(0.25118864315096) ),
f@0: mID( ID )
f@0: {
f@0: static_assert(std::is_pod::value, "PGrain must be POD");
f@0: #ifdef _WINDOW
f@0: static_assert(std::is_same::type, size_t>::value, "Rand must return a size_t");
f@0: #endif
f@0: /* init the grains */
f@0: for ( size_t grainIdx = 0; grainIdx < kMaxGrains; grainIdx++ ){
f@0: mGrains[grainIdx].phase = 0;
f@0: mGrains[grainIdx].rate = 1;
f@0: mGrains[grainIdx].alive = false;
f@0: mGrains[grainIdx].age = 0;
f@0: mGrains[grainIdx].duration = 1;
f@0: }
f@0: }
f@0:
f@0: ~PGranular(){}
f@0:
f@3: /** Sets multiplier of duration of grains in seconds */
f@0: void setGrainsDurationCoeff( double coeff )
f@0: {
f@0: mGrainsDurationCoeff = coeff;
f@0:
f@3: mGrainsDuration = std::lround( mTriggerRate * coeff );
f@0:
f@0: if ( mGrainsDuration < kMinGrainsDuration )
f@0: mGrainsDuration = kMinGrainsDuration;
f@0: }
f@0:
f@3: /** Sets rate of grains. e.g rate = 2 means one octave higer */
f@0: void setGrainsRate( double rate )
f@0: {
f@0: mGrainsRate = rate;
f@0: }
f@0:
f@3: /** sets the selection start in samples */
f@0: void setSelectionStart( size_t start )
f@0: {
f@0: mGrainsStart = start;
f@0: }
f@0:
f@3: /** Sets the selection size ( and therefore the trigger rate) in samples */
f@0: void setSelectionSize( size_t size )
f@0: {
f@0:
f@0: if ( size < kMinGrainsDuration )
f@0: size = kMinGrainsDuration;
f@0:
f@0: mTriggerRate = size;
f@0:
f@0: mGrainsDuration = std::lround( size * mGrainsDurationCoeff );
f@0:
f@0:
f@0: }
f@0:
f@3: /** Sets the attenuation of the grains with respect to the level of the recorded sample
f@3: * attenuation is in amp value and defaule value is 0.25118864315096 (-12dB) */
f@0: void setAttenuation( T attenuation )
f@0: {
f@0: mAttenuation = attenuation;
f@0: }
f@0:
f@3: /** Starts the synthesis engine */
f@0: void noteOn( double rate )
f@0: {
f@0: if ( mEnvASR.getState() == EnvASR::State::eIdle ){
f@0: // note on sets triggering top the min value
f@0: if ( mTriggerRate < kMinGrainsDuration ){
f@0: mTriggerRate = kMinGrainsDuration;
f@0: }
f@0:
f@0: setGrainsRate( rate );
f@0: mEnvASR.setState( EnvASR::State::eAttack );
f@0: }
f@0: }
f@0:
f@3: /** Stops the synthesis engine */
f@0: void noteOff()
f@0: {
f@0: if ( mEnvASR.getState() != EnvASR::State::eIdle ){
f@0: mEnvASR.setState( EnvASR::State::eRelease );
f@0: }
f@0: }
f@0:
f@3: /** Whether the synthesis engine is active or not. After noteOff is called the synth stays active until the envelope decays to 0 */
f@0: bool isIdle()
f@0: {
f@0: return mEnvASR.getState() == EnvASR::State::eIdle;
f@0: }
f@0:
f@3: /**
f@3: * Runs the granular engine and stores the output in \a audioOut
f@3: *
f@16: * \param pointer to an array of T. This will be filled with the output of PGranular. It needs to be at least \a numSamples long
f@16: * \param tempBuffer a temporary buffer used to store the envelope value. It needs to be at least \a numSamples long
f@3: * \param numSamples number of samples to be processed
f@3: */
f@0: void process( T* audioOut, T* tempBuffer, size_t numSamples )
f@0: {
f@0:
f@0: // num samples worth of sound ( due to envelope possibly finishing )
f@0: size_t envSamples = 0;
f@0: bool becameIdle = false;
f@0:
f@3: // process the envelope first and store it in the tempBuffer
f@0: for ( size_t i = 0; i < numSamples; i++ ){
f@0: tempBuffer[i] = mEnvASR.tick();
f@0: envSamples++;
f@0:
f@0: if ( isIdle() ){
f@0: // means that the envelope has stopped
f@0: becameIdle = true;
f@0: break;
f@0: }
f@0: }
f@0:
f@3: // does the actual grains processing
f@0: processGrains( audioOut, tempBuffer, envSamples );
f@0:
f@3: // becomes idle if the envelope goes to idle state
f@0: if ( becameIdle ){
f@0: mTriggerCallback( 'e', mID );
f@0: reset();
f@0: }
f@0: }
f@0:
f@0: private:
f@0:
f@0: void processGrains( T* audioOut, T* envelopeValues, size_t numSamples )
f@0: {
f@0:
f@0: /* process all existing alive grains */
f@0: for ( size_t grainIdx = 0; grainIdx < mNumAliveGrains; ){
f@0: synthesizeGrain( mGrains[grainIdx], audioOut, envelopeValues, numSamples );
f@0:
f@0: if ( !mGrains[grainIdx].alive ){
f@3: // this grain is dead so copy the last of the active grains here
f@0: // so as to keep all active grains at the beginning of the array
f@0: // don't increment grainIdx so the last active grain is processed next cycle
f@0: // if this grain is the last active grain then mNumAliveGrains is decremented
f@0: // and grainIdx = mNumAliveGrains so the loop stops
f@0: copyGrain( mNumAliveGrains - 1, grainIdx );
f@0: mNumAliveGrains--;
f@0: }
f@0: else{
f@0: // go to next grain
f@0: grainIdx++;
f@0: }
f@0: }
f@0:
f@0: if ( mTriggerRate == 0 ){
f@0: return;
f@0: }
f@0:
f@0: size_t randOffset = mRand();
f@0: bool newGrainWasTriggered = false;
f@0:
f@0: // trigger new grain and synthesize them as well
f@0: while ( mTrigger < numSamples ){
f@0:
f@0: // if there is room to accommodate new grains
f@0: if ( mNumAliveGrains < kMaxGrains ){
f@0: // get next grain will be placed at the end of the alive ones
f@0: size_t grainIdx = mNumAliveGrains;
f@0: mNumAliveGrains++;
f@0:
f@0: // initialize and synthesise the grain
f@0: PGrain &grain = mGrains[grainIdx];
f@0:
f@0: double phase = mGrainsStart + double( randOffset );
f@0: if ( phase >= mBufferLen )
f@0: phase -= mBufferLen;
f@0:
f@0: grain.phase = phase;
f@0: grain.rate = mGrainsRate;
f@0: grain.alive = true;
f@0: grain.age = 0;
f@0: grain.duration = mGrainsDuration;
f@0:
f@0: const double w = 3.14159265358979323846 / mGrainsDuration;
f@0: grain.b1 = 2.0 * std::cos( w );
f@0: grain.y1 = std::sin( w );
f@0: grain.y2 = 0.0;
f@0:
f@0: synthesizeGrain( grain, audioOut + mTrigger, envelopeValues + mTrigger, numSamples - mTrigger );
f@0:
f@0: if ( grain.alive == false ) {
f@0: mNumAliveGrains--;
f@0: }
f@0:
f@0: newGrainWasTriggered = true;
f@0: }
f@0:
f@0: // update trigger even if no new grain was started
f@0: mTrigger += mTriggerRate;
f@0: }
f@0:
f@0: // prepare trigger for next cycle: init mTrigger with the reminder of the samples from this cycle
f@0: mTrigger -= numSamples;
f@0:
f@0: if ( newGrainWasTriggered ){
f@0: mTriggerCallback( 't', mID );
f@0: }
f@0: }
f@0:
f@3: // synthesize a single grain
f@0: // audioOut = pointer to audio block to fill
f@16: // numSamples = number of samples to process for this block
f@0: void synthesizeGrain( PGrain &grain, T* audioOut, T* envelopeValues, size_t numSamples )
f@0: {
f@0:
f@16: // copy all grain data into local variable for faster processing
f@0: const auto rate = grain.rate;
f@0: auto phase = grain.phase;
f@0: auto age = grain.age;
f@0: auto duration = grain.duration;
f@0:
f@0:
f@0: auto b1 = grain.b1;
f@0: auto y1 = grain.y1;
f@0: auto y2 = grain.y2;
f@0:
f@0: // only process minimum between samples of this block and time left to leave for this grain
f@0: auto numSamplesToOut = std::min( numSamples, duration - age );
f@0:
f@0: for ( size_t sampleIdx = 0; sampleIdx < numSamplesToOut; sampleIdx++ ){
f@0:
f@0: const size_t readIndex = (size_t)phase;
f@0: const size_t nextReadIndex = (readIndex == mBufferLen - 1) ? 0 : readIndex + 1; // wrap on the read buffer if needed
f@0:
f@0: const double decimal = phase - readIndex;
f@0:
f@0: T out = interpolateLin( mBuffer[readIndex], mBuffer[nextReadIndex], decimal );
f@0:
f@0: // apply raised cosine bell envelope
f@0: auto y0 = b1 * y1 - y2;
f@0: y2 = y1;
f@0: y1 = y0;
f@0: out *= T(y0);
f@0:
f@0: audioOut[sampleIdx] += out * envelopeValues[sampleIdx] * mAttenuation;
f@0:
f@0: // increment age one sample
f@0: age++;
f@0: // increment the phase according to the rate of this grain
f@0: phase += rate;
f@0:
f@0: if ( phase >= mBufferLen ){ // wrap the phase if needed
f@0: phase -= mBufferLen;
f@0: }
f@0: }
f@0:
f@0: if ( age == duration ){
f@16: // if it processed all the samples left to leave ( numSamplesToOut = duration-age)
f@16: // then the grain is finished
f@0: grain.alive = false;
f@0: }
f@0: else{
f@0: grain.phase = phase;
f@0: grain.age = age;
f@0: grain.y1 = y1;
f@0: grain.y2 = y2;
f@0: }
f@0: }
f@0:
f@0: void copyGrain( size_t from, size_t to)
f@0: {
f@0: mGrains[to] = mGrains[from];
f@0: }
f@0:
f@0: void reset()
f@0: {
f@0: mTrigger = 0;
f@0: for ( size_t i = 0; i < mNumAliveGrains; i++ ){
f@0: mGrains[i].alive = false;
f@0: }
f@0:
f@0: mNumAliveGrains = 0;
f@0: }
f@0:
f@0: int mID;
f@0:
f@0: // pointer to (mono) buffer, where the underlying sample is recorder
f@0: const T* mBuffer;
f@0: // length of mBuffer in samples
f@0: const size_t mBufferLen;
f@0:
f@16: // offset in the buffer where the grains start. a.k.a. selection start
f@0: size_t mGrainsStart;
f@0:
f@16: // attenuates signal prevents clipping of grains (to some degree)
f@0: T mAttenuation;
f@0:
f@0: // grain duration in samples
f@0: double mGrainsDurationCoeff;
f@16: // duration of grains is selection size * duration coeff
f@0: size_t mGrainsDuration;
f@0: // rate of grain, affects pitch
f@0: double mGrainsRate;
f@0:
f@0: size_t mTrigger; // next onset
f@0: size_t mTriggerRate; // inter onset
f@0:
f@0: // the array of grains
f@0: std::array mGrains;
f@0: // number of alive grains
f@0: size_t mNumAliveGrains;
f@0:
f@0: RandOffsetFunc &mRand;
f@0: TriggerCallbackFunc &mTriggerCallback;
f@0:
f@0: EnvASR mEnvASR;
f@0: };
f@0:
f@0:
f@0:
f@0:
f@0: } // namespace collidoscope
f@0:
f@0: