/[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 80 by schoenebeck, Sun May 23 19:16:33 2004 UTC revision 246 by schoenebeck, Sun Sep 19 14:12:55 2004 UTC
# Line 37  namespace LinuxSampler { namespace gig { Line 37  namespace LinuxSampler { namespace gig {
37          pAudioOutputDevice = NULL;          pAudioOutputDevice = NULL;
38          pDiskThread        = NULL;          pDiskThread        = NULL;
39          pEventGenerator    = NULL;          pEventGenerator    = NULL;
40          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT);          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);
41            pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);
42          pEventPool         = new RTELMemoryPool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new RTELMemoryPool<Event>(MAX_EVENTS_PER_FRAGMENT);
43          pVoicePool         = new RTELMemoryPool<Voice>(MAX_AUDIO_VOICES);          pVoicePool         = new RTELMemoryPool<Voice>(MAX_AUDIO_VOICES);
44          pActiveKeys        = new RTELMemoryPool<uint>(128);          pActiveKeys        = new RTELMemoryPool<uint>(128);
# Line 47  namespace LinuxSampler { namespace gig { Line 48  namespace LinuxSampler { namespace gig {
48              pSynthesisEvents[i] = new RTEList<Event>(pEventPool);              pSynthesisEvents[i] = new RTEList<Event>(pEventPool);
49          }          }
50          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
51              pMIDIKeyInfo[i].pActiveVoices = new RTEList<Voice>(pVoicePool);              pMIDIKeyInfo[i].pActiveVoices  = new RTEList<Voice>(pVoicePool);
52              pMIDIKeyInfo[i].KeyPressed    = false;              pMIDIKeyInfo[i].KeyPressed     = false;
53              pMIDIKeyInfo[i].Active        = false;              pMIDIKeyInfo[i].Active         = false;
54              pMIDIKeyInfo[i].pSelf         = NULL;              pMIDIKeyInfo[i].ReleaseTrigger = false;
55              pMIDIKeyInfo[i].pEvents       = new RTEList<Event>(pEventPool);              pMIDIKeyInfo[i].pSelf          = NULL;
56                pMIDIKeyInfo[i].pEvents        = new RTEList<Event>(pEventPool);
57          }          }
58          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {
59              pVoice->SetEngine(this);              pVoice->SetEngine(this);
# Line 62  namespace LinuxSampler { namespace gig { Line 64  namespace LinuxSampler { namespace gig {
64          pBasicFilterParameters  = NULL;          pBasicFilterParameters  = NULL;
65          pMainFilterParameters   = NULL;          pMainFilterParameters   = NULL;
66    
67            InstrumentIdx = -1;
68            InstrumentStat = -1;
69    
70            AudioDeviceChannelLeft  = -1;
71            AudioDeviceChannelRight = -1;
72    
73          ResetInternal();          ResetInternal();
74      }      }
75    
# Line 86  namespace LinuxSampler { namespace gig { Line 94  namespace LinuxSampler { namespace gig {
94          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
95          if (pVoicePool)  delete pVoicePool;          if (pVoicePool)  delete pVoicePool;
96          if (pActiveKeys) delete pActiveKeys;          if (pActiveKeys) delete pActiveKeys;
97            if (pSysexBuffer) delete pSysexBuffer;
98          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
99          if (pMainFilterParameters) delete[] pMainFilterParameters;          if (pMainFilterParameters) delete[] pMainFilterParameters;
100          if (pBasicFilterParameters) delete[] pBasicFilterParameters;          if (pBasicFilterParameters) delete[] pBasicFilterParameters;
# Line 146  namespace LinuxSampler { namespace gig { Line 155  namespace LinuxSampler { namespace gig {
155          SustainPedal        = false;          SustainPedal        = false;
156          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
157          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
158            GlobalVolume        = 1.0;
159    
160            // reset to normal chromatic scale (means equal temper)
161            memset(&ScaleTuning[0], 0x00, 12);
162    
163          // set all MIDI controller values to zero          // set all MIDI controller values to zero
164          memset(ControllerTable, 0x00, 128);          memset(ControllerTable, 0x00, 128);
# Line 154  namespace LinuxSampler { namespace gig { Line 167  namespace LinuxSampler { namespace gig {
167          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
168              pMIDIKeyInfo[i].pActiveVoices->clear();              pMIDIKeyInfo[i].pActiveVoices->clear();
169              pMIDIKeyInfo[i].pEvents->clear();              pMIDIKeyInfo[i].pEvents->clear();
170              pMIDIKeyInfo[i].KeyPressed = false;              pMIDIKeyInfo[i].KeyPressed     = false;
171              pMIDIKeyInfo[i].Active     = false;              pMIDIKeyInfo[i].Active         = false;
172              pMIDIKeyInfo[i].pSelf      = NULL;              pMIDIKeyInfo[i].ReleaseTrigger = false;
173                pMIDIKeyInfo[i].pSelf          = NULL;
174          }          }
175    
176            // reset all key groups
177            map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();
178            for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;
179    
180          // reset all voices          // reset all voices
181          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {
182              pVoice->Reset();              pVoice->Reset();
# Line 195  namespace LinuxSampler { namespace gig { Line 213  namespace LinuxSampler { namespace gig {
213              Instruments.HandBack(pInstrument, this);              Instruments.HandBack(pInstrument, this);
214          }          }
215    
216            InstrumentFile = FileName;
217            InstrumentIdx = Instrument;
218            InstrumentStat = 0;
219    
220            // delete all key groups
221            ActiveKeyGroups.clear();
222    
223          // request gig instrument from instrument manager          // request gig instrument from instrument manager
224          try {          try {
225              instrument_id_t instrid;              instrument_id_t instrid;
# Line 202  namespace LinuxSampler { namespace gig { Line 227  namespace LinuxSampler { namespace gig {
227              instrid.iInstrument = Instrument;              instrid.iInstrument = Instrument;
228              pInstrument = Instruments.Borrow(instrid, this);              pInstrument = Instruments.Borrow(instrid, this);
229              if (!pInstrument) {              if (!pInstrument) {
230                    InstrumentStat = -1;
231                  dmsg(1,("no instrument loaded!!!\n"));                  dmsg(1,("no instrument loaded!!!\n"));
232                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
233              }              }
234          }          }
235          catch (RIFF::Exception e) {          catch (RIFF::Exception e) {
236                InstrumentStat = -2;
237              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
238              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
239          }          }
240          catch (InstrumentResourceManagerException e) {          catch (InstrumentResourceManagerException e) {
241                InstrumentStat = -3;
242              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
243              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
244          }          }
245          catch (...) {          catch (...) {
246                InstrumentStat = -4;
247              throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");              throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");
248          }          }
249    
250            // rebuild ActiveKeyGroups map with key groups of current instrument
251            for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())
252                if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;
253    
254            InstrumentStat = 100;
255    
256          // inform audio driver for the need of two channels          // inform audio driver for the need of two channels
257          try {          try {
258              if (pAudioOutputDevice) pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo              if (pAudioOutputDevice) pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo
# Line 247  namespace LinuxSampler { namespace gig { Line 282  namespace LinuxSampler { namespace gig {
282       * update process was completed, so we can continue with playback.       * update process was completed, so we can continue with playback.
283       */       */
284      void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {      void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
285          this->pInstrument = pNewResource;          this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())
286          Enable();          Enable();
287      }      }
288    
# Line 265  namespace LinuxSampler { namespace gig { Line 300  namespace LinuxSampler { namespace gig {
300              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
301          }          }
302    
303            this->AudioDeviceChannelLeft  = 0;
304            this->AudioDeviceChannelRight = 1;
305            this->pOutputLeft             = pAudioOutputDevice->Channel(0)->Buffer();
306            this->pOutputRight            = pAudioOutputDevice->Channel(1)->Buffer();
307            this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();
308            this->SampleRate              = pAudioOutputDevice->SampleRate();
309    
310          // (re)create disk thread          // (re)create disk thread
311          if (this->pDiskThread) {          if (this->pDiskThread) {
312              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
# Line 278  namespace LinuxSampler { namespace gig { Line 320  namespace LinuxSampler { namespace gig {
320    
321          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {
322              pVoice->pDiskThread = this->pDiskThread;              pVoice->pDiskThread = this->pDiskThread;
             pVoice->SetOutput(pAudioOut);  
323              dmsg(3,("d"));              dmsg(3,("d"));
324          }          }
325          pVoicePool->clear();          pVoicePool->clear();
# Line 316  namespace LinuxSampler { namespace gig { Line 357  namespace LinuxSampler { namespace gig {
357              AudioOutputDevice* olddevice = pAudioOutputDevice;              AudioOutputDevice* olddevice = pAudioOutputDevice;
358              pAudioOutputDevice = NULL;              pAudioOutputDevice = NULL;
359              olddevice->Disconnect(this);              olddevice->Disconnect(this);
360                AudioDeviceChannelLeft  = -1;
361                AudioDeviceChannelRight = -1;
362          }          }
363      }      }
364    
# Line 370  namespace LinuxSampler { namespace gig { Line 413  namespace LinuxSampler { namespace gig {
413              pNextEvent = pEvents->next();              pNextEvent = pEvents->next();
414              switch (pEvent->Type) {              switch (pEvent->Type) {
415                  case Event::type_note_on:                  case Event::type_note_on:
416                      dmsg(5,("Audio Thread: Note on received\n"));                      dmsg(5,("Engine: Note on received\n"));
417                      ProcessNoteOn(pEvent);                      ProcessNoteOn(pEvent);
418                      break;                      break;
419                  case Event::type_note_off:                  case Event::type_note_off:
420                      dmsg(5,("Audio Thread: Note off received\n"));                      dmsg(5,("Engine: Note off received\n"));
421                      ProcessNoteOff(pEvent);                      ProcessNoteOff(pEvent);
422                      break;                      break;
423                  case Event::type_control_change:                  case Event::type_control_change:
424                      dmsg(5,("Audio Thread: MIDI CC received\n"));                      dmsg(5,("Engine: MIDI CC received\n"));
425                      ProcessControlChange(pEvent);                      ProcessControlChange(pEvent);
426                      break;                      break;
427                  case Event::type_pitchbend:                  case Event::type_pitchbend:
428                      dmsg(5,("Audio Thread: Pitchbend received\n"));                      dmsg(5,("Engine: Pitchbend received\n"));
429                      ProcessPitchbend(pEvent);                      ProcessPitchbend(pEvent);
430                      break;                      break;
431                    case Event::type_sysex:
432                        dmsg(5,("Engine: Sysex received\n"));
433                        ProcessSysex(pEvent);
434                        break;
435              }              }
436          }          }
437    
# Line 408  namespace LinuxSampler { namespace gig { Line 455  namespace LinuxSampler { namespace gig {
455                  pVoice->Render(Samples);                  pVoice->Render(Samples);
456                  if (pVoice->IsActive()) active_voices++; // still active                  if (pVoice->IsActive()) active_voices++; // still active
457                  else { // voice reached end, is now inactive                  else { // voice reached end, is now inactive
458                      KillVoice(pVoice); // remove voice from the list of active voices                      KillVoiceImmediately(pVoice); // remove voice from the list of active voices
459                  }                  }
460              }              }
461              pKey->pEvents->clear(); // free all events on the key              pKey->pEvents->clear(); // free all events on the key
# Line 432  namespace LinuxSampler { namespace gig { Line 479  namespace LinuxSampler { namespace gig {
479       *  @param Velocity - MIDI velocity value of the triggered key       *  @param Velocity - MIDI velocity value of the triggered key
480       */       */
481      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {
482          Event event    = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
483          event.Type     = Event::type_note_on;          event.Type                = Event::type_note_on;
484          event.Key      = Key;          event.Param.Note.Key      = Key;
485          event.Velocity = Velocity;          event.Param.Note.Velocity = Velocity;
486          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
487          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
488      }      }
# Line 448  namespace LinuxSampler { namespace gig { Line 495  namespace LinuxSampler { namespace gig {
495       *  @param Velocity - MIDI release velocity value of the released key       *  @param Velocity - MIDI release velocity value of the released key
496       */       */
497      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {
498          Event event    = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
499          event.Type     = Event::type_note_off;          event.Type                = Event::type_note_off;
500          event.Key      = Key;          event.Param.Note.Key      = Key;
501          event.Velocity = Velocity;          event.Param.Note.Velocity = Velocity;
502          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
503          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
504      }      }
# Line 463  namespace LinuxSampler { namespace gig { Line 510  namespace LinuxSampler { namespace gig {
510       *  @param Pitch - MIDI pitch value (-8192 ... +8191)       *  @param Pitch - MIDI pitch value (-8192 ... +8191)
511       */       */
512      void Engine::SendPitchbend(int Pitch) {      void Engine::SendPitchbend(int Pitch) {
513          Event event = pEventGenerator->CreateEvent();          Event event             = pEventGenerator->CreateEvent();
514          event.Type  = Event::type_pitchbend;          event.Type              = Event::type_pitchbend;
515          event.Pitch = Pitch;          event.Param.Pitch.Pitch = Pitch;
516          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
517          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
518      }      }
# Line 478  namespace LinuxSampler { namespace gig { Line 525  namespace LinuxSampler { namespace gig {
525       *  @param Value      - value of the control change       *  @param Value      - value of the control change
526       */       */
527      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {
528          Event event      = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
529          event.Type       = Event::type_control_change;          event.Type                = Event::type_control_change;
530          event.Controller = Controller;          event.Param.CC.Controller = Controller;
531          event.Value      = Value;          event.Param.CC.Value      = Value;
532          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
533          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
534      }      }
535    
536      /**      /**
537         *  Will be called by the MIDI input device whenever a MIDI system
538         *  exclusive message has arrived.
539         *
540         *  @param pData - pointer to sysex data
541         *  @param Size  - lenght of sysex data (in bytes)
542         */
543        void Engine::SendSysex(void* pData, uint Size) {
544            Event event             = pEventGenerator->CreateEvent();
545            event.Type              = Event::type_sysex;
546            event.Param.Sysex.Size  = Size;
547            if (pEventQueue->write_space() > 0) {
548                if (pSysexBuffer->write_space() >= Size) {
549                    // copy sysex data to input buffer
550                    uint toWrite = Size;
551                    uint8_t* pPos = (uint8_t*) pData;
552                    while (toWrite) {
553                        const uint writeNow = RTMath::Min(toWrite, pSysexBuffer->write_space_to_end());
554                        pSysexBuffer->write(pPos, writeNow);
555                        toWrite -= writeNow;
556                        pPos    += writeNow;
557    
558                    }
559                    // finally place sysex event into input event queue
560                    pEventQueue->push(&event);
561                }
562                else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,SYSEX_BUFFER_SIZE));
563            }
564            else dmsg(1,("Engine: Input event queue full!"));
565        }
566    
567        /**
568       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
569       *       *
570       *  @param pNoteOnEvent - key, velocity and time stamp of the event       *  @param pNoteOnEvent - key, velocity and time stamp of the event
571       */       */
572      void Engine::ProcessNoteOn(Event* pNoteOnEvent) {      void Engine::ProcessNoteOn(Event* pNoteOnEvent) {
573          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Param.Note.Key];
574    
575          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
576    
577          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
578          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
579              pNoteOnEvent->Type = Event::type_cancel_release; // transform event type              Event* pCancelReleaseEvent = pKey->pEvents->alloc();
580              pEvents->move(pNoteOnEvent, pKey->pEvents); // move event to the key's own event list              if (pCancelReleaseEvent) {
581          }                  *pCancelReleaseEvent = *pNoteOnEvent;
582                    pCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
         // allocate a new voice for the key  
         Voice* pNewVoice = pKey->pActiveVoices->alloc();  
         if (pNewVoice) {  
             // launch the new voice  
             if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument) < 0) {  
                 dmsg(1,("Triggering new voice failed!\n"));  
                 pKey->pActiveVoices->free(pNewVoice);  
             }  
             else if (!pKey->Active) { // mark as active key  
                 pKey->Active = true;  
                 pKey->pSelf  = pActiveKeys->alloc();  
                 *pKey->pSelf = pNoteOnEvent->Key;  
583              }              }
584                else dmsg(1,("Event pool emtpy!\n"));
585          }          }
586          else std::cerr << "No free voice!" << std::endl << std::flush;  
587            // allocate and trigger a new voice for the key
588            LaunchVoice(pNoteOnEvent);
589    
590            // finally move note on event to the key's own event list
591            pEvents->move(pNoteOnEvent, pKey->pEvents);
592      }      }
593    
594      /**      /**
# Line 528  namespace LinuxSampler { namespace gig { Line 600  namespace LinuxSampler { namespace gig {
600       *  @param pNoteOffEvent - key, velocity and time stamp of the event       *  @param pNoteOffEvent - key, velocity and time stamp of the event
601       */       */
602      void Engine::ProcessNoteOff(Event* pNoteOffEvent) {      void Engine::ProcessNoteOff(Event* pNoteOffEvent) {
603          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Param.Note.Key];
604    
605          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
606    
607          // release voices on this key if needed          // release voices on this key if needed
608          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
609              pNoteOffEvent->Type = Event::type_release; // transform event type              pNoteOffEvent->Type = Event::type_release; // transform event type
             pEvents->move(pNoteOffEvent, pKey->pEvents); // move event to the key's own event list  
610          }          }
611    
612            // spawn release triggered voice(s) if needed
613            if (pKey->ReleaseTrigger) {
614                LaunchVoice(pNoteOffEvent, 0, true);
615                pKey->ReleaseTrigger = false;
616            }
617    
618            // move event to the key's own event list
619            pEvents->move(pNoteOffEvent, pKey->pEvents);
620      }      }
621    
622      /**      /**
# Line 546  namespace LinuxSampler { namespace gig { Line 626  namespace LinuxSampler { namespace gig {
626       *  @param pPitchbendEvent - absolute pitch value and time stamp of the event       *  @param pPitchbendEvent - absolute pitch value and time stamp of the event
627       */       */
628      void Engine::ProcessPitchbend(Event* pPitchbendEvent) {      void Engine::ProcessPitchbend(Event* pPitchbendEvent) {
629          this->Pitch = pPitchbendEvent->Pitch; // store current pitch value          this->Pitch = pPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
630          pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]);          pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]);
631      }      }
632    
633      /**      /**
634         *  Allocates and triggers a new voice. This method will usually be
635         *  called by the ProcessNoteOn() method and by the voices itself
636         *  (e.g. to spawn further voices on the same key for layered sounds).
637         *
638         *  @param pNoteOnEvent        - key, velocity and time stamp of the event
639         *  @param iLayer              - layer index for the new voice (optional - only
640         *                               in case of layered sounds of course)
641         *  @param ReleaseTriggerVoice - if new voice is a release triggered voice
642         *                               (optional, default = false)
643         */
644        void Engine::LaunchVoice(Event* pNoteOnEvent, int iLayer, bool ReleaseTriggerVoice) {
645            midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Param.Note.Key];
646    
647            // allocate a new voice for the key
648            Voice* pNewVoice = pKey->pActiveVoices->alloc();
649            if (pNewVoice) {
650                // launch the new voice
651                if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice) < 0) {
652                    dmsg(1,("Triggering new voice failed!\n"));
653                    pKey->pActiveVoices->free(pNewVoice);
654                }
655                else { // on success
656                    uint** ppKeyGroup = NULL;
657                    if (pNewVoice->KeyGroup) { // if this voice / key belongs to a key group
658                        ppKeyGroup = &ActiveKeyGroups[pNewVoice->KeyGroup];
659                        if (*ppKeyGroup) { // if there's already an active key in that key group
660                            midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup];
661                            // kill all voices on the (other) key
662                            Voice* pVoiceToBeKilled = pOtherKey->pActiveVoices->first();
663                            while (pVoiceToBeKilled) {
664                                Voice* pVoiceToBeKilledNext = pOtherKey->pActiveVoices->next();
665                                if (pVoiceToBeKilled->Type != Voice::type_release_trigger) pVoiceToBeKilled->Kill(pNoteOnEvent);
666                                pOtherKey->pActiveVoices->set_current(pVoiceToBeKilled);
667                                pVoiceToBeKilled = pVoiceToBeKilledNext;
668                            }
669                        }
670                    }
671                    if (!pKey->Active) { // mark as active key
672                        pKey->Active = true;
673                        pKey->pSelf  = pActiveKeys->alloc();
674                        *pKey->pSelf = pNoteOnEvent->Param.Note.Key;
675                    }
676                    if (pNewVoice->KeyGroup) {
677                        *ppKeyGroup = pKey->pSelf; // put key as the (new) active key to its key group
678                    }
679                    if (pNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
680                }
681            }
682            else std::cerr << "No free voice!" << std::endl << std::flush;
683        }
684    
685        /**
686       *  Immediately kills the voice given with pVoice (no matter if sustain is       *  Immediately kills the voice given with pVoice (no matter if sustain is
687       *  pressed or not) and removes it from the MIDI key's list of active voice.       *  pressed or not) and removes it from the MIDI key's list of active voice.
688       *  This method will e.g. be called if a voice went inactive by itself.       *  This method will e.g. be called if a voice went inactive by itself.
689       *       *
690       *  @param pVoice - points to the voice to be killed       *  @param pVoice - points to the voice to be killed
691       */       */
692      void Engine::KillVoice(Voice* pVoice) {      void Engine::KillVoiceImmediately(Voice* pVoice) {
693          if (pVoice) {          if (pVoice) {
694              if (pVoice->IsActive()) pVoice->Kill();              if (pVoice->IsActive()) pVoice->KillImmediately();
695    
696              midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey];              midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey];
697    
# Line 568  namespace LinuxSampler { namespace gig { Line 700  namespace LinuxSampler { namespace gig {
700    
701              // check if there are no voices left on the MIDI key and update the key info if so              // check if there are no voices left on the MIDI key and update the key info if so
702              if (pKey->pActiveVoices->is_empty()) {              if (pKey->pActiveVoices->is_empty()) {
703                    if (pVoice->KeyGroup) { // if voice / key belongs to a key group
704                        uint** ppKeyGroup = &ActiveKeyGroups[pVoice->KeyGroup];
705                        if (*ppKeyGroup == pKey->pSelf) *ppKeyGroup = NULL; // remove key from key group
706                    }
707                  pKey->Active = false;                  pKey->Active = false;
708                  pActiveKeys->free(pKey->pSelf); // remove key from list of active keys                  pActiveKeys->free(pKey->pSelf); // remove key from list of active keys
709                  pKey->pSelf = NULL;                  pKey->pSelf = NULL;
710                    pKey->ReleaseTrigger = false;
711                  dmsg(3,("Key has no more voices now\n"));                  dmsg(3,("Key has no more voices now\n"));
712              }              }
713          }          }
# Line 584  namespace LinuxSampler { namespace gig { Line 721  namespace LinuxSampler { namespace gig {
721       *  @param pControlChangeEvent - controller, value and time stamp of the event       *  @param pControlChangeEvent - controller, value and time stamp of the event
722       */       */
723      void Engine::ProcessControlChange(Event* pControlChangeEvent) {      void Engine::ProcessControlChange(Event* pControlChangeEvent) {
724          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", pControlChangeEvent->Controller, pControlChangeEvent->Value));          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", pControlChangeEvent->Param.CC.Controller, pControlChangeEvent->Param.CC.Value));
725    
726          switch (pControlChangeEvent->Controller) {          switch (pControlChangeEvent->Param.CC.Controller) {
727              case 64: {              case 64: {
728                  if (pControlChangeEvent->Value >= 64 && !SustainPedal) {                  if (pControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {
729                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("PEDAL DOWN\n"));
730                      SustainPedal = true;                      SustainPedal = true;
731    
# Line 608  namespace LinuxSampler { namespace gig { Line 745  namespace LinuxSampler { namespace gig {
745                          }                          }
746                      }                      }
747                  }                  }
748                  if (pControlChangeEvent->Value < 64 && SustainPedal) {                  if (pControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {
749                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("PEDAL UP\n"));
750                      SustainPedal = false;                      SustainPedal = false;
751    
# Line 633  namespace LinuxSampler { namespace gig { Line 770  namespace LinuxSampler { namespace gig {
770          }          }
771    
772          // update controller value in the engine's controller table          // update controller value in the engine's controller table
773          ControllerTable[pControlChangeEvent->Controller] = pControlChangeEvent->Value;          ControllerTable[pControlChangeEvent->Param.CC.Controller] = pControlChangeEvent->Param.CC.Value;
774    
775          // move event from the unsorted event list to the control change event list          // move event from the unsorted event list to the control change event list
776          pEvents->move(pControlChangeEvent, pCCEvents);          pEvents->move(pControlChangeEvent, pCCEvents);
777      }      }
778    
779      /**      /**
780         *  Reacts on MIDI system exclusive messages.
781         *
782         *  @param pSysexEvent - sysex data size and time stamp of the sysex event
783         */
784        void Engine::ProcessSysex(Event* pSysexEvent) {
785            RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
786    
787            uint8_t exclusive_status, id;
788            if (!reader.pop(&exclusive_status)) goto free_sysex_data;
789            if (!reader.pop(&id))               goto free_sysex_data;
790            if (exclusive_status != 0xF0)       goto free_sysex_data;
791    
792            switch (id) {
793                case 0x41: { // Roland
794                    uint8_t device_id, model_id, cmd_id;
795                    if (!reader.pop(&device_id)) goto free_sysex_data;
796                    if (!reader.pop(&model_id))  goto free_sysex_data;
797                    if (!reader.pop(&cmd_id))    goto free_sysex_data;
798                    if (model_id != 0x42 /*GS*/) goto free_sysex_data;
799                    if (cmd_id != 0x12 /*DT1*/)  goto free_sysex_data;
800    
801                    // command address
802                    uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)
803                    const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
804                    if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
805                    if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
806                    }
807                    else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
808                    }
809                    else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
810                        switch (addr[3]) {
811                            case 0x40: { // scale tuning
812                                uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
813                                if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
814                                uint8_t checksum;
815                                if (!reader.pop(&checksum))                      goto free_sysex_data;
816                                if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;
817                                for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
818                                AdjustScale((int8_t*) scale_tunes);
819                                break;
820                            }
821                        }
822                    }
823                    else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x20) { // Part Parameters (2)
824                    }
825                    else if (addr[0] == 0x41) { // Drum Setup Parameters
826                    }
827                    break;
828                }
829            }
830    
831            free_sysex_data: // finally free sysex data
832            pSysexBuffer->increment_read_ptr(pSysexEvent->Param.Sysex.Size);
833        }
834    
835        /**
836         * Calculates the Roland GS sysex check sum.
837         *
838         * @param AddrReader - reader which currently points to the first GS
839         *                     command address byte of the GS sysex message in
840         *                     question
841         * @param DataSize   - size of the GS message data (in bytes)
842         */
843        uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t>::NonVolatileReader AddrReader, uint DataSize) {
844            RingBuffer<uint8_t>::NonVolatileReader reader = AddrReader;
845            uint bytes = 3 /*addr*/ + DataSize;
846            uint8_t addr_and_data[bytes];
847            reader.read(&addr_and_data[0], bytes);
848            uint8_t sum = 0;
849            for (uint i = 0; i < bytes; i++) sum += addr_and_data[i];
850            return 128 - sum % 128;
851        }
852    
853        /**
854         * Allows to tune each of the twelve semitones of an octave.
855         *
856         * @param ScaleTunes - detuning of all twelve semitones (in cents)
857         */
858        void Engine::AdjustScale(int8_t ScaleTunes[12]) {
859            memcpy(&this->ScaleTuning[0], &ScaleTunes[0], 12); //TODO: currently not sample accurate
860        }
861    
862        /**
863       * Initialize the parameter sequence for the modulation destination given by       * Initialize the parameter sequence for the modulation destination given by
864       * by 'dst' with the constant value given by val.       * by 'dst' with the constant value given by val.
865       */       */
# Line 662  namespace LinuxSampler { namespace gig { Line 882  namespace LinuxSampler { namespace gig {
882          GlobalVolume = f;          GlobalVolume = f;
883      }      }
884    
885        uint Engine::Channels() {
886            return 2;
887        }
888    
889        void Engine::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {
890            AudioChannel* pChannel = pAudioOutputDevice->Channel(AudioDeviceChannel);
891            if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));
892            switch (EngineAudioChannel) {
893                case 0: // left output channel
894                    pOutputLeft = pChannel->Buffer();
895                    AudioDeviceChannelLeft = AudioDeviceChannel;
896                    break;
897                case 1: // right output channel
898                    pOutputRight = pChannel->Buffer();
899                    AudioDeviceChannelRight = AudioDeviceChannel;
900                    break;
901                default:
902                    throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
903            }
904        }
905    
906        int Engine::OutputChannel(uint EngineAudioChannel) {
907            switch (EngineAudioChannel) {
908                case 0: // left channel
909                    return AudioDeviceChannelLeft;
910                case 1: // right channel
911                    return AudioDeviceChannelRight;
912                default:
913                    throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
914            }
915        }
916    
917      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
918          return ActiveVoiceCount;          return ActiveVoiceCount;
919      }      }
# Line 690  namespace LinuxSampler { namespace gig { Line 942  namespace LinuxSampler { namespace gig {
942          return pDiskThread->GetBufferFillPercentage();          return pDiskThread->GetBufferFillPercentage();
943      }      }
944    
945        String Engine::EngineName() {
946            return "GigEngine";
947        }
948    
949        String Engine::InstrumentFileName() {
950            return InstrumentFile;
951        }
952    
953        int Engine::InstrumentIndex() {
954            return InstrumentIdx;
955        }
956    
957        int Engine::InstrumentStatus() {
958            return InstrumentStat;
959        }
960    
961      String Engine::Description() {      String Engine::Description() {
962          return "Gigasampler Engine";          return "Gigasampler Engine";
963      }      }
964    
965      String Engine::Version() {      String Engine::Version() {
966          return "0.0.1-0cvs20040423";          String s = "$Revision: 1.13 $";
967            return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
968      }      }
969    
970  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.80  
changed lines
  Added in v.246

  ViewVC Help
Powered by ViewVC