/[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 1644 - (show annotations) (download)
Sat Jan 19 16:55:03 2008 UTC (16 years, 3 months ago) by persson
File size: 19503 byte(s)
* fixed memory leaks that occurred when liblinuxsampler was unloaded
* fixed a memory leak that could happen when a channel was deleted
  while notes were playing
* fixed memory management bug in ASIO driver
* optimized the SynchronizedConfig class so it doesn't wait
  unnecessarily long after an update

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 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the Free Software *
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21 * MA 02111-1307 USA *
22 ***************************************************************************/
23
24 #include <sstream>
25
26 #include "DiskThread.h"
27
28 namespace LinuxSampler { namespace gig {
29
30 // *********** DiskThread **************
31 // *
32
33
34 // just a placeholder to mark a cell in the pickup array as 'reserved'
35 Stream* DiskThread::SLOT_RESERVED = (Stream*) &SLOT_RESERVED;
36
37
38 // #########################################################################
39 // # Foreign Thread Section
40 // # (following code intended to be interface for audio thread)
41
42
43 /**
44 * Suspend disk thread, kill all active streams, clear all queues and the
45 * pickup array and reset all streams. Call this method to bring everything
46 * in the disk thread to day one. If the disk thread was running, it will be
47 * respawned right after everything was reset.
48 */
49 void DiskThread::Reset() {
50 bool running = this->IsRunning();
51 if (running) this->StopThread();
52 for (int i = 0; i < CONFIG_MAX_STREAMS; i++) {
53 pStreams[i]->Kill();
54 }
55 for (int i = 1; i <= CONFIG_MAX_STREAMS; i++) {
56 pCreatedStreams[i] = NULL;
57 }
58 GhostQueue->init();
59 CreationQueue->init();
60 DeletionQueue->init();
61 DeletionNotificationQueue.init();
62
63 // make sure that all DimensionRegions are released
64 while (DeleteDimregQueue->read_space() > 0) {
65 ::gig::DimensionRegion* dimreg;
66 DeleteDimregQueue->pop(&dimreg);
67 pInstruments->HandBackDimReg(dimreg);
68 }
69 DeleteDimregQueue->init();
70 ActiveStreamCount = 0;
71 ActiveStreamCountMax = 0;
72 if (running) this->StartThread(); // start thread only if it was running before
73 }
74
75 String DiskThread::GetBufferFillBytes() {
76 bool activestreams = false;
77 std::stringstream ss;
78 for (uint i = 0; i < this->Streams; i++) {
79 if (pStreams[i]->GetState() == Stream::state_unused) continue;
80 uint bufferfill = pStreams[i]->GetReadSpace() * sizeof(sample_t);
81 uint streamid = (uint) pStreams[i]->GetHandle();
82 if (!streamid) continue;
83
84 if (activestreams) ss << ",[" << streamid << ']' << bufferfill;
85 else {
86 ss << '[' << streamid << ']' << bufferfill;
87 activestreams = true;
88 }
89 }
90 return ss.str();
91 }
92
93 String DiskThread::GetBufferFillPercentage() {
94 bool activestreams = false;
95 std::stringstream ss;
96 for (uint i = 0; i < this->Streams; i++) {
97 if (pStreams[i]->GetState() == Stream::state_unused) continue;
98 uint bufferfill = (uint) ((float) pStreams[i]->GetReadSpace() / (float) CONFIG_STREAM_BUFFER_SIZE * 100);
99 uint streamid = (uint) pStreams[i]->GetHandle();
100 if (!streamid) continue;
101
102 if (activestreams) ss << ",[" << streamid << ']' << bufferfill << '%';
103 else {
104 ss << '[' << streamid << ']' << bufferfill;
105 activestreams = true;
106 }
107 }
108 return ss.str();
109 }
110
111 /**
112 * Returns -1 if command queue or pickup pool is full, 0 on success (will be
113 * called by audio thread within the voice class).
114 */
115 int DiskThread::OrderNewStream(Stream::reference_t* pStreamRef, ::gig::DimensionRegion* pDimRgn, unsigned long SampleOffset, bool DoLoop) {
116 dmsg(4,("Disk Thread: new stream ordered\n"));
117 if (CreationQueue->write_space() < 1) {
118 dmsg(1,("DiskThread: Order queue full!\n"));
119 return -1;
120 }
121
122 const Stream::OrderID_t newOrder = CreateOrderID();
123 if (!newOrder) {
124 dmsg(1,("DiskThread: there was no free slot\n"));
125 return -1; // there was no free slot
126 }
127
128 pStreamRef->State = Stream::state_active;
129 pStreamRef->OrderID = newOrder;
130 pStreamRef->hStream = CreateHandle();
131 pStreamRef->pStream = NULL; // a stream has to be activated by the disk thread first
132
133 create_command_t cmd;
134 cmd.OrderID = pStreamRef->OrderID;
135 cmd.hStream = pStreamRef->hStream;
136 cmd.pStreamRef = pStreamRef;
137 cmd.pDimRgn = pDimRgn;
138 cmd.SampleOffset = SampleOffset;
139 cmd.DoLoop = DoLoop;
140
141 CreationQueue->push(&cmd);
142 return 0;
143 }
144
145 /**
146 * Request the disk thread to delete the given disk stream. This method
147 * will return immediately, thus it won't block until the respective voice
148 * was actually deleted. (Called by audio thread within the Voice class).
149 *
150 * @param pStreamRef - stream that shall be deleted
151 * @param bRequestNotification - set to true in case you want to receive a
152 * notification once the stream has actually
153 * been deleted
154 * @returns 0 on success, -1 if command queue is full
155 * @see AskForDeletedStream()
156 */
157 int DiskThread::OrderDeletionOfStream(Stream::reference_t* pStreamRef, bool bRequestNotification) {
158 dmsg(4,("Disk Thread: stream deletion ordered\n"));
159 if (DeletionQueue->write_space() < 1) {
160 dmsg(1,("DiskThread: Deletion queue full!\n"));
161 return -1;
162 }
163
164 delete_command_t cmd;
165 cmd.pStream = pStreamRef->pStream;
166 cmd.hStream = pStreamRef->hStream;
167 cmd.OrderID = pStreamRef->OrderID;
168 cmd.bNotify = bRequestNotification;
169
170 DeletionQueue->push(&cmd);
171 return 0;
172 }
173
174 /**
175 * Tell the disk thread to release a dimension region that belongs
176 * to an instrument which isn't loaded anymore. The disk thread
177 * will hand back the dimension region to the instrument resource
178 * manager. (OrderDeletionOfDimreg is called from the audio thread
179 * when a voice dies.)
180 */
181 int DiskThread::OrderDeletionOfDimreg(::gig::DimensionRegion* dimreg) {
182 dmsg(4,("Disk Thread: dimreg deletion ordered\n"));
183 if (DeleteDimregQueue->write_space() < 1) {
184 dmsg(1,("DiskThread: DeleteDimreg queue full!\n"));
185 return -1;
186 }
187 DeleteDimregQueue->push(&dimreg);
188 return 0;
189 }
190
191 /**
192 * Returns the pointer to a disk stream if the ordered disk stream
193 * represented by the \a StreamOrderID was already activated by the disk
194 * thread, returns NULL otherwise. If the call was successful, thus if it
195 * returned a valid stream pointer, the caller has to the store that pointer
196 * by himself, because it's not possible to call this method again with the
197 * same used order ID; this method is just intended for picking up an ordered
198 * disk stream. This method will usually be called by the voice class (within
199 * the audio thread).
200 *
201 * @param StreamOrderID - ID previously returned by OrderNewStream()
202 * @returns pointer to created stream object, NULL otherwise
203 */
204 Stream* DiskThread::AskForCreatedStream(Stream::OrderID_t StreamOrderID) {
205 dmsg(4,("Disk Thread: been asked if stream already created, OrderID=%x ", StreamOrderID));
206 Stream* pStream = pCreatedStreams[StreamOrderID];
207 if (pStream && pStream != SLOT_RESERVED) {
208 dmsg(4,("(yes created)\n"));
209 pCreatedStreams[StreamOrderID] = NULL; // free the slot for a new order
210 return pStream;
211 }
212 dmsg(4,("(no not yet created)\n"));
213 return NULL;
214 }
215
216 /**
217 * In case the original sender requested a notification with his stream
218 * deletion order, he can use this method to poll if the respective stream
219 * has actually been deleted.
220 *
221 * @returns handle / identifier of the deleted stream, or
222 * Stream::INVALID_HANDLE if no notification present
223 */
224 Stream::Handle DiskThread::AskForDeletedStream() {
225 if (DeletionNotificationQueue.read_space()) {
226 Stream::Handle hStream;
227 DeletionNotificationQueue.pop(&hStream);
228 return hStream;
229 } else return Stream::INVALID_HANDLE; // no notification received yet
230 }
231
232
233
234 // #########################################################################
235 // # Disk Thread Only Section
236 // # (following code should only be executed by the disk thread)
237
238
239 DiskThread::DiskThread(uint BufferWrapElements, InstrumentResourceManager* pInstruments) :
240 Thread(true, false, 1, -2),
241 pInstruments(pInstruments),
242 DeletionNotificationQueue(4*CONFIG_MAX_STREAMS)
243 {
244 DecompressionBuffer = ::gig::Sample::CreateDecompressionBuffer(CONFIG_STREAM_MAX_REFILL_SIZE);
245 CreationQueue = new RingBuffer<create_command_t,false>(4*CONFIG_MAX_STREAMS);
246 DeletionQueue = new RingBuffer<delete_command_t,false>(4*CONFIG_MAX_STREAMS);
247 GhostQueue = new RingBuffer<delete_command_t,false>(CONFIG_MAX_STREAMS);
248 DeleteDimregQueue = new RingBuffer< ::gig::DimensionRegion*,false>(4*CONFIG_MAX_STREAMS);
249 Streams = CONFIG_MAX_STREAMS;
250 RefillStreamsPerRun = CONFIG_REFILL_STREAMS_PER_RUN;
251 for (int i = 0; i < CONFIG_MAX_STREAMS; i++) {
252 pStreams[i] = new Stream(&DecompressionBuffer, CONFIG_STREAM_BUFFER_SIZE, BufferWrapElements); // 131072 sample words
253 }
254 for (int i = 1; i <= CONFIG_MAX_STREAMS; i++) {
255 pCreatedStreams[i] = NULL;
256 }
257 ActiveStreamCountMax = 0;
258 }
259
260 DiskThread::~DiskThread() {
261 for (int i = 0; i < CONFIG_MAX_STREAMS; i++) {
262 if (pStreams[i]) delete pStreams[i];
263 }
264 if (CreationQueue) delete CreationQueue;
265 if (DeletionQueue) delete DeletionQueue;
266 if (GhostQueue) delete GhostQueue;
267 if (DeleteDimregQueue) delete DeleteDimregQueue;
268 ::gig::Sample::DestroyDecompressionBuffer(DecompressionBuffer);
269 }
270
271 int DiskThread::Main() {
272 dmsg(3,("Disk thread running\n"));
273 while (true) {
274 #if !defined(WIN32)
275 pthread_testcancel(); // mandatory for OSX
276 #endif
277 IsIdle = true; // will be set to false if a stream got filled
278
279 // if there are ghost streams, delete them
280 for (int i = 0; i < GhostQueue->read_space(); i++) { //FIXME: unefficient
281 delete_command_t ghostStream;
282 GhostQueue->pop(&ghostStream);
283 bool found = false;
284 for (int i = 0; i < this->Streams; i++) {
285 if (pStreams[i]->GetHandle() == ghostStream.hStream) {
286 pStreams[i]->Kill();
287 found = true;
288 // if original sender requested a notification, let him know now
289 if (ghostStream.bNotify)
290 DeletionNotificationQueue.push(&ghostStream.hStream);
291 break;
292 }
293 }
294 if (!found) GhostQueue->push(&ghostStream); // put ghost stream handle back to the queue
295 }
296
297 // if there are creation commands, create new streams
298 while (Stream::UnusedStreams > 0 && CreationQueue->read_space() > 0) {
299 create_command_t command;
300 CreationQueue->pop(&command);
301 CreateStream(command);
302 }
303
304 // if there are deletion commands, delete those streams
305 while (Stream::UnusedStreams < Stream::TotalStreams && DeletionQueue->read_space() > 0) {
306 delete_command_t command;
307 DeletionQueue->pop(&command);
308 DeleteStream(command);
309 }
310
311 // release DimensionRegions that belong to instruments
312 // that are no longer loaded
313 while (DeleteDimregQueue->read_space() > 0) {
314 ::gig::DimensionRegion* dimreg;
315 DeleteDimregQueue->pop(&dimreg);
316 pInstruments->HandBackDimReg(dimreg);
317 }
318
319 RefillStreams(); // refill the most empty streams
320
321 // if nothing was done during this iteration (eg no streambuffer
322 // filled with data) then sleep for 30ms
323 if (IsIdle) usleep(30000);
324
325 int streamsInUsage = 0;
326 for (int i = Streams - 1; i >= 0; i--) {
327 if (pStreams[i]->GetState() != Stream::state_unused) streamsInUsage++;
328 }
329 ActiveStreamCount = streamsInUsage;
330 if (streamsInUsage > ActiveStreamCountMax) ActiveStreamCountMax = streamsInUsage;
331 }
332
333 return EXIT_FAILURE;
334 }
335
336 void DiskThread::CreateStream(create_command_t& Command) {
337 // search for unused stream
338 Stream* newstream = NULL;
339 for (int i = Streams - 1; i >= 0; i--) {
340 if (pStreams[i]->GetState() == Stream::state_unused) {
341 newstream = pStreams[i];
342 break;
343 }
344 }
345 if (!newstream) {
346 std::cerr << "No unused stream found (OrderID:" << Command.OrderID << ") - report if this happens, this is a bug!\n" << std::flush;
347 return;
348 }
349 newstream->Launch(Command.hStream, Command.pStreamRef, Command.pDimRgn, Command.SampleOffset, Command.DoLoop);
350 dmsg(4,("new Stream launched by disk thread (OrderID:%d,StreamHandle:%d)\n", Command.OrderID, Command.hStream));
351 if (pCreatedStreams[Command.OrderID] != SLOT_RESERVED) {
352 std::cerr << "DiskThread: Slot " << Command.OrderID << " already occupied! Please report this!\n" << std::flush;
353 newstream->Kill();
354 return;
355 }
356 pCreatedStreams[Command.OrderID] = newstream;
357 }
358
359 void DiskThread::DeleteStream(delete_command_t& Command) {
360 if (Command.pStream) Command.pStream->Kill();
361 else { // the stream wasn't created by disk thread or picked up by audio thread yet
362
363 // if stream was created but not picked up yet
364 Stream* pStream = pCreatedStreams[Command.OrderID];
365 if (pStream && pStream != SLOT_RESERVED) {
366 pStream->Kill();
367 pCreatedStreams[Command.OrderID] = NULL; // free slot for new order
368 // if original sender requested a notification, let him know now
369 if (Command.bNotify)
370 DeletionNotificationQueue.push(&Command.hStream);
371 return;
372 }
373
374 // the stream was not created yet
375 if (GhostQueue->write_space() > 0) {
376 GhostQueue->push(&Command);
377 } else { // error, queue full
378 if (Command.bNotify) {
379 dmsg(1,("DiskThread: GhostQueue full! (might lead to dead lock with instrument editor!)\n"));
380 } else {
381 dmsg(1,("DiskThread: GhostQueue full!\n"));
382 }
383 }
384 }
385 }
386
387 void DiskThread::RefillStreams() {
388 // sort the streams by most empty stream
389 qsort(pStreams, Streams, sizeof(Stream*), CompareStreamWriteSpace);
390
391 // refill the most empty streams
392 for (uint i = 0; i < RefillStreamsPerRun; i++) {
393 if (pStreams[i]->GetState() == Stream::state_active) {
394
395 //float filledpercentage = (float) pStreams[i]->GetReadSpace() / 131072.0 * 100.0;
396 //dmsg(("\nbuffer fill: %.1f%\n", filledpercentage));
397
398 int writespace = pStreams[i]->GetWriteSpaceToEnd();
399 if (writespace == 0) break;
400
401 int capped_writespace = writespace;
402 // if there is too much buffer space available then cut the read/write
403 // size to CONFIG_STREAM_MAX_REFILL_SIZE which is by default 65536 samples = 256KBytes
404 if (writespace > CONFIG_STREAM_MAX_REFILL_SIZE) capped_writespace = CONFIG_STREAM_MAX_REFILL_SIZE;
405
406 // adjust the amount to read in order to ensure that the buffer wraps correctly
407 int read_amount = pStreams[i]->AdjustWriteSpaceToAvoidBoundary(writespace, capped_writespace);
408 // if we wasn't able to refill one of the stream buffers by more than
409 // CONFIG_STREAM_MIN_REFILL_SIZE we'll send the disk thread to sleep later
410 if (pStreams[i]->ReadAhead(read_amount) > CONFIG_STREAM_MIN_REFILL_SIZE) this->IsIdle = false;
411 }
412 }
413 }
414
415 /// Handle Generator
416 Stream::Handle DiskThread::CreateHandle() {
417 static uint32_t counter = 0;
418 if (counter == 0xffffffff) counter = 1; // we use '0' as 'invalid handle' only, so we skip 0
419 else counter++;
420 return counter;
421 }
422
423 /// order ID Generator
424 Stream::OrderID_t DiskThread::CreateOrderID() {
425 static Stream::OrderID_t counter(0);
426 for (int i = 0; i < CONFIG_MAX_STREAMS; i++) {
427 if (counter == CONFIG_MAX_STREAMS) counter = 1; // we use '0' as 'invalid order' only, so we skip 0
428 else counter++;
429 if (!pCreatedStreams[counter]) {
430 pCreatedStreams[counter] = SLOT_RESERVED; // mark this slot as reserved
431 return counter; // found empty slot
432 }
433 }
434 return 0; // no free slot
435 }
436
437
438
439 // *********** C functions **************
440 // *
441
442 /**
443 * This is the comparison function the qsort algo uses to determine if a value is
444 * bigger than another one or special in our case; if the writespace of a stream
445 * is bigger than another one.
446 */
447 int CompareStreamWriteSpace(const void* A, const void* B) {
448 Stream* a = *(Stream**) A;
449 Stream* b = *(Stream**) B;
450 return b->GetWriteSpace() - a->GetWriteSpace();
451 }
452
453 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC