/[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 285 by schoenebeck, Thu Oct 14 21:31:26 2004 UTC revision 392 by schoenebeck, Sat Feb 19 02:40:24 2005 UTC
# Line 27  Line 27 
27    
28  #include "Engine.h"  #include "Engine.h"
29    
30    #if defined(__APPLE__)
31    # include <stdlib.h>
32    #else
33    # include <malloc.h>
34    #endif
35    
36  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
37    
38      InstrumentResourceManager Engine::Instruments;      InstrumentResourceManager Engine::Instruments;
# Line 76  namespace LinuxSampler { namespace gig { Line 82  namespace LinuxSampler { namespace gig {
82    
83      Engine::~Engine() {      Engine::~Engine() {
84          if (pDiskThread) {          if (pDiskThread) {
85                dmsg(1,("Stopping disk thread..."));
86              pDiskThread->StopThread();              pDiskThread->StopThread();
87              delete pDiskThread;              delete pDiskThread;
88                dmsg(1,("OK\n"));
89          }          }
90    
91            if (pInstrument) Instruments.HandBack(pInstrument, this);
92    
93          if (pGig)  delete pGig;          if (pGig)  delete pGig;
94          if (pRIFF) delete pRIFF;          if (pRIFF) delete pRIFF;
95          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
# Line 88  namespace LinuxSampler { namespace gig { Line 99  namespace LinuxSampler { namespace gig {
99          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
100              if (pSynthesisEvents[i]) delete pSynthesisEvents[i];              if (pSynthesisEvents[i]) delete pSynthesisEvents[i];
101          }          }
         delete[] pSynthesisEvents;  
102          if (pEvents)     delete pEvents;          if (pEvents)     delete pEvents;
103          if (pCCEvents)   delete pCCEvents;          if (pCCEvents)   delete pCCEvents;
104          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
105          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
106          if (pVoicePool)  delete pVoicePool;          if (pVoicePool) {
107                    pVoicePool->clear();
108                    delete pVoicePool;
109            }
110          if (pActiveKeys) delete pActiveKeys;          if (pActiveKeys) delete pActiveKeys;
111          if (pSysexBuffer) delete pSysexBuffer;          if (pSysexBuffer) delete pSysexBuffer;
112          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
113          if (pMainFilterParameters) delete[] pMainFilterParameters;          if (pMainFilterParameters) delete[] pMainFilterParameters;
114          if (pBasicFilterParameters) delete[] pBasicFilterParameters;          if (pBasicFilterParameters) delete[] pBasicFilterParameters;
115          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
116          if (pVoiceStealingQueue) delete pVoiceStealingQueue;          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
117      }      }
118    
# Line 158  namespace LinuxSampler { namespace gig { Line 171  namespace LinuxSampler { namespace gig {
171          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
172          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
173          GlobalVolume        = 1.0;          GlobalVolume        = 1.0;
174            CurrentKeyDimension = 0;
175    
176          // reset voice stealing parameters          // reset voice stealing parameters
177          itLastStolenVoice = RTList<Voice>::Iterator();          itLastStolenVoice = RTList<Voice>::Iterator();
# Line 201  namespace LinuxSampler { namespace gig { Line 215  namespace LinuxSampler { namespace gig {
215      }      }
216    
217      /**      /**
218       *  Load an instrument from a .gig file.       * More or less a workaround to set the instrument name, index and load
219         * status variable to zero percent immediately, that is without blocking
220         * the calling thread. It might be used in future for other preparations
221         * as well though.
222         *
223         * @param FileName   - file name of the Gigasampler instrument file
224         * @param Instrument - index of the instrument in the .gig file
225         * @see LoadInstrument()
226         */
227        void Engine::PrepareLoadInstrument(const char* FileName, uint Instrument) {
228            InstrumentFile = FileName;
229            InstrumentIdx  = Instrument;
230            InstrumentStat = 0;
231        }
232    
233        /**
234         * Load an instrument from a .gig file. PrepareLoadInstrument() has to
235         * be called first to provide the information which instrument to load.
236         * This method will then actually start to load the instrument and block
237         * the calling thread until loading was completed.
238       *       *
239       *  @param FileName   - file name of the Gigasampler instrument file       * @returns detailed description of the method call result
240       *  @param Instrument - index of the instrument in the .gig file       * @see PrepareLoadInstrument()
      *  @throws LinuxSamplerException  on error  
      *  @returns          detailed description of the method call result  
241       */       */
242      void Engine::LoadInstrument(const char* FileName, uint Instrument) {      void Engine::LoadInstrument() {
243    
244          DisableAndLock();          DisableAndLock();
245    
# Line 220  namespace LinuxSampler { namespace gig { Line 251  namespace LinuxSampler { namespace gig {
251              Instruments.HandBack(pInstrument, this);              Instruments.HandBack(pInstrument, this);
252          }          }
253    
         InstrumentFile = FileName;  
         InstrumentIdx = Instrument;  
         InstrumentStat = 0;  
   
254          // delete all key groups          // delete all key groups
255          ActiveKeyGroups.clear();          ActiveKeyGroups.clear();
256    
257          // request gig instrument from instrument manager          // request gig instrument from instrument manager
258          try {          try {
259              instrument_id_t instrid;              instrument_id_t instrid;
260              instrid.FileName    = FileName;              instrid.FileName    = InstrumentFile;
261              instrid.iInstrument = Instrument;              instrid.iInstrument = InstrumentIdx;
262              pInstrument = Instruments.Borrow(instrid, this);              pInstrument = Instruments.Borrow(instrid, this);
263              if (!pInstrument) {              if (!pInstrument) {
264                  InstrumentStat = -1;                  InstrumentStat = -1;
# Line 258  namespace LinuxSampler { namespace gig { Line 285  namespace LinuxSampler { namespace gig {
285          for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())          for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())
286              if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;              if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;
287    
288            InstrumentIdxName = pInstrument->pInfo->Name;
289          InstrumentStat = 100;          InstrumentStat = 100;
290    
291          // inform audio driver for the need of two channels          // inform audio driver for the need of two channels
# Line 321  namespace LinuxSampler { namespace gig { Line 349  namespace LinuxSampler { namespace gig {
349    
350          // (re)create disk thread          // (re)create disk thread
351          if (this->pDiskThread) {          if (this->pDiskThread) {
352                dmsg(1,("Stopping disk thread..."));
353              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
354              delete this->pDiskThread;              delete this->pDiskThread;
355                dmsg(1,("OK\n"));
356          }          }
357          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo
358          if (!pDiskThread) {          if (!pDiskThread) {
# Line 341  namespace LinuxSampler { namespace gig { Line 371  namespace LinuxSampler { namespace gig {
371          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
372    
373          // (re)allocate synthesis parameter matrix          // (re)allocate synthesis parameter matrix
374          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
375          pSynthesisParameters[0] = new float[Event::destination_count * pAudioOut->MaxSamplesPerCycle()];  
376            #if defined(__APPLE__)
377            pSynthesisParameters[0] = (float *) malloc(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle());
378            #else
379            pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));
380            #endif
381          for (int dst = 1; dst < Event::destination_count; dst++)          for (int dst = 1; dst < Event::destination_count; dst++)
382              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();
383    
# Line 398  namespace LinuxSampler { namespace gig { Line 433  namespace LinuxSampler { namespace gig {
433          }          }
434    
435    
436            // update time of start and end of this audio fragment (as events' time stamps relate to this)
437            pEventGenerator->UpdateFragmentTime(Samples);
438    
439    
440          // empty the event lists for the new fragment          // empty the event lists for the new fragment
441          pEvents->clear();          pEvents->clear();
442          pCCEvents->clear();          pCCEvents->clear();
# Line 412  namespace LinuxSampler { namespace gig { Line 451  namespace LinuxSampler { namespace gig {
451              }              }
452          }          }
453    
         // read and copy events from input queue  
         Event event = pEventGenerator->CreateEvent();  
         while (true) {  
             if (!pEventQueue->pop(&event) || pEvents->poolIsEmpty()) break;  
             *pEvents->allocAppend() = event;  
         }  
   
454    
455          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // get all events from the input event queue which belong to the current fragment
456          pEventGenerator->UpdateFragmentTime(Samples);          {
457                RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
458                Event* pEvent;
459                while (true) {
460                    // get next event from input event queue
461                    if (!(pEvent = eventQueueReader.pop())) break;
462                    // if younger event reached, ignore that and all subsequent ones for now
463                    if (pEvent->FragmentPos() >= Samples) {
464                        eventQueueReader--;
465                        dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
466                        pEvent->ResetFragmentPos();
467                        break;
468                    }
469                    // copy event to internal event list
470                    if (pEvents->poolIsEmpty()) {
471                        dmsg(1,("Event pool emtpy!\n"));
472                        break;
473                    }
474                    *pEvents->allocAppend() = *pEvent;
475                }
476                eventQueueReader.free(); // free all copied events from input queue
477            }
478    
479    
480          // process events          // process events
# Line 494  namespace LinuxSampler { namespace gig { Line 547  namespace LinuxSampler { namespace gig {
547                          }                          }
548                      }                      }
549                  }                  }
550                  else dmsg(1,("Ouch, voice stealing didn't work out!\n"));                  else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
551              }              }
552          }          }
553          // reset voice stealing for the new fragment          // reset voice stealing for the new fragment
# Line 503  namespace LinuxSampler { namespace gig { Line 556  namespace LinuxSampler { namespace gig {
556          iuiLastStolenKey  = RTList<uint>::Iterator();          iuiLastStolenKey  = RTList<uint>::Iterator();
557    
558    
559            // free all keys which have no active voices left
560            {
561                RTList<uint>::Iterator iuiKey = pActiveKeys->first();
562                RTList<uint>::Iterator end    = pActiveKeys->end();
563                while (iuiKey != end) { // iterate through all active keys
564                    midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
565                    ++iuiKey;
566                    if (pKey->pActiveVoices->isEmpty()) FreeKey(pKey);
567                    #if DEVMODE
568                    else { // FIXME: should be removed before the final release (purpose: just a sanity check for debugging)
569                        RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
570                        RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
571                        for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
572                            if (itVoice->itKillEvent) {
573                                dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
574                            }
575                        }
576                    }
577                    #endif // DEVMODE
578                }
579            }
580    
581    
582          // write that to the disk thread class so that it can print it          // write that to the disk thread class so that it can print it
583          // on the console for debugging purposes          // on the console for debugging purposes
584          ActiveVoiceCount = active_voices;          ActiveVoiceCount = active_voices;
# Line 611  namespace LinuxSampler { namespace gig { Line 687  namespace LinuxSampler { namespace gig {
687       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
688       */       */
689      void Engine::ProcessNoteOn(Pool<Event>::Iterator& itNoteOnEvent) {      void Engine::ProcessNoteOn(Pool<Event>::Iterator& itNoteOnEvent) {
690          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];  
691            const int key = itNoteOnEvent->Param.Note.Key;
692    
693            // Change key dimension value if key is in keyswitching area
694            if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
695                CurrentKeyDimension = ((key - pInstrument->DimensionKeyRange.low) * 128) /
696                    (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
697    
698            midi_key_info_t* pKey = &pMIDIKeyInfo[key];
699    
700          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
701    
# Line 629  namespace LinuxSampler { namespace gig { Line 713  namespace LinuxSampler { namespace gig {
713          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
714    
715          // allocate and trigger a new voice for the key          // allocate and trigger a new voice for the key
716          LaunchVoice(itNoteOnEventOnKeyList);          LaunchVoice(itNoteOnEventOnKeyList, 0, false, true);
717      }      }
718    
719      /**      /**
# Line 655  namespace LinuxSampler { namespace gig { Line 739  namespace LinuxSampler { namespace gig {
739    
740          // spawn release triggered voice(s) if needed          // spawn release triggered voice(s) if needed
741          if (pKey->ReleaseTrigger) {          if (pKey->ReleaseTrigger) {
742              LaunchVoice(itNoteOffEventOnKeyList, 0, true);              LaunchVoice(itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
743              pKey->ReleaseTrigger = false;              pKey->ReleaseTrigger = false;
744          }          }
745      }      }
# Line 685  namespace LinuxSampler { namespace gig { Line 769  namespace LinuxSampler { namespace gig {
769       *                               when there is no free voice       *                               when there is no free voice
770       *                               (optional, default = true)       *                               (optional, default = true)
771       *  @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
772       *           if an error occured while trying to trigger the new voice       *           if the voice wasn't triggered (for example when no region is
773         *           defined for the given key).
774       */       */
775      Pool<Voice>::Iterator Engine::LaunchVoice(Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {      Pool<Voice>::Iterator Engine::LaunchVoice(Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {
776          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
# Line 694  namespace LinuxSampler { namespace gig { Line 779  namespace LinuxSampler { namespace gig {
779          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
780          if (itNewVoice) {          if (itNewVoice) {
781              // launch the new voice              // launch the new voice
782              if (itNewVoice->Trigger(itNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice) < 0) {              if (itNewVoice->Trigger(itNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {
783                  dmsg(1,("Triggering new voice failed!\n"));                  dmsg(4,("Voice not triggered\n"));
784                  pKey->pActiveVoices->free(itNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
785              }              }
786              else { // on success              else { // on success
# Line 820  namespace LinuxSampler { namespace gig { Line 905  namespace LinuxSampler { namespace gig {
905                  }                  }
906              }              }
907    
908                //FIXME: can be removed, just a sanity check for debugging
909                if (!itOldestVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
910    
911              // now kill the selected voice              // now kill the selected voice
912              itOldestVoice->Kill(itNoteOnEvent);              itOldestVoice->Kill(itNoteOnEvent);
913              // remember which voice on which key we stole, so we can simply proceed for the next voice stealing              // remember which voice on which key we stole, so we can simply proceed for the next voice stealing
# Line 846  namespace LinuxSampler { namespace gig { Line 934  namespace LinuxSampler { namespace gig {
934              // free the voice object              // free the voice object
935              pVoicePool->free(itVoice);              pVoicePool->free(itVoice);
936    
937              // check if there are no voices left on the MIDI key and update the key info if so              // if no other voices left and member of a key group, remove from key group
938              if (pKey->pActiveVoices->isEmpty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
939                  if (keygroup) { // if voice / key belongs to a key group                  uint** ppKeyGroup = &ActiveKeyGroups[keygroup];
940                      uint** ppKeyGroup = &ActiveKeyGroups[keygroup];                  if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
                     if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group  
                 }  
                 pKey->Active = false;  
                 pActiveKeys->free(pKey->itSelf); // remove key from list of active keys  
                 pKey->itSelf = RTList<uint>::Iterator();  
                 pKey->ReleaseTrigger = false;  
                 pKey->pEvents->clear();  
                 dmsg(3,("Key has no more voices now\n"));  
941              }              }
942          }          }
943          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
944      }      }
945    
946      /**      /**
947         *  Called when there's no more voice left on a key, this call will
948         *  update the key info respectively.
949         *
950         *  @param pKey - key which is now inactive
951         */
952        void Engine::FreeKey(midi_key_info_t* pKey) {
953            if (pKey->pActiveVoices->isEmpty()) {
954                pKey->Active = false;
955                pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
956                pKey->itSelf = RTList<uint>::Iterator();
957                pKey->ReleaseTrigger = false;
958                pKey->pEvents->clear();
959                dmsg(3,("Key has no more voices now\n"));
960            }
961            else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
962        }
963    
964        /**
965       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
966       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
967       *       *
# Line 1097  namespace LinuxSampler { namespace gig { Line 1195  namespace LinuxSampler { namespace gig {
1195          return InstrumentFile;          return InstrumentFile;
1196      }      }
1197    
1198        String Engine::InstrumentName() {
1199            return InstrumentIdxName;
1200        }
1201    
1202      int Engine::InstrumentIndex() {      int Engine::InstrumentIndex() {
1203          return InstrumentIdx;          return InstrumentIdx;
1204      }      }
# Line 1110  namespace LinuxSampler { namespace gig { Line 1212  namespace LinuxSampler { namespace gig {
1212      }      }
1213    
1214      String Engine::Version() {      String Engine::Version() {
1215          String s = "$Revision: 1.16 $";          String s = "$Revision: 1.25 $";
1216          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
1217      }      }
1218    

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

  ViewVC Help
Powered by ViewVC