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

Contents of /linuxsampler/trunk/src/engines/gig/DiskThread.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 333 - (show annotations) (download)
Sat Jan 1 08:18:07 2005 UTC (19 years, 3 months ago) by senkov
File size: 15417 byte(s)
* Fix a basic diskthread multichannel issue.

1 /***************************************************************************
2 * *
3 * LinuxSampler - modular, streaming capable sampler *
4 * *
5 * Copyright (C) 2003, 2004 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 <sstream>
24
25 #include "DiskThread.h"
26
27 namespace LinuxSampler { namespace gig {
28
29 // *********** DiskThread **************
30 // *
31
32
33 // just a placeholder to mark a cell in the pickup array as 'reserved'
34 Stream* DiskThread::SLOT_RESERVED = (Stream*) &SLOT_RESERVED;
35
36
37 // #########################################################################
38 // # Foreign Thread Section
39 // # (following code intended to be interface for audio thread)
40
41
42 /**
43 * Suspend disk thread, kill all active streams, clear all queues and the
44 * pickup array and reset all streams. Call this method to bring everything
45 * in the disk thread to day one. If the disk thread was running, it will be
46 * respawned right after everything was reset.
47 */
48 void DiskThread::Reset() {
49 bool running = this->IsRunning();
50 if (running) this->StopThread();
51 for (int i = 0; i < MAX_INPUT_STREAMS; i++) {
52 pStreams[i]->Kill();
53 }
54 for (int i = 1; i <= MAX_INPUT_STREAMS; i++) {
55 pCreatedStreams[i] = NULL;
56 }
57 GhostQueue->init();
58 CreationQueue->init();
59 DeletionQueue->init();
60 ActiveStreamCount = 0;
61 ActiveStreamCountMax = 0;
62 if (running) this->StartThread(); // start thread only if it was running before
63 }
64
65 String DiskThread::GetBufferFillBytes() {
66 bool activestreams = false;
67 std::stringstream ss;
68 for (uint i = 0; i < this->Streams; i++) {
69 if (pStreams[i]->GetState() == Stream::state_unused) continue;
70 uint bufferfill = pStreams[i]->GetReadSpace() * sizeof(sample_t);
71 uint streamid = (uint) pStreams[i]->GetHandle();
72 if (!streamid) continue;
73
74 if (activestreams) ss << ",[" << streamid << ']' << bufferfill;
75 else {
76 ss << '[' << streamid << ']' << bufferfill;
77 activestreams = true;
78 }
79 }
80 return ss.str();
81 }
82
83 String DiskThread::GetBufferFillPercentage() {
84 bool activestreams = false;
85 std::stringstream ss;
86 for (uint i = 0; i < this->Streams; i++) {
87 if (pStreams[i]->GetState() == Stream::state_unused) continue;
88 uint bufferfill = (uint) ((float) pStreams[i]->GetReadSpace() / (float) STREAM_BUFFER_SIZE * 100);
89 uint streamid = (uint) pStreams[i]->GetHandle();
90 if (!streamid) continue;
91
92 if (activestreams) ss << ",[" << streamid << ']' << bufferfill << '%';
93 else {
94 ss << '[' << streamid << ']' << bufferfill;
95 activestreams = true;
96 }
97 }
98 return ss.str();
99 }
100
101 /**
102 * Returns -1 if command queue or pickup pool is full, 0 on success (will be
103 * called by audio thread within the voice class).
104 */
105 int DiskThread::OrderNewStream(Stream::reference_t* pStreamRef, ::gig::Sample* pSample, unsigned long SampleOffset, bool DoLoop) {
106 dmsg(4,("Disk Thread: new stream ordered\n"));
107 if (CreationQueue->write_space() < 1) {
108 dmsg(1,("DiskThread: Order queue full!\n"));
109 return -1;
110 }
111
112 const Stream::OrderID_t newOrder = CreateOrderID();
113 if (!newOrder) {
114 dmsg(1,("DiskThread: there was no free slot\n"));
115 return -1; // there was no free slot
116 }
117
118 pStreamRef->State = Stream::state_active;
119 pStreamRef->OrderID = newOrder;
120 pStreamRef->hStream = CreateHandle();
121 pStreamRef->pStream = NULL; // a stream has to be activated by the disk thread first
122
123 create_command_t cmd;
124 cmd.OrderID = pStreamRef->OrderID;
125 cmd.hStream = pStreamRef->hStream;
126 cmd.pStreamRef = pStreamRef;
127 cmd.pSample = pSample;
128 cmd.SampleOffset = SampleOffset;
129 cmd.DoLoop = DoLoop;
130
131 CreationQueue->push(&cmd);
132 return 0;
133 }
134
135 /**
136 * Returns -1 if command queue is full, 0 on success (will be called by audio
137 * thread within the voice class).
138 */
139 int DiskThread::OrderDeletionOfStream(Stream::reference_t* pStreamRef) {
140 dmsg(4,("Disk Thread: stream deletion ordered\n"));
141 if (DeletionQueue->write_space() < 1) {
142 dmsg(1,("DiskThread: Deletion queue full!\n"));
143 return -1;
144 }
145
146 delete_command_t cmd;
147 cmd.pStream = pStreamRef->pStream;
148 cmd.hStream = pStreamRef->hStream;
149 cmd.OrderID = pStreamRef->OrderID;
150
151 DeletionQueue->push(&cmd);
152 return 0;
153 }
154
155 /**
156 * Returns the pointer to a disk stream if the ordered disk stream
157 * represented by the \a StreamOrderID was already activated by the disk
158 * thread, returns NULL otherwise. If the call was successful, thus if it
159 * returned a valid stream pointer, the caller has to the store that pointer
160 * by himself, because it's not possible to call this method again with the
161 * same used order ID; this method is just intended for picking up an ordered
162 * disk stream. This method will usually be called by the voice class (within
163 * the audio thread).
164 *
165 * @param StreamOrderID - ID previously returned by OrderNewStream()
166 * @returns pointer to created stream object, NULL otherwise
167 */
168 Stream* DiskThread::AskForCreatedStream(Stream::OrderID_t StreamOrderID) {
169 dmsg(4,("Disk Thread: been asked if stream already created, OrderID=%x ", StreamOrderID));
170 Stream* pStream = pCreatedStreams[StreamOrderID];
171 if (pStream && pStream != SLOT_RESERVED) {
172 dmsg(4,("(yes created)\n"));
173 pCreatedStreams[StreamOrderID] = NULL; // free the slot for a new order
174 return pStream;
175 }
176 dmsg(4,("(no not yet created)\n"));
177 return NULL;
178 }
179
180
181
182 // #########################################################################
183 // # Disk Thread Only Section
184 // # (following code should only be executed by the disk thread)
185
186
187 DiskThread::DiskThread(uint BufferWrapElements) : Thread(false, 1, -2) {
188 CreationQueue = new RingBuffer<create_command_t>(1024);
189 DeletionQueue = new RingBuffer<delete_command_t>(1024);
190 GhostQueue = new RingBuffer<Stream::Handle>(MAX_INPUT_STREAMS);
191 Streams = MAX_INPUT_STREAMS;
192 RefillStreamsPerRun = REFILL_STREAMS_PER_RUN;
193 for (int i = 0; i < MAX_INPUT_STREAMS; i++) {
194 pStreams[i] = new Stream(STREAM_BUFFER_SIZE, BufferWrapElements); // 131072 sample words
195 }
196 for (int i = 1; i <= MAX_INPUT_STREAMS; i++) {
197 pCreatedStreams[i] = NULL;
198 }
199 }
200
201 DiskThread::~DiskThread() {
202 for (int i = 0; i < MAX_INPUT_STREAMS; i++) {
203 if (pStreams[i]) delete pStreams[i];
204 }
205 if (CreationQueue) delete CreationQueue;
206 if (DeletionQueue) delete DeletionQueue;
207 if (GhostQueue) delete GhostQueue;
208 }
209
210 int DiskThread::Main() {
211 dmsg(3,("Disk thread running\n"));
212 while (true) {
213 IsIdle = true; // will be set to false if a stream got filled
214
215 // if there are ghost streams, delete them
216 for (int i = 0; i < GhostQueue->read_space(); i++) { //FIXME: unefficient
217 Stream::Handle hGhostStream;
218 GhostQueue->pop(&hGhostStream);
219 bool found = false;
220 for (int i = 0; i < this->Streams; i++) {
221 if (pStreams[i]->GetHandle() == hGhostStream) {
222 pStreams[i]->Kill();
223 found = true;
224 break;
225 }
226 }
227 if (!found) GhostQueue->push(&hGhostStream); // put ghost stream handle back to the queue
228 }
229
230 // if there are creation commands, create new streams
231 while (Stream::UnusedStreams > 0 && CreationQueue->read_space() > 0) {
232 create_command_t command;
233 CreationQueue->pop(&command);
234 CreateStream(command);
235 }
236
237 // if there are deletion commands, delete those streams
238 while (Stream::UnusedStreams < Stream::TotalStreams && DeletionQueue->read_space() > 0) {
239 delete_command_t command;
240 DeletionQueue->pop(&command);
241 DeleteStream(command);
242 }
243
244 RefillStreams(); // refill the most empty streams
245
246 // if nothing was done during this iteration (eg no streambuffer
247 // filled with data) then sleep for 50ms
248 if (IsIdle) usleep(30000);
249
250 int streamsInUsage = 0;
251 for (int i = Streams - 1; i >= 0; i--) {
252 if (pStreams[i]->GetState() != Stream::state_unused) streamsInUsage++;
253 }
254 ActiveStreamCount = streamsInUsage;
255 if (streamsInUsage > ActiveStreamCountMax) ActiveStreamCountMax = streamsInUsage;
256 }
257
258 return EXIT_FAILURE;
259 }
260
261 void DiskThread::CreateStream(create_command_t& Command) {
262 // search for unused stream
263 Stream* newstream = NULL;
264 for (int i = Streams - 1; i >= 0; i--) {
265 if (pStreams[i]->GetState() == Stream::state_unused) {
266 newstream = pStreams[i];
267 break;
268 }
269 }
270 if (!newstream) {
271 std::cerr << "No unused stream found (OrderID:" << Command.OrderID << ") - report if this happens, this is a bug!\n" << std::flush;
272 return;
273 }
274 newstream->Launch(Command.hStream, Command.pStreamRef, Command.pSample, Command.SampleOffset, Command.DoLoop);
275 dmsg(4,("new Stream launched by disk thread (OrderID:%d,StreamHandle:%d)\n", Command.OrderID, Command.hStream));
276 if (pCreatedStreams[Command.OrderID] != SLOT_RESERVED) {
277 std::cerr << "DiskThread: Slot " << Command.OrderID << " already occupied! Please report this!\n" << std::flush;
278 newstream->Kill();
279 return;
280 }
281 pCreatedStreams[Command.OrderID] = newstream;
282 }
283
284 void DiskThread::DeleteStream(delete_command_t& Command) {
285 if (Command.pStream) Command.pStream->Kill();
286 else { // the stream wasn't created by disk thread or picked up by audio thread yet
287
288 // if stream was created but not picked up yet
289 Stream* pStream = pCreatedStreams[Command.OrderID];
290 if (pStream && pStream != SLOT_RESERVED) {
291 pStream->Kill();
292 pCreatedStreams[Command.OrderID] = NULL; // free slot for new order
293 return;
294 }
295
296 // the stream was not created yet
297 if (GhostQueue->write_space() > 0) {
298 GhostQueue->push(&Command.hStream);
299 }
300 else dmsg(1,("DiskThread: GhostQueue full!\n"));
301 }
302 }
303
304 void DiskThread::RefillStreams() {
305 // sort the streams by most empty stream
306 qsort(pStreams, Streams, sizeof(Stream*), CompareStreamWriteSpace);
307
308 // refill the most empty streams
309 for (uint i = 0; i < RefillStreamsPerRun; i++) {
310 if (pStreams[i]->GetState() == Stream::state_active) {
311
312 //float filledpercentage = (float) pStreams[i]->GetReadSpace() / 131072.0 * 100.0;
313 //dmsg(("\nbuffer fill: %.1f%\n", filledpercentage));
314
315 int writespace = pStreams[i]->GetWriteSpaceToEnd();
316 if (writespace == 0) break;
317
318 int capped_writespace = writespace;
319 // if there is too much buffer space available then cut the read/write
320 // size to MAX_REFILL_SIZE which is by default 65536 samples = 256KBytes
321 if (writespace > MAX_REFILL_SIZE) capped_writespace = MAX_REFILL_SIZE;
322
323 // adjust the amount to read in order to ensure that the buffer wraps correctly
324 int read_amount = pStreams[i]->AdjustWriteSpaceToAvoidBoundary(writespace, capped_writespace);
325 // if we wasn't able to refill one of the stream buffers by more than
326 // MIN_REFILL_SIZE we'll send the disk thread to sleep later
327 if (pStreams[i]->ReadAhead(read_amount) > MIN_REFILL_SIZE) this->IsIdle = false;
328 }
329 }
330 }
331
332 /// Handle Generator
333 Stream::Handle DiskThread::CreateHandle() {
334 static uint32_t counter = 0;
335 if (counter == 0xffffffff) counter = 1; // we use '0' as 'invalid handle' only, so we skip 0
336 else counter++;
337 return counter;
338 }
339
340 /// order ID Generator
341 Stream::OrderID_t DiskThread::CreateOrderID() {
342 static Stream::OrderID_t counter(0);
343 for (int i = 0; i < MAX_INPUT_STREAMS; i++) {
344 if (counter == MAX_INPUT_STREAMS) counter = 1; // we use '0' as 'invalid order' only, so we skip 0
345 else counter++;
346 if (!pCreatedStreams[counter]) {
347 pCreatedStreams[counter] = SLOT_RESERVED; // mark this slot as reserved
348 return counter; // found empty slot
349 }
350 }
351 return 0; // no free slot
352 }
353
354
355
356 // *********** C functions **************
357 // *
358
359 /**
360 * This is the comparison function the qsort algo uses to determine if a value is
361 * bigger than another one or special in our case; if the writespace of a stream
362 * is bigger than another one.
363 */
364 int CompareStreamWriteSpace(const void* A, const void* B) {
365 Stream* a = *(Stream**) A;
366 Stream* b = *(Stream**) B;
367 return b->GetWriteSpace() - a->GetWriteSpace();
368 }
369
370 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC