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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 53 by schoenebeck, Mon Apr 26 17:15:51 2004 UTC revision 1481 by senoner, Wed Nov 14 23:42:15 2007 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003 by Benno Senoner                                   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6     *   Copyright (C) 2005 - 2007 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   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  *   *   it under the terms of the GNU General Public License as published by  *
# Line 48  namespace LinuxSampler { namespace gig { Line 49  namespace LinuxSampler { namespace gig {
49      void DiskThread::Reset() {      void DiskThread::Reset() {
50          bool running = this->IsRunning();          bool running = this->IsRunning();
51          if (running) this->StopThread();          if (running) this->StopThread();
52          for (int i = 0; i < MAX_INPUT_STREAMS; i++) {          for (int i = 0; i < CONFIG_MAX_STREAMS; i++) {
53              pStreams[i]->Kill();              pStreams[i]->Kill();
54          }          }
55          for (int i = 1; i <= MAX_INPUT_STREAMS; i++) {          for (int i = 1; i <= CONFIG_MAX_STREAMS; i++) {
56              pCreatedStreams[i] = NULL;              pCreatedStreams[i] = NULL;
57          }          }
58          GhostQueue->init();          GhostQueue->init();
59          CreationQueue->init();          CreationQueue->init();
60          DeletionQueue->init();          DeletionQueue->init();
61            DeletionNotificationQueue.init();
62            DeleteDimregQueue->init();
63          ActiveStreamCount = 0;          ActiveStreamCount = 0;
64          ActiveStreamCountMax = 0;          ActiveStreamCountMax = 0;
65          if (running) this->StartThread(); // start thread only if it was running before          if (running) this->StartThread(); // start thread only if it was running before
# Line 85  namespace LinuxSampler { namespace gig { Line 88  namespace LinuxSampler { namespace gig {
88          std::stringstream ss;          std::stringstream ss;
89          for (uint i = 0; i < this->Streams; i++) {          for (uint i = 0; i < this->Streams; i++) {
90              if (pStreams[i]->GetState() == Stream::state_unused) continue;              if (pStreams[i]->GetState() == Stream::state_unused) continue;
91              uint bufferfill = (uint) ((float) pStreams[i]->GetReadSpace() / (float) STREAM_BUFFER_SIZE * 100);              uint bufferfill = (uint) ((float) pStreams[i]->GetReadSpace() / (float) CONFIG_STREAM_BUFFER_SIZE * 100);
92              uint streamid   = (uint) pStreams[i]->GetHandle();              uint streamid   = (uint) pStreams[i]->GetHandle();
93              if (!streamid) continue;              if (!streamid) continue;
94    
# Line 102  namespace LinuxSampler { namespace gig { Line 105  namespace LinuxSampler { namespace gig {
105       * Returns -1 if command queue or pickup pool is full, 0 on success (will be       * Returns -1 if command queue or pickup pool is full, 0 on success (will be
106       * called by audio thread within the voice class).       * called by audio thread within the voice class).
107       */       */
108      int DiskThread::OrderNewStream(Stream::reference_t* pStreamRef, ::gig::Sample* pSample, unsigned long SampleOffset, bool DoLoop) {      int DiskThread::OrderNewStream(Stream::reference_t* pStreamRef, ::gig::DimensionRegion* pDimRgn, unsigned long SampleOffset, bool DoLoop) {
109          dmsg(4,("Disk Thread: new stream ordered\n"));          dmsg(4,("Disk Thread: new stream ordered\n"));
110          if (CreationQueue->write_space() < 1) {          if (CreationQueue->write_space() < 1) {
111              dmsg(1,("DiskThread: Order queue full!\n"));              dmsg(1,("DiskThread: Order queue full!\n"));
112              return -1;              return -1;
113          }          }
114    
115            const Stream::OrderID_t newOrder = CreateOrderID();
116            if (!newOrder) {
117                    dmsg(1,("DiskThread: there was no free slot\n"));
118                    return -1; // there was no free slot
119            }
120    
121          pStreamRef->State   = Stream::state_active;          pStreamRef->State   = Stream::state_active;
122          pStreamRef->OrderID = CreateOrderID();          pStreamRef->OrderID = newOrder;
123          pStreamRef->hStream = CreateHandle();          pStreamRef->hStream = CreateHandle();
124          pStreamRef->pStream = NULL; // a stream has to be activated by the disk thread first          pStreamRef->pStream = NULL; // a stream has to be activated by the disk thread first
125    
         if (!pStreamRef->OrderID) return -1; // there was no free slot  
   
126          create_command_t cmd;          create_command_t cmd;
127          cmd.OrderID      = pStreamRef->OrderID;          cmd.OrderID      = pStreamRef->OrderID;
128          cmd.hStream      = pStreamRef->hStream;          cmd.hStream      = pStreamRef->hStream;
129          cmd.pStreamRef   = pStreamRef;          cmd.pStreamRef   = pStreamRef;
130          cmd.pSample      = pSample;          cmd.pDimRgn      = pDimRgn;
131          cmd.SampleOffset = SampleOffset;          cmd.SampleOffset = SampleOffset;
132          cmd.DoLoop       = DoLoop;          cmd.DoLoop       = DoLoop;
133    
# Line 129  namespace LinuxSampler { namespace gig { Line 136  namespace LinuxSampler { namespace gig {
136      }      }
137    
138      /**      /**
139       * Returns -1 if command queue is full, 0 on success (will be called by audio       * Request the disk thread to delete the given disk stream. This method
140       * thread within the voice class).       * will return immediately, thus it won't block until the respective voice
141         * was actually deleted. (Called by audio thread within the Voice class).
142         *
143         * @param pStreamRef           - stream that shall be deleted
144         * @param bRequestNotification - set to true in case you want to receive a
145         *                               notification once the stream has actually
146         *                               been deleted
147         * @returns 0 on success, -1 if command queue is full
148         * @see AskForDeletedStream()
149       */       */
150      int DiskThread::OrderDeletionOfStream(Stream::reference_t* pStreamRef) {      int DiskThread::OrderDeletionOfStream(Stream::reference_t* pStreamRef, bool bRequestNotification) {
151          dmsg(4,("Disk Thread: stream deletion ordered\n"));          dmsg(4,("Disk Thread: stream deletion ordered\n"));
152          if (DeletionQueue->write_space() < 1) {          if (DeletionQueue->write_space() < 1) {
153              dmsg(1,("DiskThread: Deletion queue full!\n"));              dmsg(1,("DiskThread: Deletion queue full!\n"));
# Line 143  namespace LinuxSampler { namespace gig { Line 158  namespace LinuxSampler { namespace gig {
158          cmd.pStream = pStreamRef->pStream;          cmd.pStream = pStreamRef->pStream;
159          cmd.hStream = pStreamRef->hStream;          cmd.hStream = pStreamRef->hStream;
160          cmd.OrderID = pStreamRef->OrderID;          cmd.OrderID = pStreamRef->OrderID;
161            cmd.bNotify = bRequestNotification;
162    
163          DeletionQueue->push(&cmd);          DeletionQueue->push(&cmd);
164          return 0;          return 0;
165      }      }
166    
167      /**      /**
168         * Tell the disk thread to release a dimension region that belongs
169         * to an instrument which isn't loaded anymore. The disk thread
170         * will hand back the dimension region to the instrument resource
171         * manager. (OrderDeletionOfDimreg is called from the audio thread
172         * when a voice dies.)
173         */
174        int DiskThread::OrderDeletionOfDimreg(::gig::DimensionRegion* dimreg) {
175            dmsg(4,("Disk Thread: dimreg deletion ordered\n"));
176            if (DeleteDimregQueue->write_space() < 1) {
177                dmsg(1,("DiskThread: DeleteDimreg queue full!\n"));
178                return -1;
179            }
180            DeleteDimregQueue->push(&dimreg);
181            return 0;
182        }
183    
184        /**
185       * Returns the pointer to a disk stream if the ordered disk stream       * Returns the pointer to a disk stream if the ordered disk stream
186       * represented by the \a StreamOrderID was already activated by the disk       * represented by the \a StreamOrderID was already activated by the disk
187       * thread, returns NULL otherwise. If the call was successful, thus if it       * thread, returns NULL otherwise. If the call was successful, thus if it
# Line 173  namespace LinuxSampler { namespace gig { Line 206  namespace LinuxSampler { namespace gig {
206          return NULL;          return NULL;
207      }      }
208    
209        /**
210         * In case the original sender requested a notification with his stream
211         * deletion order, he can use this method to poll if the respective stream
212         * has actually been deleted.
213         *
214         * @returns handle / identifier of the deleted stream, or
215         *          Stream::INVALID_HANDLE if no notification present
216         */
217        Stream::Handle DiskThread::AskForDeletedStream() {
218            if (DeletionNotificationQueue.read_space()) {
219                Stream::Handle hStream;
220                DeletionNotificationQueue.pop(&hStream);
221                return hStream;
222            } else return Stream::INVALID_HANDLE; // no notification received yet
223        }
224    
225    
226    
227      // #########################################################################      // #########################################################################
# Line 180  namespace LinuxSampler { namespace gig { Line 229  namespace LinuxSampler { namespace gig {
229      // #         (following code should only be executed by the disk thread)      // #         (following code should only be executed by the disk thread)
230    
231    
232      DiskThread::DiskThread(uint BufferWrapElements) : Thread(false, 1, -2) {      DiskThread::DiskThread(uint BufferWrapElements, InstrumentResourceManager* pInstruments) :
233          CreationQueue       = new RingBuffer<create_command_t>(1024);          Thread(true, false, 1, -2),
234          DeletionQueue       = new RingBuffer<delete_command_t>(1024);          pInstruments(pInstruments),
235          GhostQueue          = new RingBuffer<Stream::Handle>(MAX_INPUT_STREAMS);          DeletionNotificationQueue(4*CONFIG_MAX_STREAMS)
236          Streams             = MAX_INPUT_STREAMS;      {
237          RefillStreamsPerRun = REFILL_STREAMS_PER_RUN;          DecompressionBuffer = ::gig::Sample::CreateDecompressionBuffer(CONFIG_STREAM_MAX_REFILL_SIZE);
238          for (int i = 0; i < MAX_INPUT_STREAMS; i++) {          CreationQueue       = new RingBuffer<create_command_t,false>(4*CONFIG_MAX_STREAMS);
239              pStreams[i] = new Stream(STREAM_BUFFER_SIZE, BufferWrapElements); // 131072 sample words          DeletionQueue       = new RingBuffer<delete_command_t,false>(4*CONFIG_MAX_STREAMS);
240            GhostQueue          = new RingBuffer<delete_command_t,false>(CONFIG_MAX_STREAMS);
241            DeleteDimregQueue   = new RingBuffer< ::gig::DimensionRegion*,false>(4*CONFIG_MAX_STREAMS);
242            Streams             = CONFIG_MAX_STREAMS;
243            RefillStreamsPerRun = CONFIG_REFILL_STREAMS_PER_RUN;
244            for (int i = 0; i < CONFIG_MAX_STREAMS; i++) {
245                pStreams[i] = new Stream(&DecompressionBuffer, CONFIG_STREAM_BUFFER_SIZE, BufferWrapElements); // 131072 sample words
246          }          }
247          for (int i = 1; i <= MAX_INPUT_STREAMS; i++) {          for (int i = 1; i <= CONFIG_MAX_STREAMS; i++) {
248              pCreatedStreams[i] = NULL;              pCreatedStreams[i] = NULL;
249          }          }
250            ActiveStreamCountMax = 0;
251      }      }
252    
253      DiskThread::~DiskThread() {      DiskThread::~DiskThread() {
254          for (int i = 0; i < MAX_INPUT_STREAMS; i++) {          for (int i = 0; i < CONFIG_MAX_STREAMS; i++) {
255              if (pStreams[i]) delete pStreams[i];              if (pStreams[i]) delete pStreams[i];
256          }          }
257          if (CreationQueue) delete CreationQueue;          if (CreationQueue) delete CreationQueue;
258          if (DeletionQueue) delete DeletionQueue;          if (DeletionQueue) delete DeletionQueue;
259          if (GhostQueue)    delete GhostQueue;          if (GhostQueue)    delete GhostQueue;
260            if (DeleteDimregQueue) delete DeleteDimregQueue;
261            ::gig::Sample::DestroyDecompressionBuffer(DecompressionBuffer);
262      }      }
263    
264      int DiskThread::Main() {      int DiskThread::Main() {
265          dmsg(3,("Disk thread running\n"));          dmsg(3,("Disk thread running\n"));
266          while (true) {          while (true) {
267                #if !defined(WIN32)
268                pthread_testcancel(); // mandatory for OSX
269                #endif
270              IsIdle = true; // will be set to false if a stream got filled              IsIdle = true; // will be set to false if a stream got filled
271    
272              // if there are ghost streams, delete them              // if there are ghost streams, delete them
273              for (int i = 0; i < GhostQueue->read_space(); i++) { //FIXME: unefficient              for (int i = 0; i < GhostQueue->read_space(); i++) { //FIXME: unefficient
274                  Stream::Handle hGhostStream;                  delete_command_t ghostStream;
275                  GhostQueue->pop(&hGhostStream);                  GhostQueue->pop(&ghostStream);
276                  bool found = false;                  bool found = false;
277                  for (int i = 0; i < this->Streams; i++) {                  for (int i = 0; i < this->Streams; i++) {
278                      if (pStreams[i]->GetHandle() == hGhostStream) {                      if (pStreams[i]->GetHandle() == ghostStream.hStream) {
279                          pStreams[i]->Kill();                          pStreams[i]->Kill();
280                          found = true;                          found = true;
281                            // if original sender requested a notification, let him know now
282                            if (ghostStream.bNotify)
283                                DeletionNotificationQueue.push(&ghostStream.hStream);
284                          break;                          break;
285                      }                      }
286                  }                  }
287                  if (!found) GhostQueue->push(&hGhostStream); // put ghost stream handle back to the queue                  if (!found) GhostQueue->push(&ghostStream); // put ghost stream handle back to the queue
288              }              }
289    
290              // if there are creation commands, create new streams              // if there are creation commands, create new streams
# Line 231  namespace LinuxSampler { namespace gig { Line 295  namespace LinuxSampler { namespace gig {
295              }              }
296    
297              // if there are deletion commands, delete those streams              // if there are deletion commands, delete those streams
298              while (Stream::UnusedStreams < Streams && DeletionQueue->read_space() > 0) {              while (Stream::UnusedStreams < Stream::TotalStreams && DeletionQueue->read_space() > 0) {
299                  delete_command_t command;                  delete_command_t command;
300                  DeletionQueue->pop(&command);                  DeletionQueue->pop(&command);
301                  DeleteStream(command);                  DeleteStream(command);
302              }              }
303    
304                // release DimensionRegions that belong to instruments
305                // that are no longer loaded
306                while (DeleteDimregQueue->read_space() > 0) {
307                    ::gig::DimensionRegion* dimreg;
308                    DeleteDimregQueue->pop(&dimreg);
309                    pInstruments->HandBackDimReg(dimreg);
310                }
311    
312              RefillStreams(); // refill the most empty streams              RefillStreams(); // refill the most empty streams
313    
314              // if nothing was done during this iteration (eg no streambuffer              // if nothing was done during this iteration (eg no streambuffer
315              // filled with data) then sleep for 50ms              // filled with data) then sleep for 30ms
316              if (IsIdle) usleep(30000);              if (IsIdle) usleep(30000);
317    
318              int streamsInUsage = 0;              int streamsInUsage = 0;
# Line 267  namespace LinuxSampler { namespace gig { Line 339  namespace LinuxSampler { namespace gig {
339              std::cerr << "No unused stream found (OrderID:" << Command.OrderID << ") - report if this happens, this is a bug!\n" << std::flush;              std::cerr << "No unused stream found (OrderID:" << Command.OrderID << ") - report if this happens, this is a bug!\n" << std::flush;
340              return;              return;
341          }          }
342          newstream->Launch(Command.hStream, Command.pStreamRef, Command.pSample, Command.SampleOffset, Command.DoLoop);          newstream->Launch(Command.hStream, Command.pStreamRef, Command.pDimRgn, Command.SampleOffset, Command.DoLoop);
343          dmsg(4,("new Stream launched by disk thread (OrderID:%d,StreamHandle:%d)\n", Command.OrderID, Command.hStream));          dmsg(4,("new Stream launched by disk thread (OrderID:%d,StreamHandle:%d)\n", Command.OrderID, Command.hStream));
344          if (pCreatedStreams[Command.OrderID] != SLOT_RESERVED) {          if (pCreatedStreams[Command.OrderID] != SLOT_RESERVED) {
345              std::cerr << "DiskThread: Slot " << Command.OrderID << " already occupied! Please report this!\n" << std::flush;              std::cerr << "DiskThread: Slot " << Command.OrderID << " already occupied! Please report this!\n" << std::flush;
# Line 286  namespace LinuxSampler { namespace gig { Line 358  namespace LinuxSampler { namespace gig {
358              if (pStream && pStream != SLOT_RESERVED) {              if (pStream && pStream != SLOT_RESERVED) {
359                  pStream->Kill();                  pStream->Kill();
360                  pCreatedStreams[Command.OrderID] = NULL; // free slot for new order                  pCreatedStreams[Command.OrderID] = NULL; // free slot for new order
361                    // if original sender requested a notification, let him know now
362                    if (Command.bNotify)
363                        DeletionNotificationQueue.push(&Command.hStream);
364                  return;                  return;
365              }              }
366    
367              // the stream was not created yet              // the stream was not created yet
368              if (GhostQueue->write_space() > 0) {              if (GhostQueue->write_space() > 0) {
369                  GhostQueue->push(&Command.hStream);                  GhostQueue->push(&Command);
370                } else { // error, queue full
371                    if (Command.bNotify) {
372                        dmsg(1,("DiskThread: GhostQueue full! (might lead to dead lock with instrument editor!)\n"));
373                    } else {
374                        dmsg(1,("DiskThread: GhostQueue full!\n"));
375                    }
376              }              }
             else dmsg(1,("DiskThread: GhostQueue full!\n"));  
377          }          }
378      }      }
379    
# Line 313  namespace LinuxSampler { namespace gig { Line 393  namespace LinuxSampler { namespace gig {
393    
394                  int capped_writespace = writespace;                  int capped_writespace = writespace;
395                  // if there is too much buffer space available then cut the read/write                  // if there is too much buffer space available then cut the read/write
396                  // size to MAX_REFILL_SIZE which is by default 65536 samples = 256KBytes                  // size to CONFIG_STREAM_MAX_REFILL_SIZE which is by default 65536 samples = 256KBytes
397                  if (writespace > MAX_REFILL_SIZE) capped_writespace = MAX_REFILL_SIZE;                  if (writespace > CONFIG_STREAM_MAX_REFILL_SIZE) capped_writespace = CONFIG_STREAM_MAX_REFILL_SIZE;
398    
399                  // adjust the amount to read in order to ensure that the buffer wraps correctly                  // adjust the amount to read in order to ensure that the buffer wraps correctly
400                  int read_amount = pStreams[i]->AdjustWriteSpaceToAvoidBoundary(writespace, capped_writespace);                  int read_amount = pStreams[i]->AdjustWriteSpaceToAvoidBoundary(writespace, capped_writespace);
401                  // if we wasn't able to refill one of the stream buffers by more than                  // if we wasn't able to refill one of the stream buffers by more than
402                  // MIN_REFILL_SIZE we'll send the disk thread to sleep later                  // CONFIG_STREAM_MIN_REFILL_SIZE we'll send the disk thread to sleep later
403                  if (pStreams[i]->ReadAhead(read_amount) > MIN_REFILL_SIZE) this->IsIdle = false;                  if (pStreams[i]->ReadAhead(read_amount) > CONFIG_STREAM_MIN_REFILL_SIZE) this->IsIdle = false;
404              }              }
405          }          }
406      }      }
# Line 335  namespace LinuxSampler { namespace gig { Line 415  namespace LinuxSampler { namespace gig {
415    
416      /// order ID Generator      /// order ID Generator
417      Stream::OrderID_t DiskThread::CreateOrderID() {      Stream::OrderID_t DiskThread::CreateOrderID() {
418          static uint32_t counter = 0;          static Stream::OrderID_t counter(0);
419          for (int i = 0; i < MAX_INPUT_STREAMS; i++) {          for (int i = 0; i < CONFIG_MAX_STREAMS; i++) {
420              if (counter == MAX_INPUT_STREAMS) counter = 1; // we use '0' as 'invalid order' only, so we skip 0              if (counter == CONFIG_MAX_STREAMS) counter = 1; // we use '0' as 'invalid order' only, so we skip 0
421              else                              counter++;              else                              counter++;
422              if (!pCreatedStreams[counter]) {              if (!pCreatedStreams[counter]) {
423                  pCreatedStreams[counter] = SLOT_RESERVED; // mark this slot as reserved                  pCreatedStreams[counter] = SLOT_RESERVED; // mark this slot as reserved

Legend:
Removed from v.53  
changed lines
  Added in v.1481

  ViewVC Help
Powered by ViewVC