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

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

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

revision 473 by schoenebeck, Thu Mar 17 20:13:08 2005 UTC revision 690 by schoenebeck, Fri Jul 15 16:43:56 2005 UTC
# Line 103  namespace LinuxSampler { namespace gig { Line 103  namespace LinuxSampler { namespace gig {
103          pAudioOutputDevice = NULL;          pAudioOutputDevice = NULL;
104          pDiskThread        = NULL;          pDiskThread        = NULL;
105          pEventGenerator    = NULL;          pEventGenerator    = NULL;
106          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);          pSysexBuffer       = new RingBuffer<uint8_t>(CONFIG_SYSEX_BUFFER_SIZE, 0);
107          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);          pEventQueue        = new RingBuffer<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
108          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
109          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);          pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);
110          pVoiceStealingQueue = new RTList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
111          pGlobalEvents      = new RTList<Event>(pEventPool);          pGlobalEvents      = new RTList<Event>(pEventPool);
112          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
# Line 119  namespace LinuxSampler { namespace gig { Line 119  namespace LinuxSampler { namespace gig {
119          pMainFilterParameters   = NULL;          pMainFilterParameters   = NULL;
120    
121          ResetInternal();          ResetInternal();
122            ResetScaleTuning();
123      }      }
124    
125      /**      /**
# Line 171  namespace LinuxSampler { namespace gig { Line 172  namespace LinuxSampler { namespace gig {
172      void Engine::Reset() {      void Engine::Reset() {
173          DisableAndLock();          DisableAndLock();
174          ResetInternal();          ResetInternal();
175            ResetScaleTuning();
176          Enable();          Enable();
177      }      }
178    
# Line 184  namespace LinuxSampler { namespace gig { Line 186  namespace LinuxSampler { namespace gig {
186    
187          // reset voice stealing parameters          // reset voice stealing parameters
188          pVoiceStealingQueue->clear();          pVoiceStealingQueue->clear();
189          itLastStolenVoice  = RTList<Voice>::Iterator();          itLastStolenVoice          = RTList<Voice>::Iterator();
190          iuiLastStolenKey   = RTList<uint>::Iterator();          itLastStolenVoiceGlobally  = RTList<Voice>::Iterator();
191          pLastStolenChannel = NULL;          iuiLastStolenKey           = RTList<uint>::Iterator();
192            iuiLastStolenKeyGlobally   = RTList<uint>::Iterator();
193          // reset to normal chromatic scale (means equal temper)          pLastStolenChannel         = NULL;
         memset(&ScaleTuning[0], 0x00, 12);  
194    
195          // reset all voices          // reset all voices
196          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
# Line 205  namespace LinuxSampler { namespace gig { Line 206  namespace LinuxSampler { namespace gig {
206      }      }
207    
208      /**      /**
209         * Reset to normal, chromatic scale (means equal tempered).
210         */
211        void Engine::ResetScaleTuning() {
212            memset(&ScaleTuning[0], 0x00, 12);
213        }
214    
215        /**
216       * Connect this engine instance with the given audio output device.       * Connect this engine instance with the given audio output device.
217       * This method will be called when an Engine instance is created.       * This method will be called when an Engine instance is created.
218       * All of the engine's data structures which are dependant to the used       * All of the engine's data structures which are dependant to the used
# Line 231  namespace LinuxSampler { namespace gig { Line 239  namespace LinuxSampler { namespace gig {
239          this->SampleRate         = pAudioOutputDevice->SampleRate();          this->SampleRate         = pAudioOutputDevice->SampleRate();
240    
241          // FIXME: audio drivers with varying fragment sizes might be a problem here          // FIXME: audio drivers with varying fragment sizes might be a problem here
242          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
243          if (MaxFadeOutPos < 0)          if (MaxFadeOutPos < 0) {
244              throw LinuxSamplerException("EG_MIN_RELEASE_TIME in EGADSR.h too big for current audio fragment size / sampling rate!");              std::cerr << "gig::Engine: WARNING, CONFIG_EG_MIN_RELEASE_TIME "
245                          << "too big for current audio fragment size & sampling rate! "
246                          << "May lead to click sounds if voice stealing chimes in!\n" << std::flush;
247                // force volume ramp downs at the beginning of each fragment
248                MaxFadeOutPos = 0;
249                // lower minimum release time
250                const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
251                for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
252                    iterVoice->pEG1->CalculateFadeOutCoeff(minReleaseTime, SampleRate);
253                }
254                pVoicePool->clear();
255            }
256    
257          // (re)create disk thread          // (re)create disk thread
258          if (this->pDiskThread) {          if (this->pDiskThread) {
# Line 242  namespace LinuxSampler { namespace gig { Line 261  namespace LinuxSampler { namespace gig {
261              delete this->pDiskThread;              delete this->pDiskThread;
262              dmsg(1,("OK\n"));              dmsg(1,("OK\n"));
263          }          }
264          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << CONFIG_MAX_PITCH) << 1) + 6); //FIXME: assuming stereo
265          if (!pDiskThread) {          if (!pDiskThread) {
266              dmsg(0,("gig::Engine  new diskthread = NULL\n"));              dmsg(0,("gig::Engine  new diskthread = NULL\n"));
267              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
# Line 352  namespace LinuxSampler { namespace gig { Line 371  namespace LinuxSampler { namespace gig {
371          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // update time of start and end of this audio fragment (as events' time stamps relate to this)
372          pEventGenerator->UpdateFragmentTime(Samples);          pEventGenerator->UpdateFragmentTime(Samples);
373    
374            // We only allow a maximum of CONFIG_MAX_VOICES voices to be spawned
375            // in each audio fragment. All subsequent request for spawning new
376            // voices in the same audio fragment will be ignored.
377            VoiceSpawnsLeft = CONFIG_MAX_VOICES;
378    
379          // get all events from the engine's global input event queue which belong to the current fragment          // get all events from the engine's global input event queue which belong to the current fragment
380          // (these are usually just SysEx messages)          // (these are usually just SysEx messages)
381          ImportEvents(Samples);          ImportEvents(Samples);
# Line 370  namespace LinuxSampler { namespace gig { Line 394  namespace LinuxSampler { namespace gig {
394              }              }
395          }          }
396    
         // We only allow a maximum of MAX_AUDIO_VOICES voices to be stolen  
         // in each audio fragment. All subsequent request for spawning new  
         // voices in the same audio fragment will be ignored.  
         VoiceTheftsLeft = MAX_AUDIO_VOICES;  
   
397          // reset internal voice counter (just for statistic of active voices)          // reset internal voice counter (just for statistic of active voices)
398          ActiveVoiceCountTemp = 0;          ActiveVoiceCountTemp = 0;
399    
   
400          // handle events on all engine channels          // handle events on all engine channels
401          for (int i = 0; i < engineChannels.size(); i++) {          for (int i = 0; i < engineChannels.size(); i++) {
402              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
# Line 406  namespace LinuxSampler { namespace gig { Line 424  namespace LinuxSampler { namespace gig {
424    
425          // reset voice stealing for the next audio fragment          // reset voice stealing for the next audio fragment
426          pVoiceStealingQueue->clear();          pVoiceStealingQueue->clear();
         itLastStolenVoice  = RTList<Voice>::Iterator();  
         iuiLastStolenKey   = RTList<uint>::Iterator();  
         pLastStolenChannel = NULL;  
427    
428          // just some statistics about this engine instance          // just some statistics about this engine instance
429          ActiveVoiceCount = ActiveVoiceCountTemp;          ActiveVoiceCount = ActiveVoiceCountTemp;
430          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
431    
432            FrameTime += Samples;
433    
434          return 0;          return 0;
435      }      }
436    
# Line 456  namespace LinuxSampler { namespace gig { Line 473  namespace LinuxSampler { namespace gig {
473                  }                  }
474              }              }
475          }          }
476    
477            // reset voice stealing for the next engine channel (or next audio fragment)
478            itLastStolenVoice         = RTList<Voice>::Iterator();
479            itLastStolenVoiceGlobally = RTList<Voice>::Iterator();
480            iuiLastStolenKey          = RTList<uint>::Iterator();
481            iuiLastStolenKeyGlobally  = RTList<uint>::Iterator();
482            pLastStolenChannel        = NULL;
483      }      }
484    
485      /**      /**
# Line 506  namespace LinuxSampler { namespace gig { Line 530  namespace LinuxSampler { namespace gig {
530          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
531              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
532              Pool<Voice>::Iterator itNewVoice =              Pool<Voice>::Iterator itNewVoice =
533                  LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);                  LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
534              if (itNewVoice) {              if (itNewVoice) {
535                  itNewVoice->Render(Samples);                  itNewVoice->Render(Samples);
536                  if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active                  if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
# Line 539  namespace LinuxSampler { namespace gig { Line 563  namespace LinuxSampler { namespace gig {
563                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
564                  ++iuiKey;                  ++iuiKey;
565                  if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);                  if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
566                  #if DEVMODE                  #if CONFIG_DEVMODE
567                  else { // FIXME: should be removed before the final release (purpose: just a sanity check for debugging)                  else { // just a sanity check for debugging
568                      RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();                      RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
569                      RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();                      RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
570                      for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key                      for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
# Line 549  namespace LinuxSampler { namespace gig { Line 573  namespace LinuxSampler { namespace gig {
573                          }                          }
574                      }                      }
575                  }                  }
576                  #endif // DEVMODE                  #endif // CONFIG_DEVMODE
577              }              }
578          }          }
579    
# Line 584  namespace LinuxSampler { namespace gig { Line 608  namespace LinuxSampler { namespace gig {
608                  // finally place sysex event into input event queue                  // finally place sysex event into input event queue
609                  pEventQueue->push(&event);                  pEventQueue->push(&event);
610              }              }
611              else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,SYSEX_BUFFER_SIZE));              else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,CONFIG_SYSEX_BUFFER_SIZE));
612          }          }
613          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
614      }      }
# Line 610  namespace LinuxSampler { namespace gig { Line 634  namespace LinuxSampler { namespace gig {
634          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
635    
636          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
637            pKey->Velocity   = itNoteOnEvent->Param.Note.Velocity;
638            pKey->NoteOnTime = FrameTime + itNoteOnEvent->FragmentPos(); // will be used to calculate note length
639    
640          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
641          if (pKey->Active && !pEngineChannel->SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
# Line 632  namespace LinuxSampler { namespace gig { Line 658  namespace LinuxSampler { namespace gig {
658                  int voicesRequired = pRegion->Layers;                  int voicesRequired = pRegion->Layers;
659                  // now launch the required amount of voices                  // now launch the required amount of voices
660                  for (int i = 0; i < voicesRequired; i++)                  for (int i = 0; i < voicesRequired; i++)
661                      LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true);                      LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
662              }              }
663          }          }
664    
# Line 660  namespace LinuxSampler { namespace gig { Line 686  namespace LinuxSampler { namespace gig {
686          // release voices on this key if needed          // release voices on this key if needed
687          if (pKey->Active && !pEngineChannel->SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
688              itNoteOffEvent->Type = Event::type_release; // transform event type              itNoteOffEvent->Type = Event::type_release; // transform event type
         }  
689    
690          // move event to the key's own event list              // move event to the key's own event list
691          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);              RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
692    
693          // spawn release triggered voice(s) if needed              // spawn release triggered voice(s) if needed
694          if (pKey->ReleaseTrigger) {              if (pKey->ReleaseTrigger) {
695              // first, get total amount of required voices (dependant on amount of layers)                  // first, get total amount of required voices (dependant on amount of layers)
696              ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);                  ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
697              if (pRegion) {                  if (pRegion) {
698                  int voicesRequired = pRegion->Layers;                      int voicesRequired = pRegion->Layers;
699                  // now launch the required amount of voices  
700                  for (int i = 0; i < voicesRequired; i++)                      // MIDI note-on velocity is used instead of note-off velocity
701                      LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples                      itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity;
702    
703                        // now launch the required amount of voices
704                        for (int i = 0; i < voicesRequired; i++)
705                            LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
706                    }
707                    pKey->ReleaseTrigger = false;
708              }              }
             pKey->ReleaseTrigger = false;  
         }  
709    
710          // if neither a voice was spawned or postponed then remove note off event from key again              // if neither a voice was spawned or postponed then remove note off event from key again
711          if (!pKey->Active && !pKey->VoiceTheftsQueued)              if (!pKey->Active && !pKey->VoiceTheftsQueued)
712              pKey->pEvents->free(itNoteOffEventOnKeyList);                  pKey->pEvents->free(itNoteOffEventOnKeyList);
713            }
714      }      }
715    
716      /**      /**
# Line 709  namespace LinuxSampler { namespace gig { Line 739  namespace LinuxSampler { namespace gig {
739       *  @param VoiceStealing       - if voice stealing should be performed       *  @param VoiceStealing       - if voice stealing should be performed
740       *                               when there is no free voice       *                               when there is no free voice
741       *                               (optional, default = true)       *                               (optional, default = true)
742         *  @param HandleKeyGroupConflicts - if voices should be killed due to a
743         *                                   key group conflict
744       *  @returns pointer to new voice or NULL if there was no free voice or       *  @returns pointer to new voice or NULL if there was no free voice or
745       *           if the voice wasn't triggered (for example when no region is       *           if the voice wasn't triggered (for example when no region is
746       *           defined for the given key).       *           defined for the given key).
747       */       */
748      Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {      Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing, bool HandleKeyGroupConflicts) {
749          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];          int MIDIKey            = itNoteOnEvent->Param.Note.Key;
750            midi_key_info_t* pKey  = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
751            ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
752    
753            // if nothing defined for this key
754            if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
755    
756            // only mark the first voice of a layered voice (group) to be in a
757            // key group, so the layered voices won't kill each other
758            int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
759    
760            // handle key group (a.k.a. exclusive group) conflicts
761            if (HandleKeyGroupConflicts) {
762                if (iKeyGroup) { // if this voice / key belongs to a key group
763                    uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
764                    if (*ppKeyGroup) { // if there's already an active key in that key group
765                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
766                        // kill all voices on the (other) key
767                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
768                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
769                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
770                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
771                                itVoiceToBeKilled->Kill(itNoteOnEvent);
772                                --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
773                            }
774                        }
775                    }
776                }
777            }
778    
779            Voice::type_t VoiceType = Voice::type_normal;
780    
781            // get current dimension values to select the right dimension region
782            //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
783            //FIXME: controller values for selecting the dimension region here are currently not sample accurate
784            uint DimValues[8] = { 0 };
785            for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
786                switch (pRegion->pDimensionDefinitions[i].dimension) {
787                    case ::gig::dimension_samplechannel:
788                        DimValues[i] = 0; //TODO: we currently ignore this dimension
789                        break;
790                    case ::gig::dimension_layer:
791                        DimValues[i] = iLayer;
792                        break;
793                    case ::gig::dimension_velocity:
794                        DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
795                        break;
796                    case ::gig::dimension_channelaftertouch:
797                        DimValues[i] = 0; //TODO: we currently ignore this dimension
798                        break;
799                    case ::gig::dimension_releasetrigger:
800                        VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
801                        DimValues[i] = (uint) ReleaseTriggerVoice;
802                        break;
803                    case ::gig::dimension_keyboard:
804                        DimValues[i] = (uint) pEngineChannel->CurrentKeyDimension;
805                        break;
806                    case ::gig::dimension_roundrobin:
807                        DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
808                        break;
809                    case ::gig::dimension_random:
810                        RandomSeed   = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
811                        DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
812                        break;
813                    case ::gig::dimension_modwheel:
814                        DimValues[i] = pEngineChannel->ControllerTable[1];
815                        break;
816                    case ::gig::dimension_breath:
817                        DimValues[i] = pEngineChannel->ControllerTable[2];
818                        break;
819                    case ::gig::dimension_foot:
820                        DimValues[i] = pEngineChannel->ControllerTable[4];
821                        break;
822                    case ::gig::dimension_portamentotime:
823                        DimValues[i] = pEngineChannel->ControllerTable[5];
824                        break;
825                    case ::gig::dimension_effect1:
826                        DimValues[i] = pEngineChannel->ControllerTable[12];
827                        break;
828                    case ::gig::dimension_effect2:
829                        DimValues[i] = pEngineChannel->ControllerTable[13];
830                        break;
831                    case ::gig::dimension_genpurpose1:
832                        DimValues[i] = pEngineChannel->ControllerTable[16];
833                        break;
834                    case ::gig::dimension_genpurpose2:
835                        DimValues[i] = pEngineChannel->ControllerTable[17];
836                        break;
837                    case ::gig::dimension_genpurpose3:
838                        DimValues[i] = pEngineChannel->ControllerTable[18];
839                        break;
840                    case ::gig::dimension_genpurpose4:
841                        DimValues[i] = pEngineChannel->ControllerTable[19];
842                        break;
843                    case ::gig::dimension_sustainpedal:
844                        DimValues[i] = pEngineChannel->ControllerTable[64];
845                        break;
846                    case ::gig::dimension_portamento:
847                        DimValues[i] = pEngineChannel->ControllerTable[65];
848                        break;
849                    case ::gig::dimension_sostenutopedal:
850                        DimValues[i] = pEngineChannel->ControllerTable[66];
851                        break;
852                    case ::gig::dimension_softpedal:
853                        DimValues[i] = pEngineChannel->ControllerTable[67];
854                        break;
855                    case ::gig::dimension_genpurpose5:
856                        DimValues[i] = pEngineChannel->ControllerTable[80];
857                        break;
858                    case ::gig::dimension_genpurpose6:
859                        DimValues[i] = pEngineChannel->ControllerTable[81];
860                        break;
861                    case ::gig::dimension_genpurpose7:
862                        DimValues[i] = pEngineChannel->ControllerTable[82];
863                        break;
864                    case ::gig::dimension_genpurpose8:
865                        DimValues[i] = pEngineChannel->ControllerTable[83];
866                        break;
867                    case ::gig::dimension_effect1depth:
868                        DimValues[i] = pEngineChannel->ControllerTable[91];
869                        break;
870                    case ::gig::dimension_effect2depth:
871                        DimValues[i] = pEngineChannel->ControllerTable[92];
872                        break;
873                    case ::gig::dimension_effect3depth:
874                        DimValues[i] = pEngineChannel->ControllerTable[93];
875                        break;
876                    case ::gig::dimension_effect4depth:
877                        DimValues[i] = pEngineChannel->ControllerTable[94];
878                        break;
879                    case ::gig::dimension_effect5depth:
880                        DimValues[i] = pEngineChannel->ControllerTable[95];
881                        break;
882                    case ::gig::dimension_none:
883                        std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
884                        break;
885                    default:
886                        std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
887                }
888            }
889            ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
890    
891            // no need to continue if sample is silent
892            if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
893    
894          // allocate a new voice for the key          // allocate a new voice for the key
895          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
896          if (itNewVoice) {          if (itNewVoice) {
897              // launch the new voice              // launch the new voice
898              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pEngineChannel->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
899                  dmsg(4,("Voice not triggered\n"));                  dmsg(4,("Voice not triggered\n"));
900                  pKey->pActiveVoices->free(itNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
901              }              }
902              else { // on success              else { // on success
903                  uint** ppKeyGroup = NULL;                  --VoiceSpawnsLeft;
                 if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group  
                     ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];  
                     if (*ppKeyGroup) { // if there's already an active key in that key group  
                         midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];  
                         // kill all voices on the (other) key  
                         RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();  
                         RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();  
                         for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {  
                             if (itVoiceToBeKilled->Type != Voice::type_release_trigger) itVoiceToBeKilled->Kill(itNoteOnEvent);  
                         }  
                     }  
                 }  
904                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
905                      pKey->Active = true;                      pKey->Active = true;
906                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
907                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
908                  }                  }
909                  if (itNewVoice->KeyGroup) {                  if (itNewVoice->KeyGroup) {
910                        uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
911                      *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group                      *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
912                  }                  }
913                  if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)                  if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
# Line 780  namespace LinuxSampler { namespace gig { Line 944  namespace LinuxSampler { namespace gig {
944       *  @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing       *  @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
945       */       */
946      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
947          if (!VoiceTheftsLeft) {          if (VoiceSpawnsLeft <= 0) {
948              dmsg(1,("Max. voice thefts per audio fragment reached (you may raise MAX_AUDIO_VOICES).\n"));              dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
949              return -1;              return -1;
950          }          }
951          if (!pEventPool->poolIsEmpty()) {          if (!pEventPool->poolIsEmpty()) {
# Line 789  namespace LinuxSampler { namespace gig { Line 953  namespace LinuxSampler { namespace gig {
953              RTList<Voice>::Iterator itSelectedVoice;              RTList<Voice>::Iterator itSelectedVoice;
954    
955              // Select one voice for voice stealing              // Select one voice for voice stealing
956              switch (VOICE_STEAL_ALGORITHM) {              switch (CONFIG_VOICE_STEAL_ALGO) {
957    
958                  // try to pick the oldest voice on the key where the new                  // try to pick the oldest voice on the key where the new
959                  // voice should be spawned, if there is no voice on that                  // voice should be spawned, if there is no voice on that
960                  // key, or no voice left to kill there, then procceed with                  // key, or no voice left to kill, then procceed with
961                  // 'oldestkey' algorithm                  // 'oldestkey' algorithm
962                  case voice_steal_algo_oldestvoiceonkey: {                  case voice_steal_algo_oldestvoiceonkey: {
                 #if 0 // FIXME: broken  
963                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
964                      if (this->itLastStolenVoice) {                      itSelectedVoice = pSelectedKey->pActiveVoices->first();
965                          itSelectedVoice = this->itLastStolenVoice;                      // proceed iterating if voice was created in this fragment cycle
966                          ++itSelectedVoice;                      while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
967                      }                      // if we haven't found a voice then proceed with algorithm 'oldestkey'
968                      else { // no voice stolen in this audio fragment cycle yet                      if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
                         itSelectedVoice = pSelectedKey->pActiveVoices->first();  
                     }  
                     if (itSelectedVoice) {  
                         iuiSelectedKey = pSelectedKey->itSelf;  
                         break; // selection succeeded  
                     }  
                 #endif  
969                  } // no break - intentional !                  } // no break - intentional !
970    
971                  // try to pick the oldest voice on the oldest active key                  // try to pick the oldest voice on the oldest active key
972                    // from the same engine channel
973                  // (caution: must stay after 'oldestvoiceonkey' algorithm !)                  // (caution: must stay after 'oldestvoiceonkey' algorithm !)
974                  case voice_steal_algo_oldestkey: {                  case voice_steal_algo_oldestkey: {
975                        // if we already stole in this fragment, try to proceed on same key
976                      if (this->itLastStolenVoice) {                      if (this->itLastStolenVoice) {
977                          itSelectedVoice = this->itLastStolenVoice;                          itSelectedVoice = this->itLastStolenVoice;
978                          ++itSelectedVoice;                          do {
979                          if (itSelectedVoice) break; // selection succeeded                              ++itSelectedVoice;
980                          RTList<uint>::Iterator iuiSelectedKey = this->iuiLastStolenKey;                          } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
981                          ++iuiSelectedKey;                          // found a "stealable" voice ?
982                          if (iuiSelectedKey) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
983                              this->iuiLastStolenKey = iuiSelectedKey;                              // remember which voice we stole, so we can simply proceed on next voice stealing
984                              midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];                              this->itLastStolenVoice = itSelectedVoice;
985                              itSelectedVoice = pSelectedKey->pActiveVoices->first();                              break; // selection succeeded
986                            }
987                        }
988                        // get (next) oldest key
989                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
990                        while (iuiSelectedKey) {
991                            midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
992                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
993                            // proceed iterating if voice was created in this fragment cycle
994                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
995                            // found a "stealable" voice ?
996                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
997                                // remember which voice on which key we stole, so we can simply proceed on next voice stealing
998                                this->iuiLastStolenKey  = iuiSelectedKey;
999                                this->itLastStolenVoice = itSelectedVoice;
1000                              break; // selection succeeded                              break; // selection succeeded
1001                          }                          }
1002                            ++iuiSelectedKey; // get next oldest key
1003                      }                      }
1004                      break;                      break;
1005                  }                  }
# Line 839  namespace LinuxSampler { namespace gig { Line 1012  namespace LinuxSampler { namespace gig {
1012                  }                  }
1013              }              }
1014    
1015              // steal oldest voice on the oldest key from this or any other engine channel              // if we couldn't steal a voice from the same engine channel then
1016              if (!itSelectedVoice) {              // steal oldest voice on the oldest key from any other engine channel
1017                  EngineChannel* pSelectedChannel = (pLastStolenChannel) ? pLastStolenChannel : pEngineChannel;              // (the smaller engine channel number, the higher priority)
1018                  int iChannelIndex = pSelectedChannel->iEngineIndexSelf;              if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1019                  while (true) {                  EngineChannel* pSelectedChannel;
1020                      RTList<uint>::Iterator iuiSelectedKey = pSelectedChannel->pActiveKeys->first();                  int            iChannelIndex;
1021                      if (iuiSelectedKey) {                  // select engine channel
1022                    if (pLastStolenChannel) {
1023                        pSelectedChannel = pLastStolenChannel;
1024                        iChannelIndex    = pSelectedChannel->iEngineIndexSelf;
1025                    } else { // pick the engine channel followed by this engine channel
1026                        iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1027                        pSelectedChannel = engineChannels[iChannelIndex];
1028                    }
1029    
1030                    // if we already stole in this fragment, try to proceed on same key
1031                    if (this->itLastStolenVoiceGlobally) {
1032                        itSelectedVoice = this->itLastStolenVoiceGlobally;
1033                        do {
1034                            ++itSelectedVoice;
1035                        } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1036                    }
1037    
1038                    #if CONFIG_DEVMODE
1039                    EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1040                    #endif // CONFIG_DEVMODE
1041    
1042                    // did we find a 'stealable' voice?
1043                    if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1044                        // remember which voice we stole, so we can simply proceed on next voice stealing
1045                        this->itLastStolenVoiceGlobally = itSelectedVoice;
1046                    } else while (true) { // iterate through engine channels
1047                        // get (next) oldest key
1048                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1049                        this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1050                        while (iuiSelectedKey) {
1051                          midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];                          midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1052                          itSelectedVoice    = pSelectedKey->pActiveVoices->first();                          itSelectedVoice = pSelectedKey->pActiveVoices->first();
1053                          iuiLastStolenKey   = iuiSelectedKey;                          // proceed iterating if voice was created in this fragment cycle
1054                          pLastStolenChannel = pSelectedChannel;                          while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1055                          break; // selection succeeded                          // found a "stealable" voice ?
1056                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1057                                // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1058                                this->iuiLastStolenKeyGlobally  = iuiSelectedKey;
1059                                this->itLastStolenVoiceGlobally = itSelectedVoice;
1060                                this->pLastStolenChannel        = pSelectedChannel;
1061                                goto stealable_voice_found; // selection succeeded
1062                            }
1063                            ++iuiSelectedKey; // get next key on current engine channel
1064                      }                      }
1065                        // get next engine channel
1066                      iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();                      iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
1067                      pSelectedChannel =  engineChannels[iChannelIndex];                      pSelectedChannel = engineChannels[iChannelIndex];
1068    
1069                        #if CONFIG_DEVMODE
1070                        if (pSelectedChannel == pBegin) {
1071                            dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1072                            dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1073                            dmsg(1,("Exiting.\n"));
1074                            exit(-1);
1075                        }
1076                        #endif // CONFIG_DEVMODE
1077                  }                  }
1078              }              }
1079    
1080              //FIXME: can be removed, just a sanity check for debugging              // jump point if a 'stealable' voice was found
1081                stealable_voice_found:
1082    
1083                #if CONFIG_DEVMODE
1084              if (!itSelectedVoice->IsActive()) {              if (!itSelectedVoice->IsActive()) {
1085                  dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));                  dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
1086                  return -1;                  return -1;
1087              }              }
1088                #endif // CONFIG_DEVMODE
1089    
1090              // now kill the selected voice              // now kill the selected voice
1091              itSelectedVoice->Kill(itNoteOnEvent);              itSelectedVoice->Kill(itNoteOnEvent);
1092    
1093              // remember which voice we stole, so we can simply proceed for the next voice stealing              --VoiceSpawnsLeft;
             itLastStolenVoice = itSelectedVoice;  
   
             --VoiceTheftsLeft;  
1094    
1095              return 0; // success              return 0; // success
1096          }          }
# Line 945  namespace LinuxSampler { namespace gig { Line 1166  namespace LinuxSampler { namespace gig {
1166              case 7: { // volume              case 7: { // volume
1167                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1168                  pEngineChannel->GlobalVolume = (float) itControlChangeEventOnCCList->Param.CC.Value / 127.0f;                  pEngineChannel->GlobalVolume = (float) itControlChangeEventOnCCList->Param.CC.Value / 127.0f;
1169                    pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1170                  break;                  break;
1171              }              }
1172              case 10: { // panpot              case 10: { // panpot
# Line 1027  namespace LinuxSampler { namespace gig { Line 1249  namespace LinuxSampler { namespace gig {
1249    
1250          switch (id) {          switch (id) {
1251              case 0x41: { // Roland              case 0x41: { // Roland
1252                    dmsg(3,("Roland Sysex\n"));
1253                  uint8_t device_id, model_id, cmd_id;                  uint8_t device_id, model_id, cmd_id;
1254                  if (!reader.pop(&device_id)) goto free_sysex_data;                  if (!reader.pop(&device_id)) goto free_sysex_data;
1255                  if (!reader.pop(&model_id))  goto free_sysex_data;                  if (!reader.pop(&model_id))  goto free_sysex_data;
# Line 1039  namespace LinuxSampler { namespace gig { Line 1262  namespace LinuxSampler { namespace gig {
1262                  const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later                  const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1263                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1264                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1265                        dmsg(3,("\tSystem Parameter\n"));
1266                  }                  }
1267                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1268                        dmsg(3,("\tCommon Parameter\n"));
1269                  }                  }
1270                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1271                      switch (addr[3]) {                      dmsg(3,("\tPart Parameter\n"));
1272                        switch (addr[2]) {
1273                          case 0x40: { // scale tuning                          case 0x40: { // scale tuning
1274                                dmsg(3,("\t\tScale Tuning\n"));
1275                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1276                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1277                              uint8_t checksum;                              uint8_t checksum;
1278                              if (!reader.pop(&checksum))                      goto free_sysex_data;                              if (!reader.pop(&checksum)) goto free_sysex_data;
1279                              if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;                              #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1280                                if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
1281                                #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1282                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1283                              AdjustScale((int8_t*) scale_tunes);                              AdjustScale((int8_t*) scale_tunes);
1284                                dmsg(3,("\t\t\tNew scale applied.\n"));
1285                              break;                              break;
1286                          }                          }
1287                      }                      }
# Line 1136  namespace LinuxSampler { namespace gig { Line 1366  namespace LinuxSampler { namespace gig {
1366              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1367              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1368                  itVoice->Kill(itKillEvent);                  itVoice->Kill(itKillEvent);
1369                    --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1370              }              }
1371          }          }
1372      }      }
# Line 1184  namespace LinuxSampler { namespace gig { Line 1415  namespace LinuxSampler { namespace gig {
1415      }      }
1416    
1417      String Engine::EngineName() {      String Engine::EngineName() {
1418          return "GigEngine";          return LS_GIG_ENGINE_NAME;
1419      }      }
1420    
1421      String Engine::Description() {      String Engine::Description() {
# Line 1192  namespace LinuxSampler { namespace gig { Line 1423  namespace LinuxSampler { namespace gig {
1423      }      }
1424    
1425      String Engine::Version() {      String Engine::Version() {
1426          String s = "$Revision: 1.33 $";          String s = "$Revision: 1.49 $";
1427          return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword          return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1428      }      }
1429    

Legend:
Removed from v.473  
changed lines
  Added in v.690

  ViewVC Help
Powered by ViewVC