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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 30 - (show 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 /***************************************************************************
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 // allocate the ActiveVoicePool (for each midi key there is a variable size linked list
32 // of pointers to Voice objects)
33 ActiveVoicePool = new RTELMemoryPool<Voice*>(MAX_AUDIO_VOICES);
34 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 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 }
44 SustainedKeyPool = new RTELMemoryPool<uint>(128);
45
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 dmsg(1,("Caching initial samples..."));
55 gig::Region* pRgn = this->pInstrument->GetFirstRegion();
56 while (pRgn) {
57 if (!pRgn->GetSample()->GetCache().Size) {
58 dmsg(2,("C"));
59 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
68 // initialize modulation system
69 ModulationSystem::Initialize(pAudioIO->Samplerate, pAudioIO->FragmentSize);
70
71 // sustain pedal value
72 PrevHoldCCValue = 0;
73 SustainPedal = 0;
74
75 dmsg(1,("OK\n"));
76 }
77
78 AudioThread::~AudioThread() {
79 ModulationSystem::Close();
80 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 dmsg(2,("Audio thread running\n"));
91
92 while (true) {
93
94 // read and process commands from the queue
95 while (true) {
96 command_t command;
97 if (!pCommandQueue->pop(&command)) break;
98
99 switch (command.type) {
100 case command_type_note_on:
101 dmsg(5,("Audio Thread: Note on received\n"));
102 ProcessNoteOn(command.pitch, command.velocity);
103 break;
104 case command_type_note_off:
105 dmsg(5,("Audio Thread: Note off received\n"));
106 ProcessNoteOff(command.pitch, command.velocity);
107 break;
108 case command_type_continuous_controller:
109 dmsg(5,("Audio Thread: MIDI CC received\n"));
110 ProcessControlChange(command.channel, command.number, command.value);
111 break;
112 }
113 }
114
115
116 // zero out the output sum buffer
117 memset(pAudioSumBuffer, 0, pAudioIO->FragmentSize * pAudioIO->Channels * sizeof(float));
118
119
120 // render audio from all active voices
121 int active_voices = 0;
122 for (uint i = 0; i < MAX_AUDIO_VOICES; i++) {
123 if (pVoices[i]->IsActive()) {
124 pVoices[i]->RenderAudio();
125 if (pVoices[i]->IsActive()) active_voices++; // still active
126 else { // voice reached end, is now inactive
127 KillVoice(pVoices[i]); // remove voice from the list of active voices
128 }
129 }
130 }
131 // write that to the disk thread class so that it can print it
132 // on the console for debugging purposes
133 ActiveVoiceCount = active_voices;
134 if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
135
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 sample_point = this->pAudioSumBuffer[u] * this->Volume;
142 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 void AudioThread::SendNoteOn(uint8_t Pitch, uint8_t Velocity) {
156 command_t cmd;
157 cmd.type = command_type_note_on;
158 cmd.pitch = Pitch;
159 cmd.velocity = Velocity;
160 if (this->pCommandQueue->write_space() > 0) this->pCommandQueue->push(&cmd);
161 else dmsg(1,("AudioThread: Command queue full!"));
162 }
163
164 /// 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 command_t cmd;
167 cmd.type = command_type_note_off;
168 cmd.pitch = Pitch;
169 cmd.velocity = Velocity;
170 if (this->pCommandQueue->write_space() > 0) this->pCommandQueue->push(&cmd);
171 else dmsg(1,("AudioThread: Command queue full!"));
172 }
173
174 // 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 command_t cmd;
177 cmd.type = command_type_continuous_controller;
178 cmd.channel = Channel;
179 cmd.number = Number;
180 cmd.value = Value;
181 if (this->pCommandQueue->write_space() > 0) this->pCommandQueue->push(&cmd);
182 else dmsg(1,("AudioThread: Command queue full!"));
183 }
184
185 /**
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 for (int i = 0; i < MAX_AUDIO_VOICES; i++) {
191 if (pVoices[i]->IsActive()) continue; // search for a free voice
192
193 // 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 // add (append) a new voice to the corresponding MIDIKey active voices list
199 Voice** new_voice_ptr = ActiveVoicePool->alloc_append(pMIDIKeyInfo[MIDIKey].pActiveVoices);
200 *new_voice_ptr = pVoices[i];
201 pVoices[i]->pSelfPtr = new_voice_ptr; // FIXME: hack to allow fast deallocation
202
203 // update key info
204 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 return;
210 }
211 std::cerr << "No free voice!" << std::endl << std::flush;
212 }
213
214 /**
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 void AudioThread::ProcessNoteOff(uint8_t MIDIKey, uint8_t Velocity) {
221 pMIDIKeyInfo[MIDIKey].KeyPressed = false; // the MIDI key was currently released
222 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 uint* sustainedmidikey = SustainedKeyPool->alloc();
235 *sustainedmidikey = MIDIKey;
236 pmidikey->pSustainPoolNode = sustainedmidikey;
237 pmidikey->Sustained = true;
238 }
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 }
244 else {
245 // release all active voices on the midi key
246 Voice** pVoicePtr = pmidikey->pActiveVoices->first();
247 while (pVoicePtr) {
248 Voice** pVoicePtrNext = pMIDIKeyInfo[MIDIKey].pActiveVoices->next();
249 (*pVoicePtr)->Release();
250 pVoicePtr = pVoicePtrNext;
251 }
252 }
253 }
254
255 /**
256 * 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 */
262 void AudioThread::KillVoice(Voice* pVoice) {
263 if (pVoice) {
264 if (pVoice->IsActive()) pVoice->Kill();
265
266 if (pMIDIKeyInfo[pVoice->MIDIKey].Sustained) {
267 // check if the sustain pointer has to be moved, now that we kill the voice
268 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 }
283
284 // remove the voice from the list associated with this MIDI key
285 ActiveVoicePool->free(pVoice->pSelfPtr);
286
287 // 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 }
295 dmsg(3,("Key has no more voices now\n"));
296 }
297 }
298 else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;
299 }
300
301 void AudioThread::ProcessControlChange(uint8_t Channel, uint8_t Number, uint8_t Value) {
302 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 // iterate through all keys that are currently sustained
312 for (uint* key = SustainedKeyPool->first(); key; key = SustainedKeyPool->next()) {
313 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 (*pVoicePtr)->Release();
320 pVoicePtr = pVoicePtrNext;
321 }
322 }
323 SustainedKeyPool->free(pMIDIKeyInfo[*key].pSustainPoolNode);
324 pMIDIKeyInfo[*key].pSustainPoolNode = NULL;
325 pMIDIKeyInfo[*key].Sustained = false;
326 pMIDIKeyInfo[*key].hSustainPtr = NULL;
327 }
328 //SustainedKeyPool->empty();
329 }
330 PrevHoldCCValue = Value;
331 }
332 }
333
334 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 gig::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension((pAudioIO->FragmentSize << MAX_PITCH) + 3);
343 dmsg(4,("Cached %d Bytes, %d silence bytes.\n", buf.Size, buf.NullExtensionSize));
344 }
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