/[svn]/linuxsampler/trunk/src/engines/common/VoiceBase.h
ViewVC logotype

Contents of /linuxsampler/trunk/src/engines/common/VoiceBase.h

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2216 - (show annotations) (download) (as text)
Mon Jul 25 17:21:16 2011 UTC (12 years, 8 months ago) by iliev
File MIME type: text/x-c++hdr
File size: 13594 byte(s)
* sfz: added support for sample offset (offset)

1 /***************************************************************************
2 * *
3 * LinuxSampler - modular, streaming capable sampler *
4 * *
5 * Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck *
6 * Copyright (C) 2005-2008 Christian Schoenebeck *
7 * Copyright (C) 2009-2010 Christian Schoenebeck and Grigor Iliev *
8 * *
9 * 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 *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 * This program is distributed in the hope that it will be useful, *
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
17 * GNU General Public License for more details. *
18 * *
19 * You should have received a copy of the GNU General Public License *
20 * along with this program; if not, write to the Free Software *
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
22 * MA 02111-1307 USA *
23 ***************************************************************************/
24
25 #ifndef __LS_VOICEBASE_H__
26 #define __LS_VOICEBASE_H__
27
28 #include "AbstractVoice.h"
29
30 namespace LinuxSampler {
31
32 template <class EC /* Engine Channel */, class R /* Region */, class S /* Sample */, class D /* DiskThread */>
33 class VoiceBase : public AbstractVoice {
34 public:
35 D* pDiskThread; ///< Pointer to the disk thread, to be able to order a disk stream and later to delete the stream again
36 int RealSampleWordsLeftToRead; ///< Number of samples left to read, not including the silence added for the interpolator
37
38 VoiceBase() {
39 pRegion = NULL;
40 pDiskThread = NULL;
41 }
42 virtual ~VoiceBase() { }
43
44 virtual R* GetRegion() { return pRegion; }
45
46 virtual unsigned long GetSampleCacheSize() {
47 return pSample->GetCache().Size;
48 }
49
50 /**
51 * Initializes and triggers the voice, a disk stream will be launched if
52 * needed.
53 *
54 * @param pEngineChannel - engine channel on which this voice was ordered
55 * @param itNoteOnEvent - event that caused triggering of this voice
56 * @param PitchBend - MIDI detune factor (-8192 ... +8191)
57 * @param pRegion - points to the region which provides sample wave(s) and articulation data
58 * @param VoiceType - type of this voice
59 * @param iKeyGroup - a value > 0 defines a key group in which this voice is member of
60 * @returns 0 on success, a value < 0 if the voice wasn't triggered
61 * (either due to an error or e.g. because no region is
62 * defined for the given key)
63 */
64 virtual int Trigger (
65 AbstractEngineChannel* pEngineChannel,
66 Pool<Event>::Iterator& itNoteOnEvent,
67 int PitchBend,
68 R* pRegion,
69 type_t VoiceType,
70 int iKeyGroup
71 ) {
72 this->pRegion = pRegion;
73 this->pSample = pRegion->pSample; // sample won't change until the voice is finished
74
75 return AbstractVoice::Trigger (
76 pEngineChannel, itNoteOnEvent, PitchBend, VoiceType, iKeyGroup
77 );
78 }
79
80 virtual int OrderNewStream() {
81 int res = pDiskThread->OrderNewStream (
82 &DiskStreamRef, pRegion, MaxRAMPos + GetRAMCacheOffset(), !RAMLoop
83 );
84
85 if (res < 0) {
86 dmsg(1,("Disk stream order failed!\n"));
87 KillImmediately();
88 return -1;
89 }
90
91 return 0;
92 }
93
94 /** The offset of the RAM cache from the sample start (in sample units). */
95 virtual int GetRAMCacheOffset() { return 0; }
96
97 /**
98 * Renders the audio data for this voice for the current audio fragment.
99 * The sample input data can either come from RAM (cached sample or sample
100 * part) or directly from disk. The output signal will be rendered by
101 * resampling / interpolation. If this voice is a disk streaming voice and
102 * the voice completely played back the cached RAM part of the sample, it
103 * will automatically switch to disk playback for the next RenderAudio()
104 * call.
105 *
106 * @param Samples - number of samples to be rendered in this audio fragment cycle
107 */
108 void Render(uint Samples) {
109 // select default values for synthesis mode bits
110 SYNTHESIS_MODE_SET_LOOP(SynthesisMode, false);
111
112 switch (this->PlaybackState) {
113
114 case Voice::playback_state_init:
115 this->PlaybackState = Voice::playback_state_ram; // we always start playback from RAM cache and switch then to disk if needed
116 // no break - continue with playback_state_ram
117
118 case Voice::playback_state_ram: {
119 if (RAMLoop) SYNTHESIS_MODE_SET_LOOP(SynthesisMode, true); // enable looping
120
121 // render current fragment
122 Synthesize(Samples, (sample_t*) pSample->GetCache().pStart, Delay);
123
124 if (DiskVoice) {
125 // check if we reached the allowed limit of the sample RAM cache
126 if (finalSynthesisParameters.dPos > MaxRAMPos) {
127 dmsg(5,("VoiceBase: switching to disk playback (Pos=%f)\n", finalSynthesisParameters.dPos));
128 this->PlaybackState = Voice::playback_state_disk;
129 }
130 } else if (finalSynthesisParameters.dPos >= pSample->GetCache().Size / SmplInfo.FrameSize) {
131 this->PlaybackState = Voice::playback_state_end;
132 }
133 }
134 break;
135
136 case Voice::playback_state_disk: {
137 if (!DiskStreamRef.pStream) {
138 // check if the disk thread created our ordered disk stream in the meantime
139 DiskStreamRef.pStream = pDiskThread->AskForCreatedStream(DiskStreamRef.OrderID);
140 if (!DiskStreamRef.pStream) {
141 std::cout << stderr << "Disk stream not available in time!" << std::endl << std::flush;
142 KillImmediately();
143 return;
144 }
145 DiskStreamRef.pStream->IncrementReadPos(SmplInfo.ChannelCount * (int(finalSynthesisParameters.dPos) - MaxRAMPos));
146 finalSynthesisParameters.dPos -= int(finalSynthesisParameters.dPos);
147 RealSampleWordsLeftToRead = -1; // -1 means no silence has been added yet
148 }
149
150 const int sampleWordsLeftToRead = DiskStreamRef.pStream->GetReadSpace();
151
152 // add silence sample at the end if we reached the end of the stream (for the interpolator)
153 if (DiskStreamRef.State == Stream::state_end) {
154 const int maxSampleWordsPerCycle = (GetEngine()->MaxSamplesPerCycle << CONFIG_MAX_PITCH) * SmplInfo.ChannelCount + 6; // +6 for the interpolator algorithm
155 if (sampleWordsLeftToRead <= maxSampleWordsPerCycle) {
156 // remember how many sample words there are before any silence has been added
157 if (RealSampleWordsLeftToRead < 0) RealSampleWordsLeftToRead = sampleWordsLeftToRead;
158 DiskStreamRef.pStream->WriteSilence(maxSampleWordsPerCycle - sampleWordsLeftToRead);
159 }
160 }
161
162 sample_t* ptr = (sample_t*)DiskStreamRef.pStream->GetReadPtr(); // get the current read_ptr within the ringbuffer where we read the samples from
163
164 // render current audio fragment
165 Synthesize(Samples, ptr, Delay);
166
167 const int iPos = (int) finalSynthesisParameters.dPos;
168 const int readSampleWords = iPos * SmplInfo.ChannelCount; // amount of sample words actually been read
169 DiskStreamRef.pStream->IncrementReadPos(readSampleWords);
170 finalSynthesisParameters.dPos -= iPos; // just keep fractional part of playback position
171
172 // change state of voice to 'end' if we really reached the end of the sample data
173 if (RealSampleWordsLeftToRead >= 0) {
174 RealSampleWordsLeftToRead -= readSampleWords;
175 if (RealSampleWordsLeftToRead <= 0) this->PlaybackState = Voice::playback_state_end;
176 }
177 }
178 break;
179
180 case Voice::playback_state_end:
181 std::cerr << "VoiceBase::Render(): entered with playback_state_end, this is a bug!\n" << std::flush;
182 break;
183 }
184
185 // Reset delay
186 Delay = 0;
187
188 itTriggerEvent = Pool<Event>::Iterator();
189
190 // If sample stream or release stage finished, kill the voice
191 if (PlaybackState == Voice::playback_state_end || EG1Finished()) {
192 KillImmediately();
193 }
194 }
195
196 /**
197 * Immediately kill the voice. This method should not be used to kill
198 * a normal, active voice, because it doesn't take care of things like
199 * fading down the volume level to avoid clicks and regular processing
200 * until the kill event actually occured!
201 *
202 * If it's necessary to know when the voice's disk stream was actually
203 * deleted, then one can set the optional @a bRequestNotification
204 * parameter and this method will then return the handle of the disk
205 * stream (unique identifier) and one can use this handle to poll the
206 * disk thread if this stream has been deleted. In any case this method
207 * will return immediately and will not block until the stream actually
208 * was deleted.
209 *
210 * @param bRequestNotification - (optional) whether the disk thread shall
211 * provide a notification once it deleted
212 * the respective disk stream
213 * (default=false)
214 * @returns handle to the voice's disk stream or @c Stream::INVALID_HANDLE
215 * if the voice did not use a disk stream at all
216 * @see Kill()
217 */
218 Stream::Handle KillImmediately(bool bRequestNotification = false) {
219 Stream::Handle hStream = Stream::INVALID_HANDLE;
220 if (DiskVoice && DiskStreamRef.State != Stream::state_unused) {
221 pDiskThread->OrderDeletionOfStream(&DiskStreamRef, bRequestNotification);
222 hStream = DiskStreamRef.hStream;
223 }
224 Reset();
225 return hStream;
226 }
227
228 protected:
229 S* pSample; ///< Pointer to the sample to be played back
230 R* pRegion; ///< Pointer to the articulation information of current region of this voice
231
232 virtual MidiKeyBase* GetMidiKeyInfo(int MIDIKey) {
233 EC* pChannel = static_cast<EC*>(pEngineChannel);
234 return &pChannel->pMIDIKeyInfo[MIDIKey];
235 }
236
237 virtual unsigned long GetNoteOnTime(int MIDIKey) {
238 EC* pChannel = static_cast<EC*>(pEngineChannel);
239 return pChannel->pMIDIKeyInfo[MIDIKey].NoteOnTime;
240 }
241
242 void GetFirstEventOnKey(uint8_t MIDIKey, RTList<Event>::Iterator& itEvent) {
243 EC* pChannel = static_cast<EC*>(pEngineChannel);
244 itEvent = pChannel->pMIDIKeyInfo[MIDIKey].pEvents->first();
245 }
246 };
247 } // namespace LinuxSampler
248
249 #endif /* __LS_VOICEBASE_H__ */
250

  ViewVC Help
Powered by ViewVC