/[svn]/linuxsampler/trunk/src/audiothread.cpp
ViewVC logotype

Annotation of /linuxsampler/trunk/src/audiothread.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 30 - (hide annotations) (download)
Sun Jan 11 16:43:54 2004 UTC (20 years, 3 months ago) by schoenebeck
File size: 16022 byte(s)
* implemented amplitude envelope generator
* src/voice.cpp: some .gig instruments still sounded detuned, I hope
  finally to have this fixed now

1 schoenebeck 9 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5     * Copyright (C) 2003 by Benno Senoner and Christian Schoenebeck *
6     * *
7     * This program is free software; you can redistribute it and/or modify *
8     * it under the terms of the GNU General Public License as published by *
9     * the Free Software Foundation; either version 2 of the License, or *
10     * (at your option) any later version. *
11     * *
12     * This program is distributed in the hope that it will be useful, *
13     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15     * GNU General Public License for more details. *
16     * *
17     * You should have received a copy of the GNU General Public License *
18     * along with this program; if not, write to the Free Software *
19     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
20     * MA 02111-1307 USA *
21     ***************************************************************************/
22    
23     #include "audiothread.h"
24    
25     AudioThread::AudioThread(AudioIO* pAudioIO, DiskThread* pDiskThread, gig::Instrument* pInstrument) : Thread(true, 1, 0) {
26     this->pAudioIO = pAudioIO;
27     this->pDiskThread = pDiskThread;
28     this->pInstrument = pInstrument;
29     pCommandQueue = new RingBuffer<command_t>(1024);
30     pVoices = new Voice*[MAX_AUDIO_VOICES];
31 senoner 10 // allocate the ActiveVoicePool (for each midi key there is a variable size linked list
32 schoenebeck 12 // of pointers to Voice objects)
33     ActiveVoicePool = new RTELMemoryPool<Voice*>(MAX_AUDIO_VOICES);
34 schoenebeck 9 for (uint i = 0; i < MAX_AUDIO_VOICES; i++) {
35     pVoices[i] = new Voice(pDiskThread);
36     }
37     for (uint i = 0; i < 128; i++) {
38 schoenebeck 18 pMIDIKeyInfo[i].pActiveVoices = new RTEList<Voice*>;
39     pMIDIKeyInfo[i].hSustainPtr = NULL;
40     pMIDIKeyInfo[i].Sustained = false;
41     pMIDIKeyInfo[i].KeyPressed = false;
42     pMIDIKeyInfo[i].pSustainPoolNode = NULL;
43 schoenebeck 9 }
44 schoenebeck 15 SustainedKeyPool = new RTELMemoryPool<uint>(128);
45 schoenebeck 9
46     pAudioSumBuffer = new float[pAudioIO->FragmentSize * pAudioIO->Channels];
47    
48     // set all voice outputs to the AudioSumBuffer
49     for (int i = 0; i < MAX_AUDIO_VOICES; i++) {
50     pVoices[i]->SetOutput(pAudioSumBuffer, pAudioIO->FragmentSize * 2); //FIXME: assuming stereo
51     }
52    
53     // cache initial samples points (for actually needed samples)
54 schoenebeck 12 dmsg(1,("Caching initial samples..."));
55 schoenebeck 9 gig::Region* pRgn = this->pInstrument->GetFirstRegion();
56     while (pRgn) {
57     if (!pRgn->GetSample()->GetCache().Size) {
58 schoenebeck 12 dmsg(2,("C"));
59 schoenebeck 9 CacheInitialSamples(pRgn->GetSample());
60     }
61     for (uint i = 0; i < pRgn->DimensionRegions; i++) {
62     CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample);
63     }
64    
65     pRgn = this->pInstrument->GetNextRegion();
66     }
67 senoner 10
68 schoenebeck 30 // initialize modulation system
69     ModulationSystem::Initialize(pAudioIO->Samplerate, pAudioIO->FragmentSize);
70    
71 senoner 10 // sustain pedal value
72 schoenebeck 12 PrevHoldCCValue = 0;
73     SustainPedal = 0;
74 senoner 10
75 schoenebeck 12 dmsg(1,("OK\n"));
76 schoenebeck 9 }
77    
78     AudioThread::~AudioThread() {
79 schoenebeck 30 ModulationSystem::Close();
80 schoenebeck 9 if (pCommandQueue) delete pCommandQueue;
81     if (pVoices) {
82     for (uint i = 0; i < MAX_AUDIO_VOICES; i++) {
83     if (pVoices[i]) delete pVoices[i];
84     }
85     }
86     delete[] pVoices;
87     }
88    
89     int AudioThread::Main() {
90 schoenebeck 12 dmsg(2,("Audio thread running\n"));
91 schoenebeck 9
92     while (true) {
93    
94     // read and process commands from the queue
95     while (true) {
96     command_t command;
97 schoenebeck 18 if (!pCommandQueue->pop(&command)) break;
98 schoenebeck 9
99     switch (command.type) {
100     case command_type_note_on:
101 schoenebeck 12 dmsg(5,("Audio Thread: Note on received\n"));
102 schoenebeck 18 ProcessNoteOn(command.pitch, command.velocity);
103 schoenebeck 9 break;
104     case command_type_note_off:
105 schoenebeck 12 dmsg(5,("Audio Thread: Note off received\n"));
106 schoenebeck 18 ProcessNoteOff(command.pitch, command.velocity);
107 schoenebeck 9 break;
108 senoner 10 case command_type_continuous_controller:
109 schoenebeck 12 dmsg(5,("Audio Thread: MIDI CC received\n"));
110 schoenebeck 18 ProcessControlChange(command.channel, command.number, command.value);
111 senoner 10 break;
112 schoenebeck 9 }
113     }
114    
115    
116 schoenebeck 20 // zero out the output sum buffer
117     memset(pAudioSumBuffer, 0, pAudioIO->FragmentSize * pAudioIO->Channels * sizeof(float));
118 schoenebeck 9
119    
120     // render audio from all active voices
121 schoenebeck 12 int active_voices = 0;
122 schoenebeck 9 for (uint i = 0; i < MAX_AUDIO_VOICES; i++) {
123     if (pVoices[i]->IsActive()) {
124     pVoices[i]->RenderAudio();
125 schoenebeck 12 if (pVoices[i]->IsActive()) active_voices++; // still active
126     else { // voice reached end, is now inactive
127 schoenebeck 30 KillVoice(pVoices[i]); // remove voice from the list of active voices
128 schoenebeck 12 }
129 schoenebeck 9 }
130     }
131 schoenebeck 12 // write that to the disk thread class so that it can print it
132 senoner 10 // on the console for debugging purposes
133 schoenebeck 12 ActiveVoiceCount = active_voices;
134 schoenebeck 13 if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
135 schoenebeck 9
136    
137     // check clipping in the audio sum, convert to sample_type
138     // (from 32bit to 16bit sample) and copy to output buffer
139     float sample_point;
140     for (uint u = 0; u < pAudioIO->FragmentSize * pAudioIO->Channels; u++) {
141 schoenebeck 20 sample_point = this->pAudioSumBuffer[u] * this->Volume;
142 schoenebeck 9 if (sample_point < -32768.0) sample_point = -32768.0;
143     if (sample_point > 32767.0) sample_point = 32767.0;
144     this->pAudioIO->pOutputBuffer[u] = (sample_t) sample_point;
145     }
146    
147    
148     // call audio driver to output sound
149     int res = this->pAudioIO->Output();
150     if (res < 0) exit(EXIT_FAILURE);
151     }
152     }
153    
154     /// Will be called by the MIDIIn Thread to let the audio thread trigger a new voice.
155 schoenebeck 18 void AudioThread::SendNoteOn(uint8_t Pitch, uint8_t Velocity) {
156 schoenebeck 9 command_t cmd;
157     cmd.type = command_type_note_on;
158     cmd.pitch = Pitch;
159     cmd.velocity = Velocity;
160 schoenebeck 18 if (this->pCommandQueue->write_space() > 0) this->pCommandQueue->push(&cmd);
161     else dmsg(1,("AudioThread: Command queue full!"));
162 schoenebeck 9 }
163    
164 schoenebeck 18 /// Will be called by the MIDIIn Thread to signal the audio thread to release voice(s).
165     void AudioThread::SendNoteOff(uint8_t Pitch, uint8_t Velocity) {
166 schoenebeck 9 command_t cmd;
167     cmd.type = command_type_note_off;
168     cmd.pitch = Pitch;
169     cmd.velocity = Velocity;
170 schoenebeck 18 if (this->pCommandQueue->write_space() > 0) this->pCommandQueue->push(&cmd);
171     else dmsg(1,("AudioThread: Command queue full!"));
172 schoenebeck 9 }
173    
174 schoenebeck 18 // Will be called by the MIDIIn Thread to signal the audio thread that a continuous controller value has changed.
175     void AudioThread::SendControlChange(uint8_t Channel, uint8_t Number, uint8_t Value) {
176 senoner 10 command_t cmd;
177     cmd.type = command_type_continuous_controller;
178     cmd.channel = Channel;
179     cmd.number = Number;
180     cmd.value = Value;
181 schoenebeck 18 if (this->pCommandQueue->write_space() > 0) this->pCommandQueue->push(&cmd);
182     else dmsg(1,("AudioThread: Command queue full!"));
183 senoner 10 }
184    
185 schoenebeck 18 /**
186     * Assigns and triggers a new voice for the respective MIDI key.
187     */
188     void AudioThread::ProcessNoteOn(uint8_t MIDIKey, uint8_t Velocity) {
189     pMIDIKeyInfo[MIDIKey].KeyPressed = true; // the MIDI key was currently pressed down
190 schoenebeck 9 for (int i = 0; i < MAX_AUDIO_VOICES; i++) {
191 schoenebeck 18 if (pVoices[i]->IsActive()) continue; // search for a free voice
192 schoenebeck 15
193 schoenebeck 18 // launch the new voice
194     if (pVoices[i]->Trigger(MIDIKey, Velocity, this->pInstrument) < 0) {
195     return; // failed to trigger the new voice
196     }
197    
198 senoner 10 // add (append) a new voice to the corresponding MIDIKey active voices list
199 schoenebeck 15 Voice** new_voice_ptr = ActiveVoicePool->alloc_append(pMIDIKeyInfo[MIDIKey].pActiveVoices);
200 schoenebeck 12 *new_voice_ptr = pVoices[i];
201     pVoices[i]->pSelfPtr = new_voice_ptr; // FIXME: hack to allow fast deallocation
202 schoenebeck 15
203 schoenebeck 18 // update key info
204 schoenebeck 15 if (!pMIDIKeyInfo[MIDIKey].hSustainPtr) {
205     dmsg(4,("ActivateVoice(uint,uint): hSustainPtr == null, setting release pointer to the last voice on the key...\n"));
206     pMIDIKeyInfo[MIDIKey].pActiveVoices->last();
207     pMIDIKeyInfo[MIDIKey].hSustainPtr = pMIDIKeyInfo[MIDIKey].pActiveVoices->current();
208     }
209 schoenebeck 9 return;
210     }
211     std::cerr << "No free voice!" << std::endl << std::flush;
212     }
213    
214 schoenebeck 15 /**
215     * Releases the voices on the given key if sustain pedal is not pressed.
216     * If sustain is pressed, the release of the note will be postponed until
217     * sustain pedal will be released or voice turned inactive by itself (e.g.
218     * due to completion of sample playback).
219     */
220 schoenebeck 18 void AudioThread::ProcessNoteOff(uint8_t MIDIKey, uint8_t Velocity) {
221     pMIDIKeyInfo[MIDIKey].KeyPressed = false; // the MIDI key was currently released
222 schoenebeck 15 midi_key_info_t* pmidikey = &pMIDIKeyInfo[MIDIKey];
223     if (SustainPedal) { // if sustain pedal is pressed postpone the Note-Off
224     if (pmidikey->hSustainPtr) {
225     // stick the note-off information to the respective voice
226     Voice** pVoiceToRelease = pmidikey->pActiveVoices->set_current(pmidikey->hSustainPtr);
227     if (pVoiceToRelease) {
228     (*pVoiceToRelease)->ReleaseVelocity = Velocity;
229     // now increment the sustain pointer
230     pmidikey->pActiveVoices->next();
231     pmidikey->hSustainPtr = pmidikey->pActiveVoices->current();
232     // if the key was not sustained yet, add it's MIDI key number to the sustained key pool
233     if (!pmidikey->Sustained) {
234 schoenebeck 18 uint* sustainedmidikey = SustainedKeyPool->alloc();
235     *sustainedmidikey = MIDIKey;
236     pmidikey->pSustainPoolNode = sustainedmidikey;
237     pmidikey->Sustained = true;
238 schoenebeck 15 }
239     }
240     else dmsg(3,("Ignoring NOTE OFF --> pVoiceToRelease == null!\n"));
241     }
242     else dmsg(3,("Ignoring NOTE OFF, seems like more Note-Offs than Note-Ons or no free voices available?\n"));
243 schoenebeck 12 }
244     else {
245 schoenebeck 18 // release all active voices on the midi key
246 schoenebeck 15 Voice** pVoicePtr = pmidikey->pActiveVoices->first();
247 schoenebeck 18 while (pVoicePtr) {
248     Voice** pVoicePtrNext = pMIDIKeyInfo[MIDIKey].pActiveVoices->next();
249 schoenebeck 30 (*pVoicePtr)->Release();
250 schoenebeck 18 pVoicePtr = pVoicePtrNext;
251     }
252 schoenebeck 12 }
253     }
254 senoner 10
255 schoenebeck 15 /**
256 schoenebeck 30 * Immediately kills the voice given with pVoice (no matter if sustain is
257     * pressed or not) and removes it from the MIDI key's list of active voice.
258     * This method will e.g. be called if a voice went inactive by itself. If
259     * sustain pedal is pressed the method takes care to free those sustain
260     * informations of the voice.
261 schoenebeck 15 */
262 schoenebeck 30 void AudioThread::KillVoice(Voice* pVoice) {
263 schoenebeck 9 if (pVoice) {
264 schoenebeck 30 if (pVoice->IsActive()) pVoice->Kill();
265 senoner 10
266 schoenebeck 15 if (pMIDIKeyInfo[pVoice->MIDIKey].Sustained) {
267 schoenebeck 30 // check if the sustain pointer has to be moved, now that we kill the voice
268 schoenebeck 15 RTEList<Voice*>::NodeHandle hSustainPtr = pMIDIKeyInfo[pVoice->MIDIKey].hSustainPtr;
269     if (hSustainPtr) {
270     Voice** pVoicePtr = pMIDIKeyInfo[pVoice->MIDIKey].pActiveVoices->set_current(hSustainPtr);
271     if (pVoicePtr) {
272     if (*pVoicePtr == pVoice) { // move sustain pointer to the next sustained voice
273     dmsg(3,("Correcting sustain pointer\n"));
274     pMIDIKeyInfo[pVoice->MIDIKey].pActiveVoices->next();
275     pMIDIKeyInfo[pVoice->MIDIKey].hSustainPtr = pMIDIKeyInfo[pVoice->MIDIKey].pActiveVoices->current();
276     }
277     else dmsg(4,("ReleaseVoice(Voice*): *hSustain != pVoice\n"));
278     }
279     else dmsg(3,("ReleaseVoice(Voice*): pVoicePtr == null\n"));
280     }
281     else dmsg(3,("ReleaseVoice(Voice*): hSustainPtr == null\n"));
282 schoenebeck 18 }
283 schoenebeck 15
284 schoenebeck 18 // remove the voice from the list associated with this MIDI key
285     ActiveVoicePool->free(pVoice->pSelfPtr);
286 schoenebeck 15
287 schoenebeck 18 // check if there are no voices left on the MIDI key and update the key info if so
288     if (pMIDIKeyInfo[pVoice->MIDIKey].pActiveVoices->is_empty()) {
289     pMIDIKeyInfo[pVoice->MIDIKey].hSustainPtr = NULL;
290     if (pMIDIKeyInfo[pVoice->MIDIKey].Sustained) {
291     SustainedKeyPool->free(pMIDIKeyInfo[pVoice->MIDIKey].pSustainPoolNode);
292     pMIDIKeyInfo[pVoice->MIDIKey].pSustainPoolNode = NULL;
293     pMIDIKeyInfo[pVoice->MIDIKey].Sustained = false;
294 schoenebeck 15 }
295 schoenebeck 18 dmsg(3,("Key has no more voices now\n"));
296 schoenebeck 15 }
297 schoenebeck 9 }
298 schoenebeck 15 else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;
299 schoenebeck 9 }
300    
301 schoenebeck 18 void AudioThread::ProcessControlChange(uint8_t Channel, uint8_t Number, uint8_t Value) {
302 schoenebeck 12 dmsg(4,("AudioThread::ContinuousController c=%d n=%d v=%d\n", Channel, Number, Value));
303     if (Number == 64) {
304     if (Value >= 64 && PrevHoldCCValue < 64) {
305     dmsg(4,("PEDAL DOWN\n"));
306     SustainPedal = true;
307     }
308     if (Value < 64 && PrevHoldCCValue >= 64) {
309     dmsg(4,("PEDAL UP\n"));
310     SustainPedal = false;
311 schoenebeck 15 // iterate through all keys that are currently sustained
312     for (uint* key = SustainedKeyPool->first(); key; key = SustainedKeyPool->next()) {
313 schoenebeck 18 if (!pMIDIKeyInfo[*key].KeyPressed) { // release the voices on the key, if the key is not pressed anymore
314     // release all active voices on the midi key
315     Voice** pVoicePtr = pMIDIKeyInfo[*key].pActiveVoices->first();
316     while (pVoicePtr) {
317     Voice** pVoicePtrNext = pMIDIKeyInfo[*key].pActiveVoices->next();
318     dmsg(3,("Sustain CC: releasing voice on midi key %d\n", *key));
319 schoenebeck 30 (*pVoicePtr)->Release();
320 schoenebeck 18 pVoicePtr = pVoicePtrNext;
321     }
322 schoenebeck 15 }
323 schoenebeck 30 SustainedKeyPool->free(pMIDIKeyInfo[*key].pSustainPoolNode);
324     pMIDIKeyInfo[*key].pSustainPoolNode = NULL;
325     pMIDIKeyInfo[*key].Sustained = false;
326     pMIDIKeyInfo[*key].hSustainPtr = NULL;
327 schoenebeck 12 }
328 schoenebeck 30 //SustainedKeyPool->empty();
329 schoenebeck 12 }
330     PrevHoldCCValue = Value;
331 senoner 10 }
332     }
333    
334 schoenebeck 9 void AudioThread::CacheInitialSamples(gig::Sample* pSample) {
335     if (!pSample || pSample->GetCache().Size) return;
336     if (pSample->SamplesTotal <= NUM_RAM_PRELOAD_SAMPLES) {
337     // Sample is too short for disk streaming, so we load the whole
338     // sample into RAM and place 'pAudioIO->FragmentSize << MAX_PITCH'
339     // number of '0' samples (silence samples) behind the official buffer
340     // border, to allow the interpolator do it's work even at the end of
341     // the sample.
342 schoenebeck 18 gig::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension((pAudioIO->FragmentSize << MAX_PITCH) + 3);
343 schoenebeck 12 dmsg(4,("Cached %d Bytes, %d silence bytes.\n", buf.Size, buf.NullExtensionSize));
344 schoenebeck 9 }
345     else { // we only cache NUM_RAM_PRELOAD_SAMPLES and stream the other sample points from disk
346     pSample->LoadSampleData(NUM_RAM_PRELOAD_SAMPLES);
347     }
348    
349     if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush;
350     }

  ViewVC Help
Powered by ViewVC