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

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

  ViewVC Help
Powered by ViewVC