• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
SyncViews

XAudio2 Code Design, Callbacks or Polling

3 posts in this topic

Been working on creating a better audio module for my game and have come across two different designs, but been unable to work out how the XAudio2 API was actually intended to be used in larger projects.


[u]Design A - Callbacks:[/u]

XAudio2 provides a number of callbacks such as when a submitted audio buffer has completed playing.

My design here is to create a worker thread in my audio module to perform the heavy lifting (as to not ever block the XAudio2 thread) which can run tasks as soon as possible, or delayed until at least some future time.

So for example, for audio that I am streaming (e.g. music), when I get an XAudio2 buffer completed thread, I can then add a task to my worker to refill and submit the buffer.

[source lang="cpp"]
STDMETHODIMP_(void) StreamSourceVoice::OnBufferEnd (THIS_ void* pBufferContext)
{
if (!completed)
audio->getWorkerThread()->addTask(
std::bind(&StreamSourceVoice::fillAndSubmitBuffer, this));
}
[/source]
I can also handle some things that need to be completed in the future completely internally. e.g. if the game wants to stop some sound, but does want any remaining effects (such as echo) to complete, I could stop the source voice, then add a destroy callback to my worker for in say 5 seconds, and the game code need not to worry about such details.
[source lang="cpp"]
void SourceVoice::end(bool finishEffects)
{
if(!finishEffects)
{
//example problem here, what if the audio worker thread had a fillAndSubmitBuffer?
//Could solve here with a mutex, but what if this was the destructor, then the mutex is invalidated as well...
//shared_ptr for everything that crosses threads?
voice->DestroyVoice();
voice = 0;
}
else
{
voice->Stop(false);
audio->getWorkerThread()->addDelayedTask(
std::bind(&StreamSourceVoice::end, this, false),
calcEffectTrailTime());
}
}
[/source]

The problem I'm having with this design is one of resource management. Mainly at the point of destroying a voice (either from the game code, or via one of my worker callbacks) how to ensure this resource is no longer accessed (e.g. due to another callback that was already pending). I think I might be able to make it work with appropriate locks and a way to cancel scheduled tasks (i.e. remove them from the task queue without executing), but I can see that getting very complex design wise.

[u]Design B - Polling[/u]
Ignore the callbacks for buffers ending and such, and just provide some audio update methods to call x times per second, since I can query the number of queued buffers and such. Right now this is seeming somewhat simpler, since XAudio2 in that case already does basically all the synchronisation work required, e.g. it is always safe to call DestroyVoice from my own thread, and XAudio2 takes care of it.

[source lang="cpp"]
void StreamSourceVoice::update()
{
if (!completed)
{
XAUDIO2_VOICE_STATE state;
voice->GetState(&state);
unsigned toFill = BUFFER_COUNT - state.BuffersQueued;
while (toFill--) fillAndSubmitBuffer();
}
}
[/source]

The potential downside is it leaves the audio I/O and decoding on the game thread, but in my tests streaming an ogg/vorbis was like 1% CPU usage for the entire app, so is that a problem anyway?



Clearly these 2 designs are very different, so I cant just change between them later. Design B seems simpler right now, but the API seems like it was built more for A, and perhaps I'm missing something and overcomplicating that designs.
0

Share this post


Link to post
Share on other sites
[quote name='SyncViews' timestamp='1340808938' post='4953348']
streaming an ogg/vorbis was like 1% CPU usage for the entire app, so is that a problem anyway?
[/quote]Of course not.
I use a method which is more or less an hybrid.
First, I decide if a sound can be completely pooled or needs to be streamed.
Streamed sounds get slightly different buffer sizes, a base value + a random value ranging about 5%. That way they don't run out of decoded samples in the same frame.
Then I allocate three buffers (same size) for each streaming sound, 1 playing, 1 queued, 1 decoded.
Callbacks just perform an atomic swap on the queue marking 1 buffer completed. The next time the game ticks (it still got a whole buffer before time runs out) it will poll everything and update accordingly.

[quote name='SyncViews' timestamp='1340808938' post='4953348']
The problem I'm having with this design is one of resource management. Mainly at the point of destroying a voice (either from the game code, or via one of my worker callbacks) how to ensure this resource is no longer accessed (e.g. due to another callback that was already pending). I think I might be able to make it work with appropriate locks and a way to cancel scheduled tasks (i.e. remove them from the task queue without executing), but I can see that getting very complex design wise.[/quote]Hopefully worker threads won't destroy a voice just because they think is reasonable. Your code must be integrated. And you cannot just have sources anyway (perhaps another component needs to compute occlusion, or a path or whatever...) so some synchronization is necessary.

In my case that's not a problem as the main thread has full control of the graph. In the exact moment a source is destroyed it will not generate new callbacks. Components destroying sources go through the main thread as well. XAudio2 guarentees this will not be a problem, unless you are running a callback in that specific instant... it was my understanding there was a lock on callbacks anyway but I'm not sure.
So I'm actually interested in some elaborations as well.
0

Share this post


Link to post
Share on other sites
Yes I was designing non-streamed sounds as well, although I have not entirely defined where I'll put the boundary, since I guess some ambient and voice stuff can be fairly long and doesn't gain much from pooling either. In testing I was able to get 2 buffers each approx 1 second to run smoothly, does the 3rd buffer gain anything except a bit
of extra time if the disk is busy or something and your decode gets delayed?

Not sure what good an atomic swap does you in the callback if the game has to poll the status of your buffer anyway? Doesn't XAUDIO2_VOICE_STATE give you that info without the callback if your polling (as per my code snippets)?


Well XAudio2 guarantees that during/after you call DestroyVoice it wont call a callback on that voice (or that voices effects chain AFAIK) and most XAudio2 methods are thread safe, except the object destruction ones (since afterwards you have no object, invalid pointer, etc if there is another thread), so the problem is what to do with callbacks on [u]my[/u] worker thread I already scheduled when it comes time for voice deletion. Which is where the problem with that end method comes from or anything else the game might do to terminate a voice, because my task queue on the my worker thread might reference it still? Guess as I said can be solved with Mutex and such, but does that effort gain anything?

I'm going to have some kind of audio graph regardless I guess, just a question of weather the game thread polls that graph x times per second to perform maintenance (load stream buffers, clear up finished sounds, etc.) or if those tasks are done as a response to an XAudio2 callback. Although having said that, the game does play with most of the graph most frames anyway to update 3D positional data and such, so polling buffer status is perhaps not much extra, and best to forget about IXAudio2VoiceCallback and having my own internal worker thread to perform related tasks (as to not block the XAudio2 thread with say mutexes and disk IO). Edited by SyncViews
0

Share this post


Link to post
Share on other sites
[quote name='SyncViews' timestamp='1340876178' post='4953596']
Not sure what good an atomic swap does you in the callback if the game has to poll the status of your buffer anyway? Doesn't XAUDIO2_VOICE_STATE give you that info without the callback if your polling (as per my code snippets)?
[/quote]No. It's not a full poll. I don't need the full information to drive this. As a side note, while the check granularity is the same **in the current implementation** event-based allows much higher precision, in case I need it in the future.[quote name='SyncViews' timestamp='1340876178' post='4953596']
so the problem is what to do with callbacks on my worker thread
[/quote]It appears I haven't got the point across. 1st: no need for worker threads to manage 1% load. 2nd: your code must be integrated so this does not happen. In my case this does not happen because the playing and the decoding are effectively decoupled.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0