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

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

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

revision 554 by schoenebeck, Thu May 19 19:25:14 2005 UTC revision 2277 by persson, Sat Oct 1 08:23:02 2011 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
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                              *   *   Copyright (C) 2005-2008 Christian Schoenebeck                         *
7     *   Copyright (C) 2009-2011 Christian Schoenebeck and Grigor Iliev        *
8   *                                                                         *   *                                                                         *
9   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
10   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 22  Line 23 
23   ***************************************************************************/   ***************************************************************************/
24    
25  #include "EngineChannel.h"  #include "EngineChannel.h"
26    #include "Engine.h"
27    
28  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
   
29      EngineChannel::EngineChannel() {      EngineChannel::EngineChannel() {
30          pMIDIKeyInfo = new midi_key_info_t[128];          
         pEngine      = NULL;  
         pInstrument  = NULL;  
         pEvents      = NULL; // we allocate when we retrieve the right Engine object  
         pCCEvents    = NULL; // we allocate when we retrieve the right Engine object  
         pEventQueue  = new RingBuffer<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);  
         pActiveKeys  = new Pool<uint>(128);  
         for (uint i = 0; i < 128; i++) {  
             pMIDIKeyInfo[i].pActiveVoices  = NULL; // we allocate when we retrieve the right Engine object  
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].pEvents        = NULL; // we allocate when we retrieve the right Engine object  
             pMIDIKeyInfo[i].VoiceTheftsQueued = 0;  
             pMIDIKeyInfo[i].RoundRobinIndex = 0;  
         }  
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i] = NULL; // we allocate when we retrieve the right Engine object  
         }  
         InstrumentIdx  = -1;  
         InstrumentStat = -1;  
         AudioDeviceChannelLeft  = -1;  
         AudioDeviceChannelRight = -1;  
31      }      }
32    
33      EngineChannel::~EngineChannel() {      EngineChannel::~EngineChannel() {
34          DisconnectAudioOutputDevice();          DisconnectAudioOutputDevice();
35          if (pInstrument) Engine::instruments.HandBack(pInstrument, this);          // In case the channel was removed before the instrument was
36          if (pEventQueue) delete pEventQueue;          // fully loaded, try to give back instrument again (see bug #113)
37          if (pActiveKeys) delete pActiveKeys;          InstrumentChangeCmd< ::gig::DimensionRegion, ::gig::Instrument>& cmd = ChangeInstrument(NULL);
38          if (pMIDIKeyInfo) delete[] pMIDIKeyInfo;          if (cmd.pInstrument) {
39                Engine::instruments.HandBack(cmd.pInstrument, this);
40            }
41            ///////
42      }      }
43    
44      /**      AbstractEngine::Format EngineChannel::GetEngineFormat() { return AbstractEngine::GIG; }
45       * This method is not thread safe!  
46       */      /** This method is not thread safe! */
47      void EngineChannel::ResetInternal() {      void EngineChannel::ResetInternal() {
         Pitch               = 0;  
         SustainPedal        = false;  
         GlobalVolume        = 1.0;  
         GlobalPanLeft       = 1.0f;  
         GlobalPanRight      = 1.0f;  
48          CurrentKeyDimension = 0;          CurrentKeyDimension = 0;
49            EngineChannelBase<Voice, ::gig::DimensionRegion, ::gig::Instrument>::ResetInternal();
         ResetControllers();  
   
         // reset key info  
         for (uint i = 0; i < 128; i++) {  
             if (pMIDIKeyInfo[i].pActiveVoices)  
                 pMIDIKeyInfo[i].pActiveVoices->clear();  
             if (pMIDIKeyInfo[i].pEvents)  
                 pMIDIKeyInfo[i].pEvents->clear();  
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].itSelf         = Pool<uint>::Iterator();  
             pMIDIKeyInfo[i].VoiceTheftsQueued = 0;  
         }  
   
         // reset all key groups  
         std::map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();  
         for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;  
   
         // free all active keys  
         pActiveKeys->clear();  
   
         // delete all input events  
         pEventQueue->init();  
   
         if (pEngine) pEngine->ResetInternal();  
     }  
   
     LinuxSampler::Engine* EngineChannel::GetEngine() {  
         return pEngine;  
50      }      }
51    
52      /**      /**
53       * More or less a workaround to set the instrument name, index and load       *  Will be called by the MIDIIn Thread to signal that a program
54       * status variable to zero percent immediately, that is without blocking       *  change should be performed. As a program change isn't
55       * the calling thread. It might be used in future for other preparations       *  real-time safe, the actual change is performed by the disk
56       * as well though.       *  thread.
57       *       *
58       * @param FileName   - file name of the Gigasampler instrument file       *  @param Program     - MIDI program change number
      * @param Instrument - index of the instrument in the .gig file  
      * @see LoadInstrument()  
59       */       */
60      void EngineChannel::PrepareLoadInstrument(const char* FileName, uint Instrument) {      void EngineChannel::SendProgramChange(uint8_t Program) {
61          InstrumentFile = FileName;          SetMidiProgram(Program);
62          InstrumentIdx  = Instrument;          Engine* engine = dynamic_cast<Engine*>(pEngine);
63          InstrumentStat = 0;          if(engine == NULL) return;
64    
65            if(engine->GetDiskThread()) {
66                uint32_t merged = (GetMidiBankMsb() << 16) | (GetMidiBankLsb() << 8) | Program;
67                engine->GetDiskThread()->OrderProgramChange(merged, this);
68            } else {
69                // TODO:
70            }
71      }      }
72    
73      /**      /**
# Line 124  namespace LinuxSampler { namespace gig { Line 76  namespace LinuxSampler { namespace gig {
76       * This method will then actually start to load the instrument and block       * This method will then actually start to load the instrument and block
77       * the calling thread until loading was completed.       * the calling thread until loading was completed.
78       *       *
      * @returns detailed description of the method call result  
79       * @see PrepareLoadInstrument()       * @see PrepareLoadInstrument()
80       */       */
81      void EngineChannel::LoadInstrument() {      void EngineChannel::LoadInstrument() {
82            InstrumentResourceManager* pInstrumentManager = dynamic_cast<InstrumentResourceManager*>(pEngine->GetInstrumentManager());
83    
84          if (pEngine) pEngine->DisableAndLock();          // make sure we don't trigger any new notes with an old
85            // instrument
86          ResetInternal();          InstrumentChangeCmd< ::gig::DimensionRegion, ::gig::Instrument>& cmd = ChangeInstrument(0);
87            if (cmd.pInstrument) {
88          // free old instrument              // give old instrument back to instrument manager, but
89          if (pInstrument) {              // keep the dimension regions and samples that are in use
90              // give old instrument back to instrument manager              pInstrumentManager->HandBackInstrument(cmd.pInstrument, this, cmd.pRegionsInUse);
             Engine::instruments.HandBack(pInstrument, this);  
91          }          }
92            cmd.pRegionsInUse->clear();
93    
94          // delete all key groups          // delete all key groups
95          ActiveKeyGroups.clear();          DeleteGroupEventLists();
96    
97          // request gig instrument from instrument manager          // request gig instrument from instrument manager
98            ::gig::Instrument* newInstrument;
99          try {          try {
100              instrument_id_t instrid;              InstrumentManager::instrument_id_t instrid;
101              instrid.FileName    = InstrumentFile;              instrid.FileName  = InstrumentFile;
102              instrid.iInstrument = InstrumentIdx;              instrid.Index     = InstrumentIdx;
103              pInstrument = Engine::instruments.Borrow(instrid, this);  
104              if (!pInstrument) {              newInstrument = pInstrumentManager->Borrow(instrid, this);
105                  InstrumentStat = -1;              if (!newInstrument) {
106                  dmsg(1,("no instrument loaded!!!\n"));                  throw InstrumentManagerException("resource was not created");
                 exit(EXIT_FAILURE);  
107              }              }
108          }          }
109          catch (RIFF::Exception e) {          catch (RIFF::Exception e) {
110              InstrumentStat = -2;              InstrumentStat = -2;
111                StatusChanged(true);
112              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
113              throw LinuxSamplerException(msg);              throw Exception(msg);
114          }          }
115          catch (InstrumentResourceManagerException e) {          catch (InstrumentManagerException e) {
116              InstrumentStat = -3;              InstrumentStat = -3;
117                StatusChanged(true);
118              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
119              throw LinuxSamplerException(msg);              throw Exception(msg);
120          }          }
121          catch (...) {          catch (...) {
122              InstrumentStat = -4;              InstrumentStat = -4;
123              throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");              StatusChanged(true);
124          }              throw Exception("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");
   
         // rebuild ActiveKeyGroups map with key groups of current instrument  
         for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())  
             if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;  
   
         InstrumentIdxName = pInstrument->pInfo->Name;  
         InstrumentStat = 100;  
   
         // inform audio driver for the need of two channels  
         try {  
             if (pEngine && pEngine->pAudioOutputDevice)  
                 pEngine->pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo  
125          }          }
         catch (AudioOutputException e) {  
             String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
   
         if (pEngine) pEngine->Enable();  
     }  
   
     /**  
      * Will be called by the InstrumentResourceManager when the instrument  
      * we are currently using on this EngineChannel is going to be updated,  
      * so we can stop playback before that happens.  
      */  
     void EngineChannel::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {  
         dmsg(3,("gig::Engine: Received instrument update message.\n"));  
         if (pEngine) pEngine->DisableAndLock();  
         ResetInternal();  
         this->pInstrument = NULL;  
     }  
126    
127      /**          RoundRobinIndex = 0;
128       * Will be called by the InstrumentResourceManager when the instrument          for (int i = 0 ; i < 128 ; i++) pMIDIKeyInfo[i].pRoundRobinIndex = NULL;
      * update process was completed, so we can continue with playback.  
      */  
     void EngineChannel::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {  
         this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())  
         if (pEngine) pEngine->Enable();  
     }  
   
     /**  
      * Will be called by the InstrumentResourceManager on progress changes  
      * while loading or realoading an instrument for this EngineChannel.  
      *  
      * @param fProgress - current progress as value between 0.0 and 1.0  
      */  
     void EngineChannel::OnResourceProgress(float fProgress) {  
         this->InstrumentStat = int(fProgress * 100.0f);  
         dmsg(7,("gig::EngineChannel: progress %d%", InstrumentStat));  
     }  
129    
130      void EngineChannel::Connect(AudioOutputDevice* pAudioOut) {          // rebuild ActiveKeyGroups map with key groups of current
131          if (pEngine) {          // instrument and set the round robin pointers to use one
132              if (pEngine->pAudioOutputDevice == pAudioOut) return;          // counter for each region
133              DisconnectAudioOutputDevice();          int region = 0;
134          }          for (::gig::Region* pRegion = newInstrument->GetFirstRegion(); pRegion; pRegion = newInstrument->GetNextRegion()) {
135          pEngine = Engine::AcquireEngine(this, pAudioOut);              AddGroup(pRegion->KeyGroup);
         ResetInternal();  
         pEvents   = new RTList<Event>(pEngine->pEventPool);  
         pCCEvents = new RTList<Event>(pEngine->pEventPool);  
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i] = new RTList<Event>(pEngine->pEventPool);  
         }  
         for (uint i = 0; i < 128; i++) {  
             pMIDIKeyInfo[i].pActiveVoices = new RTList<Voice>(pEngine->pVoicePool);  
             pMIDIKeyInfo[i].pEvents       = new RTList<Event>(pEngine->pEventPool);  
         }  
         AudioDeviceChannelLeft  = 0;  
         AudioDeviceChannelRight = 1;  
         pOutputLeft             = pAudioOut->Channel(0)->Buffer();  
         pOutputRight            = pAudioOut->Channel(1)->Buffer();  
     }  
136    
137      void EngineChannel::DisconnectAudioOutputDevice() {              RoundRobinIndexes[region] = 0;
138          if (pEngine) { // if clause to prevent disconnect loops              for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
139              ResetInternal();                  pMIDIKeyInfo[iKey].pRoundRobinIndex = &RoundRobinIndexes[region];
             if (pEvents) {  
                 delete pEvents;  
                 pEvents = NULL;  
             }  
             if (pCCEvents) {  
                 delete pCCEvents;  
                 pCCEvents = NULL;  
140              }              }
141              for (uint i = 0; i < 128; i++) {              region++;
                 if (pMIDIKeyInfo[i].pActiveVoices) {  
                     delete pMIDIKeyInfo[i].pActiveVoices;  
                     pMIDIKeyInfo[i].pActiveVoices = NULL;  
                 }  
                 if (pMIDIKeyInfo[i].pEvents) {  
                     delete pMIDIKeyInfo[i].pEvents;  
                     pMIDIKeyInfo[i].pEvents = NULL;  
                 }  
             }  
             for (uint i = 0; i < Event::destination_count; i++) {  
                 if (pSynthesisEvents[i]) {  
                     delete pSynthesisEvents[i];  
                     pSynthesisEvents[i] = NULL;  
                 }  
             }  
             Engine* oldEngine = pEngine;  
             AudioOutputDevice* oldAudioDevice = pEngine->pAudioOutputDevice;  
             pEngine = NULL;  
             Engine::FreeEngine(this, oldAudioDevice);  
             AudioDeviceChannelLeft  = -1;  
             AudioDeviceChannelRight = -1;  
         }  
     }  
   
     void EngineChannel::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {  
         if (!pEngine || !pEngine->pAudioOutputDevice) throw AudioOutputException("No audio output device connected yet.");  
   
         AudioChannel* pChannel = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannel);  
         if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));  
         switch (EngineAudioChannel) {  
             case 0: // left output channel  
                 pOutputLeft = pChannel->Buffer();  
                 AudioDeviceChannelLeft = AudioDeviceChannel;  
                 break;  
             case 1: // right output channel  
                 pOutputRight = pChannel->Buffer();  
                 AudioDeviceChannelRight = AudioDeviceChannel;  
                 break;  
             default:  
                 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));  
142          }          }
     }  
   
     int EngineChannel::OutputChannel(uint EngineAudioChannel) {  
         switch (EngineAudioChannel) {  
             case 0: // left channel  
                 return AudioDeviceChannelLeft;  
             case 1: // right channel  
                 return AudioDeviceChannelRight;  
             default:  
                 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));  
         }  
     }  
143    
144      /**          InstrumentIdxName = newInstrument->pInfo->Name;
145       *  Will be called by the MIDIIn Thread to let the audio thread trigger a new          InstrumentStat = 100;
      *  voice for the given key.  
      *  
      *  @param Key      - MIDI key number of the triggered key  
      *  @param Velocity - MIDI velocity value of the triggered key  
      */  
     void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity) {  
         if (pEngine) {  
             Event event               = pEngine->pEventGenerator->CreateEvent();  
             event.Type                = Event::type_note_on;  
             event.Param.Note.Key      = Key;  
             event.Param.Note.Velocity = Velocity;  
             event.pEngineChannel      = this;  
             if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);  
             else dmsg(1,("EngineChannel: Input event queue full!"));  
         }  
     }  
   
     /**  
      *  Will be called by the MIDIIn Thread to signal the audio thread to release  
      *  voice(s) on the given key.  
      *  
      *  @param Key      - MIDI key number of the released key  
      *  @param Velocity - MIDI release velocity value of the released key  
      */  
     void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity) {  
         if (pEngine) {  
             Event event               = pEngine->pEventGenerator->CreateEvent();  
             event.Type                = Event::type_note_off;  
             event.Param.Note.Key      = Key;  
             event.Param.Note.Velocity = Velocity;  
             event.pEngineChannel      = this;  
             if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);  
             else dmsg(1,("EngineChannel: Input event queue full!"));  
         }  
     }  
146    
147      /**          ChangeInstrument(newInstrument);
      *  Will be called by the MIDIIn Thread to signal the audio thread to change  
      *  the pitch value for all voices.  
      *  
      *  @param Pitch - MIDI pitch value (-8192 ... +8191)  
      */  
     void EngineChannel::SendPitchbend(int Pitch) {  
         if (pEngine) {  
             Event event             = pEngine->pEventGenerator->CreateEvent();  
             event.Type              = Event::type_pitchbend;  
             event.Param.Pitch.Pitch = Pitch;  
             event.pEngineChannel    = this;  
             if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);  
             else dmsg(1,("EngineChannel: Input event queue full!"));  
         }  
     }  
148    
149      /**          StatusChanged(true);
      *  Will be called by the MIDIIn Thread to signal the audio thread that a  
      *  continuous controller value has changed.  
      *  
      *  @param Controller - MIDI controller number of the occured control change  
      *  @param Value      - value of the control change  
      */  
     void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value) {  
         if (pEngine) {  
             Event event               = pEngine->pEventGenerator->CreateEvent();  
             event.Type                = Event::type_control_change;  
             event.Param.CC.Controller = Controller;  
             event.Param.CC.Value      = Value;  
             event.pEngineChannel      = this;  
             if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);  
             else dmsg(1,("EngineChannel: Input event queue full!"));  
         }  
150      }      }
151    
152      void EngineChannel::ClearEventLists() {      void EngineChannel::ProcessKeySwitchChange(int key) {
153          pEvents->clear();          // Change key dimension value if key is in keyswitching area
         pCCEvents->clear();  
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i]->clear();  
         }  
         // empty MIDI key specific event lists  
154          {          {
155              RTList<uint>::Iterator iuiKey = pActiveKeys->first();              if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
156              RTList<uint>::Iterator end    = pActiveKeys->end();                  CurrentKeyDimension = float(key - pInstrument->DimensionKeyRange.low) /
157              for(; iuiKey != end; ++iuiKey) {                      (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
                 pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key  
             }  
158          }          }
159      }      }
160    
     void EngineChannel::ResetControllers() {  
         // set all MIDI controller values to zero  
         memset(ControllerTable, 0x00, 128);  
     }  
   
     /**  
      * Copy all events from the engine channel's input event queue buffer to  
      * the internal event list. This will be done at the beginning of each  
      * audio cycle (that is each RenderAudio() call) to distinguish all  
      * events which have to be processed in the current audio cycle. Each  
      * EngineChannel has it's own input event queue for the common channel  
      * specific events (like NoteOn, NoteOff and ControlChange events).  
      * Beside that, the engine also has a input event queue for global  
      * events (usually SysEx messages).  
      *  
      * @param Samples - number of sample points to be processed in the  
      *                  current audio cycle  
      */  
     void EngineChannel::ImportEvents(uint Samples) {  
         RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();  
         Event* pEvent;  
         while (true) {  
             // get next event from input event queue  
             if (!(pEvent = eventQueueReader.pop())) break;  
             // if younger event reached, ignore that and all subsequent ones for now  
             if (pEvent->FragmentPos() >= Samples) {  
                 eventQueueReader--;  
                 dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));  
                 pEvent->ResetFragmentPos();  
                 break;  
             }  
             // copy event to internal event list  
             if (pEvents->poolIsEmpty()) {  
                 dmsg(1,("Event pool emtpy!\n"));  
                 break;  
             }  
             *pEvents->allocAppend() = *pEvent;  
         }  
         eventQueueReader.free(); // free all copied events from input queue  
     }  
   
     float EngineChannel::Volume() {  
         return GlobalVolume;  
     }  
   
     void EngineChannel::Volume(float f) {  
         GlobalVolume = f;  
     }  
   
     uint EngineChannel::Channels() {  
         return 2;  
     }  
   
     String EngineChannel::InstrumentFileName() {  
         return InstrumentFile;  
     }  
   
     String EngineChannel::InstrumentName() {  
         return InstrumentIdxName;  
     }  
   
     int EngineChannel::InstrumentIndex() {  
         return InstrumentIdx;  
     }  
   
     int EngineChannel::InstrumentStatus() {  
         return InstrumentStat;  
     }  
   
     String EngineChannel::EngineName() {  
         return LS_GIG_ENGINE_NAME;  
     }  
       
161  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.554  
changed lines
  Added in v.2277

  ViewVC Help
Powered by ViewVC