text: c++ - Windows Audio / WaveInAddBuffer() blocks - Stack Overflow
  My application records audio samples from a microphone connected to my PC. So I chose the Windows WaveInXXX API to do the job. After reading the documentation I decided to avoid using the callback mechanism with WaveInProc to save me the hassle synchronizing the threads. The whole application is pretty big and I thought this would make debugging simpler. When the application requests a block of samples, I just iterate over my buffer queue, take one out, copy the data, unprepare it, prepare it and add it back to the buffer queue. Basic program structure looks like this, I hope it makes the basic program flow clear:
  FunctionAddingPreparedBuffersToTheQueue()
  while(someConditionThatEventuallyBecomesFalse)
  if(NextBufferInQueueIsMarkedDone)
  GetDataFromBuffer()
  UnpreparePrepareHeaderAndAddBuffer()
  WaitForAShortTime()
  Now the problem appears: After some time (and I am unable to reproduce the exact condition), WaveInAddBuffer() causes a deadlock although it's in the same thread as all the rest. The header for the buffer that shall be added when the deadlock happens is prepared and dwFlags == WHDR_PREPARED == 2.
  Any ideas what could cause this deadlock?
  c++ multithreading winapi audio waveform share|improve this question edited Dec 9 '13 at 15:25
  asked Dec 9 '13 at 15:18
  Even though you don't know the cause of the problem yet, try to post an SSCCE, to illustrate the problem you are facing.
  So what callback mechanism you are using, CALLBACK_NULL? At deadlock time you can break in and catch frozen thread call stacks - this is what is going to be helpful. My guess is the problem is around NextBufferInQueueIsMarkedDone and you are checking buffer flags accessing them immediately (checking for WHDR_DONE). If so, you should not be doing this, and you should obtain notification on buffer availability through callback mechanism of your preference.
  – fewu
  API reads/writes the flags on worker threads. Accessing them directly you are unable to synchronize access with the API, so you have to rely on API's return of the buffers to you and not on buffer flags you can read directly.
  I have not seen such a problem, but a guess might be something like fragmentation related to all the unprepare/prepare cycles. They are not necessary. You can do the prepare once for each buffer and then unprepare when finished recording. (Prepare locks the buffer into physical memory.) share|improve this answer answered Dec 9 '13 at 16:29
  8,7912513
  Not the answer you're looking for?	Browse other questions tagged c++ multithreading winapi audio waveform or ask your own question.	asked