/[svn]/linuxsampler/trunk/src/engines/gig/EGADSR.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/engines/gig/EGADSR.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 285 by schoenebeck, Thu Oct 14 21:31:26 2004 UTC revision 1906 by persson, Sat May 16 12:14:27 2009 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6     *   Copyright (C) 2005 - 2009 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 22  Line 23 
23    
24  #include "EGADSR.h"  #include "EGADSR.h"
25    
26  namespace LinuxSampler { namespace gig {  #include "../../common/global_private.h"
27    
28      const float EGADSR::FadeOutCoeff(CalculateFadeOutCoeff());  namespace LinuxSampler { namespace gig {
29    
30      float EGADSR::CalculateFadeOutCoeff() {      EGADSR::EGADSR() {
31          const float sampleRate = 44100.0; // even if the sample rate will be 192kHz it won't hurt at all          enterEndStage();
32          const float killSteps  = EG_MIN_RELEASE_TIME * sampleRate;          Level = 0.0;
33          return -1.0f / killSteps;          CalculateFadeOutCoeff(CONFIG_EG_MIN_RELEASE_TIME, 44100.0); // even if the sample rate will be 192kHz it won't hurt at all
34      }      }
35    
36      EGADSR::EGADSR(gig::Engine* pEngine, Event::destination_t ModulationDestination) {      void EGADSR::CalculateFadeOutCoeff(float FadeOutTime, float SampleRate) {
37          this->pEngine = pEngine;          const float killSteps = FadeOutTime * SampleRate / CONFIG_DEFAULT_SUBFRAGMENT_SIZE;
38          this->ModulationDestination = ModulationDestination;          FadeOutCoeff = -1.0f / killSteps;
         Stage = stage_end;  
         Level = 0.0;  
39      }      }
40    
41      /**      void EGADSR::update(event_t Event, uint SampleRate) {
42       * Will be called by the voice for every audio fragment to let the EG          if (Event == event_hold_end) HoldAttack = false;
43       * queue it's modulation changes for the current audio fragment.  
44       *          switch (Stage) {
45       * @param TotalSamples  - total number of sample points to be rendered in this              case stage_attack:
46       *                        audio fragment cycle by the audio engine                  switch (Event) {
47       * @param pEvents       - event list with "release" and "cancel release" events                      case event_release:
48       * @param itTriggerEvent - event that caused triggering of the voice (only if                          enterReleasePart1Stage();
49       *                        the voice was triggered in the current audio                          break;
50       *                        fragment, NULL otherwise)                      case event_stage_end:
51       * @param SamplePos     - current playback position                          if (HoldAttack)
52       * @param CurrentPitch  - current pitch value for playback                              enterAttackHoldStage();
53       * @param itKillEvent   - (optional) event which caused this voice to be killed                          else
54       */                              enterDecay1Part1Stage(SampleRate);
55      void EGADSR::Process(uint TotalSamples, RTList<Event>* pEvents, RTList<Event>::Iterator itTriggerEvent, double SamplePos, double CurrentPitch, RTList<Event>::Iterator itKillEvent) {                          break;
         // skip all events which occured before this voice was triggered  
         RTList<Event>::Iterator itTransitionEvent = (itTriggerEvent) ? ++itTriggerEvent : pEvents->first();  
   
         // if the voice was killed in this fragment we only process the time before this kill event, then switch to 'stage_fadeout'  
         int Samples = (itKillEvent) ? RTMath::Min(itKillEvent->FragmentPos(), pEngine->MaxFadeOutPos) : (int) TotalSamples;  
   
         int iSample = TriggerDelay;  
         while (iSample < TotalSamples) {  
   
             // if the voice was killed in this fragment and we already processed the time before this kill event  
             if (itKillEvent && iSample >= Samples) Stage = stage_fadeout;  
   
             switch (Stage) {  
                 case stage_attack: {  
                     TriggerDelay = 0;  
                     int to_process   = RTMath::Min(AttackStepsLeft, Samples - iSample);  
                     int process_end  = iSample + to_process;  
                     AttackStepsLeft -= to_process;  
                     while (iSample < process_end) {  
                         Level += AttackCoeff;  
                         pEngine->pSynthesisParameters[ModulationDestination][iSample++] *= Level;  
                     }  
                     if (iSample == TotalSamples) { // postpone last transition event for the next audio fragment  
                         RTList<Event>::Iterator itLastEvent = pEvents->last();  
                         if (itLastEvent) ReleasePostponed = (itLastEvent->Type == Event::type_release);  
                     }  
                     if (!AttackStepsLeft) Stage = (ReleasePostponed) ? stage_release : (HoldAttack) ? stage_attack_hold : stage_decay1;  
                     break;  
56                  }                  }
57                  case stage_attack_hold: {                  break;
58                      if (SamplePos >= LoopStart) {              case stage_attack_hold:
59                          Stage = stage_decay1;                  switch (Event) {
60                        case event_stage_end: {// just refresh time
61                            const int intMax = (unsigned int) -1 >> 1;
62                            StepsLeft = intMax; // we use the highest possible value
63                          break;                          break;
64                      }                      }
65                      int holdstepsleft = (int) (LoopStart - SamplePos / CurrentPitch); // FIXME: just an approximation, inaccuracy grows with higher audio fragment size, sufficient for usual fragment sizes though                      case event_hold_end:
66                      int to_process    = RTMath::Min(holdstepsleft, Samples - iSample);                          enterDecay1Part1Stage(SampleRate);
67                      int process_end   = iSample + to_process;                          break;
68                      if (itTransitionEvent && itTransitionEvent->FragmentPos() <= process_end) {                      case event_release:
69                          process_end       = itTransitionEvent->FragmentPos();                          enterReleasePart1Stage();
70                          Stage             = (itTransitionEvent->Type == Event::type_release) ? stage_release : (InfiniteSustain) ? stage_sustain : stage_decay2;                          break;
                         ++itTransitionEvent;  
                     }  
                     else if (to_process == holdstepsleft) Stage = stage_decay1;  
                     while (iSample < process_end) {  
                         pEngine->pSynthesisParameters[ModulationDestination][iSample++] *= Level;  
                     }  
                     break;  
71                  }                  }
72                  case stage_decay1: {                  break;
73                      int to_process   = RTMath::Min(Samples - iSample, Decay1StepsLeft);              case stage_decay1_part1:
74                      int process_end  = iSample + to_process;                  switch (Event) {
75                      if (itTransitionEvent && itTransitionEvent->FragmentPos() <= process_end) {                      case event_stage_end:
76                          process_end       = itTransitionEvent->FragmentPos();                          enterDecay1Part2Stage(SampleRate);
77                          Stage             = (itTransitionEvent->Type == Event::type_release) ? stage_release : (InfiniteSustain) ? stage_sustain : stage_decay2;                          break;
78                          ++itTransitionEvent;                      case event_cancel_release:
79                      }                          if (InfiniteSustain)
80                      else {                              enterSustainStage();
81                          Decay1StepsLeft -= to_process;                          else
82                          if (!Decay1StepsLeft) Stage = (InfiniteSustain) ? stage_sustain : stage_decay2;                              enterDecay2Stage(SampleRate);
83                      }                          break;
                     while (iSample < process_end) {  
                         Level += Level * Decay1Coeff;  
                         pEngine->pSynthesisParameters[ModulationDestination][iSample++] *= Level;  
                     }  
                     break;  
84                  }                  }
85                  case stage_decay2: {                  break;
86                      int process_end;              case stage_decay1_part2:
87                      if (itTransitionEvent && itTransitionEvent->Type == Event::type_release && itTransitionEvent->FragmentPos() <= Samples) {                  switch (Event) {
88                          process_end       = itTransitionEvent->FragmentPos();                      case event_release:
89                          ++itTransitionEvent;                          enterReleasePart1Stage();
90                          Stage             = stage_release; // switch to release stage soon                          break;
91                      }                      case event_stage_end:
92                      else process_end = Samples;                          if (Level < CONFIG_EG_BOTTOM)
93                      while (iSample < process_end) {                              enterEndStage();
94                          Level += Level * Decay2Coeff;                          else if (InfiniteSustain)
95                          pEngine->pSynthesisParameters[ModulationDestination][iSample++] *= Level;                              enterSustainStage();
96                      }                          else
97                      if (Level <= EG_ENVELOPE_LIMIT) Stage = stage_fadeout;                              enterDecay2Stage(SampleRate);
98                      break;                          break;
99                  }                  }
100                  case stage_sustain: {                  break;
101                      int process_end;              case stage_decay2:
102                      if (itTransitionEvent && itTransitionEvent->Type == Event::type_release && itTransitionEvent->FragmentPos() <= Samples) {                  switch (Event) {
103                          process_end       = itTransitionEvent->FragmentPos();                      case event_stage_end:
104                          ++itTransitionEvent;                          enterFadeOutStage();
105                          Stage             = stage_release; // switch to release stage soon                          break;
106                      }                      case event_release:
107                      else process_end = Samples;                          enterReleasePart1Stage();
108                      while (iSample < process_end) {                          break;
109                         pEngine->pSynthesisParameters[ModulationDestination][iSample++] *= Level;                      case event_hold_end:
110                      }                          enterDecay1Part1Stage(SampleRate);
111                      break;                          break;
112                  }                  }
113                  case stage_release: {                  break;
114                      int process_end;              case stage_sustain:
115                      if (itTransitionEvent && itTransitionEvent->Type == Event::type_cancel_release && itTransitionEvent->FragmentPos() <= Samples) {                  switch (Event) {
116                          process_end       = itTransitionEvent->FragmentPos();                      case event_stage_end: {// just refresh time
117                          ++itTransitionEvent;                          const int intMax = (unsigned int) -1 >> 1;
118                          Stage             = (InfiniteSustain) ? stage_sustain : stage_decay2; // switch back to sustain / decay2 stage soon                          StepsLeft = intMax; // we use the highest possible value
119                      }                          break;
                     else process_end = Samples;  
                     while (iSample < process_end) {  
                         Level += Level * ReleaseCoeff;  
                         pEngine->pSynthesisParameters[ModulationDestination][iSample++] *= Level;  
120                      }                      }
121                      if (Level <= EG_ENVELOPE_LIMIT) Stage = stage_fadeout;                      case event_release:
122                      break;                          enterReleasePart1Stage();
123                            break;
124                        case event_hold_end:
125                            enterDecay1Part1Stage(SampleRate);
126                            break;
127                  }                  }
128                  case stage_fadeout: {                  break;
129                      int to_process   = RTMath::Min(int(Level / (-FadeOutCoeff)), TotalSamples - iSample);              case stage_release_part1:
130                      int process_end  = iSample + to_process;                  switch (Event) {
131                      while (iSample < process_end) {                      case event_stage_end:
132                          Level += FadeOutCoeff;                          enterReleasePart2Stage();
133                          pEngine->pSynthesisParameters[ModulationDestination][iSample++] *= Level;                          break;
134                      }                      case event_cancel_release:
135                      Stage = stage_end;                          if (InfiniteSustain)
136                      if (Level > -FadeOutCoeff) dmsg(1,("EGADSR: Warning, final fade out level too high, may result in click sound!\n"));                              enterSustainStage();
137                  } //Fall through here instead of breaking otherwise we can get back into stage_fadeout and loop forever!                          else
138                  case stage_end: {                              enterDecay2Stage(SampleRate);
139                      while (iSample < TotalSamples) {                          break;
                         pEngine->pSynthesisParameters[ModulationDestination][iSample++] = 0.0f;  
                     }  
                     break;  
140                  }                  }
141              }                  break;
142          }              case stage_release_part2:
143                    switch (Event) {
144          if (itKillEvent && Stage != stage_end) {                      case event_stage_end:
145              dmsg(1,("EGADSR: VOICE KILLING NOT COMPLETED !!!\n"));                          enterFadeOutStage();
146              dmsg(1,("EGADSR: Stage=%d,iSample=%d,Samples=%d, TotalSamples=%d, MaxFadoutPos=%d\n",Stage,iSample,Samples,TotalSamples,pEngine->MaxFadeOutPos));                          break;
147                        case event_cancel_release:
148                            if (InfiniteSustain)
149                                enterSustainStage();
150                            else
151                                enterDecay2Stage(SampleRate);
152                            break;
153                    }
154                    break;
155                case stage_fadeout:
156                    switch (Event) {
157                        case event_stage_end:
158                            enterEndStage();
159                            break;
160                    }
161                    break;
162          }          }
163      }      }
164    
165      /**      void EGADSR::trigger(uint PreAttack, float AttackTime, bool HoldAttack, float Decay1Time, double Decay2Time, bool InfiniteSustain, uint SustainLevel, float ReleaseTime, float Volume, uint SampleRate) {
166       * Will be called by the voice when the key / voice was triggered.          this->SustainLevel     = SustainLevel / 1000.0;
      *  
      * @param PreAttack       - Preattack value for the envelope (0 - 1000 permille)  
      * @param AttackTime      - Attack time for the envelope (0.000 - 60.000s)  
      * @param HoldAttack      - If true, Decay1 will be postponed until the sample reached the sample loop start.  
      * @param LoopStart       - Sample position where sample loop starts (if any)  
      * @param Decay1Time      - Decay1 time of the sample amplitude EG (0.000 - 60.000s).  
      * @param Decay2Time      - Only if !InfiniteSustain: 2nd decay stage time of the sample amplitude EG (0.000 - 60.000s).  
      * @param InfiniteSustain - If true, instead of going into Decay2 phase, Decay1 level will be hold until note will be released.  
      * @param SustainLevel    - Sustain level of the sample amplitude EG (0 - 1000 permille).  
      * @param ReleaseTIme     - Release time for the envelope (0.000 - 60.000s)  
      * @param Delay           - Number of sample points triggering should be delayed.  
      */  
     void EGADSR::Trigger(uint PreAttack, double AttackTime, bool HoldAttack, long LoopStart, double Decay1Time, double Decay2Time, bool InfiniteSustain, uint SustainLevel, double ReleaseTime, uint Delay) {  
         this->TriggerDelay     = Delay;  
         this->Stage            = stage_attack;  
         this->SustainLevel     = (SustainLevel) ? (SustainLevel > EG_ENVELOPE_LIMIT) ? (float) SustainLevel / 1000.0 : EG_ENVELOPE_LIMIT : 1.0;  
167          this->InfiniteSustain  = InfiniteSustain;          this->InfiniteSustain  = InfiniteSustain;
168          this->HoldAttack       = HoldAttack;          this->HoldAttack       = HoldAttack;
         this->LoopStart        = LoopStart;  
         this->ReleasePostponed = false;  
169    
170          // calculate attack stage parameters (lin. curve)          this->Decay1Time = Decay1Time;
171          AttackStepsLeft = (long) (AttackTime * pEngine->pAudioOutputDevice->SampleRate());          this->Decay2Time = Decay2Time;
172          if (AttackStepsLeft) {  
173              Level       = (float) PreAttack / 1000.0;          invVolume = 1 / Volume;
174              AttackCoeff = (1.0 - Level) / AttackStepsLeft;          ExpOffset = (0.25 - 1 / 3.55) * invVolume;
175    
176            // calculate release stage parameters (lin+exp curve)
177            if (ReleaseTime < CONFIG_EG_MIN_RELEASE_TIME) ReleaseTime = CONFIG_EG_MIN_RELEASE_TIME;  // to avoid click sounds at the end of the sample playback
178            const float ReleaseStepsLeft = (long) (ReleaseTime * SampleRate);
179            ReleaseSlope  = 1.365 * (0 - 1) / ReleaseStepsLeft;
180            ReleaseCoeff  = ReleaseSlope * invVolume;
181            ReleaseSlope  *= 3.55;
182            ReleaseCoeff2 = exp(ReleaseSlope);
183            ReleaseCoeff3 = ExpOffset * (1 - ReleaseCoeff2);
184            ReleaseLevel2 = 0.25 * invVolume;
185    
186            enterAttackStage(PreAttack, AttackTime, SampleRate);
187        }
188    
189        void EGADSR::enterAttackStage(const uint PreAttack, const float AttackTime, const uint SampleRate) {
190            Stage   = stage_attack;
191            Segment = segment_lin;
192    
193            if (AttackTime >= 0.0005f) {
194                // Measurements of GSt output shows that the real attack time
195                // is about 65.5% of the value specified in the gig file.
196                // The minimum attack value used is 0.032.
197                StepsLeft = int(0.655f * RTMath::Max(AttackTime, 0.032f) * SampleRate);
198                Level = (float) PreAttack / 1000.0;
199                Coeff = 0.896f * (1.0f - Level) / StepsLeft; // max level is a bit lower if attack != 0
200            } else { // attack is zero - immediately jump to the next stage
201                Level = 1.029f; // a bit higher than max sustain
202                if (HoldAttack) enterAttackHoldStage();
203                else            enterDecay1Part1Stage(SampleRate);
204          }          }
205          else {      }
206              Level       = 1.0;  
207              AttackCoeff = 0.0;      void EGADSR::enterAttackHoldStage() {
208            Stage     = stage_attack_hold;
209            Segment   = segment_lin;
210            Coeff     = 0.0f; // don't rise anymore
211            const int intMax = (unsigned int) -1 >> 1;
212            StepsLeft = intMax; // we use the highest value possible (we refresh StepsLeft in update() in case)
213        }
214    
215        void EGADSR::enterDecay1Part1Stage(const uint SampleRate) {
216            // The decay1 and release stage both consist of two parts,
217            // first a linear curve, f, followed by an exponential curve,
218            // g:
219            //
220            // f(x + d) = f(x) + Coeff
221            // g(x + d) = Coeff2 * g(x) + Coeff3
222            //
223            // (where d is 1/SampleRate). The transition from f to g is
224            // done when f(x) has reached Level2 = 25% of full volume.
225            StepsLeft = (int) (Decay1Time * SampleRate);
226            if (StepsLeft && Level > SustainLevel) {
227                Stage        = stage_decay1_part1;
228                Segment      = segment_lin;
229                Decay1Slope = (1.347f * SustainLevel - 1.361f) / StepsLeft;
230                Coeff        = Decay1Slope * invVolume;
231                Decay1Level2 = 0.25 * invVolume;
232                StepsLeft = int((RTMath::Max(Decay1Level2, SustainLevel) - Level) / Coeff);
233                if (StepsLeft <= 0) enterDecay1Part2Stage(SampleRate);
234            } else {
235                if (InfiniteSustain) enterSustainStage();
236                else                 enterDecay2Stage(SampleRate);
237          }          }
238        }
239    
240          // calculate decay1 stage parameters (exp. curve)      void EGADSR::enterDecay1Part2Stage(const uint SampleRate) {
241          Decay1StepsLeft = (long) (Decay1Time * pEngine->pAudioOutputDevice->SampleRate());          if (SustainLevel < Decay1Level2) {
242          Decay1Coeff     = (Decay1StepsLeft) ? exp(log(this->SustainLevel) / (double) Decay1StepsLeft) - 1.0              Stage   = stage_decay1_part2;
243                                              : 0.0;              Segment = segment_exp;
244                Decay1Slope *= 3.55;
245          // calculate decay2 stage parameters (exp. curve)              Coeff  = exp(Decay1Slope);
246          if (!InfiniteSustain) {              Offset = ExpOffset * (1 - Coeff);
247              if (Decay2Time < EG_MIN_RELEASE_TIME) Decay2Time = EG_MIN_RELEASE_TIME;              StepsLeft = int(log((SustainLevel - ExpOffset) / (Level - ExpOffset)) / Decay1Slope);
248              long Decay2Steps = (long) (Decay2Time * pEngine->pAudioOutputDevice->SampleRate());              if (StepsLeft > 0) return;
             Decay2Coeff      = (Decay2Steps) ? exp((log(EG_ENVELOPE_LIMIT) - log(this->SustainLevel)) / Decay2Steps + log(this->SustainLevel)) - this->SustainLevel  
                                              : 0.0;  
249          }          }
250            if (InfiniteSustain) enterSustainStage();
251            else                 enterDecay2Stage(SampleRate);
252        }
253    
254        void EGADSR::enterDecay2Stage(const uint SampleRate) {
255            Stage      = stage_decay2;
256            Segment    = segment_lin;
257            Decay2Time = RTMath::Max(Decay2Time, 0.05f);
258            StepsLeft  = (int) (Decay2Time * SampleRate);
259            Coeff      = (-1.03 / StepsLeft) * invVolume;
260            //FIXME: do we really have to calculate 'StepsLeft' two times?
261            StepsLeft  = int((CONFIG_EG_BOTTOM - Level) / Coeff);
262            if (StepsLeft <= 0) enterEndStage();
263        }
264    
265        void EGADSR::enterSustainStage() {
266            Stage   = stage_sustain;
267            Segment = segment_lin;
268            Coeff   = 0.0f; // don't change the envelope level in this stage
269            const int intMax = (unsigned int) -1 >> 1;
270            StepsLeft = intMax; // we use the highest value possible (we refresh StepsLeft in update() in case)
271        }
272    
273          // calculate release stage parameters (exp. curve)      void EGADSR::enterReleasePart1Stage() {
274          if (ReleaseTime < EG_MIN_RELEASE_TIME) ReleaseTime = EG_MIN_RELEASE_TIME;  // to avoid click sounds at the end of the sample playback          Stage     = stage_release_part1;
275          ReleaseStepsLeft = (long) (ReleaseTime * pEngine->pAudioOutputDevice->SampleRate());          Segment   = segment_lin;
276          ReleaseCoeff     = exp((log(EG_ENVELOPE_LIMIT) - log(this->SustainLevel)) / ReleaseStepsLeft + log(this->SustainLevel)) - this->SustainLevel;          StepsLeft = int((ReleaseLevel2 - Level) / ReleaseCoeff);
277            Coeff     = ReleaseCoeff;
278            if (StepsLeft <= 0) enterReleasePart2Stage();
279        }
280    
281        void EGADSR::enterReleasePart2Stage() {
282            Stage     = stage_release_part2;
283            Segment   = segment_exp;
284            StepsLeft = int(log((CONFIG_EG_BOTTOM - ExpOffset) / (Level - ExpOffset)) / ReleaseSlope);
285            Coeff     = ReleaseCoeff2;
286            Offset    = ReleaseCoeff3;
287            if (StepsLeft <= 0) enterFadeOutStage();
288        }
289    
290        void EGADSR::enterFadeOutStage() {
291            Stage     = stage_fadeout;
292            Segment   = segment_lin;
293            StepsLeft = int(Level / (-FadeOutCoeff));
294            Coeff     = FadeOutCoeff;
295            if (StepsLeft <= 0) enterEndStage();
296        }
297    
298        void EGADSR::enterFadeOutStage(int maxFadeOutSteps) {
299            Stage     = stage_fadeout;
300            Segment   = segment_lin;
301            StepsLeft = int(Level / (-FadeOutCoeff));
302            if (StepsLeft > maxFadeOutSteps) {
303                StepsLeft = maxFadeOutSteps;
304                Coeff = -Level / maxFadeOutSteps;
305            } else {
306                Coeff = FadeOutCoeff;
307            }
308            if (StepsLeft <= 0) enterEndStage();
309        }
310    
311          dmsg(4,("PreAttack=%d, AttackLength=%d, AttackCoeff=%f, Decay1Coeff=%f, Decay2Coeff=%f, ReleaseLength=%d, ReleaseCoeff=%f\n",      void EGADSR::enterEndStage() {
312                  PreAttack, AttackStepsLeft, AttackCoeff, Decay1Coeff, Decay2Coeff, ReleaseStepsLeft, ReleaseCoeff));          Stage   = stage_end;
313            Segment = segment_end;
314            Level   = 0;
315      }      }
316    
317  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.285  
changed lines
  Added in v.1906

  ViewVC Help
Powered by ViewVC