Category Archives: Graphics APIs

So that’s what happens when a programming language gets old…

  • Continuing with the test exec. I’m also going to need a class that records the data associated with each test segment.
  • Ran into a… Well, I don’t want to call it a bug. Let’s say that C++ is showing its age. FLTK uses char*. Most of Windows uses wchar_t. They don’t play well together, so I spent about half of my time working out the best way to convert between them. It’s this:
  • void setSoundFileString(LPCWSTR wps){
    	soundFileString = new wstring(wps);
    	string str(soundFileString->begin(), soundFileString->end());
    	sprintf_s(soundFile, "%s", str.c_str());
  • I mean really!? Good grief.
  • Got a lot of the exec built and running. Clicking on the center button fires the sound, and you can drag to where you think the sound is. I am not all that accurate. It could be a frequency thing though. I’m running a low 10-20 HZ signal. The test should definitely try different frequencies.

Closing in on something useful

  • Put all the projects into SVN, checked them out and did a clean build. Everything still works.
  • Starting on capturing mouse events. Done. Capturing Left, Middle, Right, Wheel and Drag. I think I want to have it so that the user presses (holds down?) a “button” in the middle of the GL window, signifying that he’s ready for the next sound queue. Once the sound plays, he drags toward the source. This is indicated by a line indicating the vector (and a cursor?). Releasing the mouse is the event that marks and records the choice, vector, elapsed time and position (vector?) of the emitter.
  • Making a button class for OGL. Done
  • Making a line segment class so we can point to where the sound is. Done.
  • And just to show that I’ve been paying attention in class, the user doesn’t have to worry about hitting a particular length when dragging towards the sound. Since there is essentially no source (since the test starts after the subject clicks) and no target, we don’t have to worry about any Fitts’ Law biases 🙂
  • Progress for today:
  • vth

    Start Button (red), Sound Vector and Emitter

Audio is in and synchronized to the video

Well that was a good day.

  • Spent a good deal of time trying to figure out the best way for the GUI and the Exec to communicate. Originally, I wanted to be able to pass a pointer to the GUI from the exec so that user actions in the GUI could be executed in a more reasonable place. Due to header conflicts, I couldn’t manage to get that to work, so I put together a UI_cmd class that is set in the UI and read in the Exec. That seems to be working pretty well, though I may want to put a queue in there and turn it more into a message bus/event pump. That level of sophistication isn’t needed yet though.
  • Integrated the sound library that I wrote. I still have to reference the D3D audio library in the main application which I think is a bit odd, but I think it may be because I’m incorrectly exporting the symbol table from the static library. Again, that’s a refinement for later.
  • At this point, the 3D position of my OGL shape and the 3D postion of my continuous sound (2D actually, Y = 0) are running in an infinite circle. It’s pretty cool to hear the audio track to the image. I’m uploading a video of the running system, and although it won’t be in surround, you can hear the flanging effects from the sound moving around the helmet.

Not bad for 90 minutes worth of work…

I’m busy doing demos and presentations in my day job, so this has been suffering. Nonetheless, here’s the progress for today:

  • Added a fine-grained timer callback to the main app
  • Added an OpenGL window, set to Ortho2, and with pixel-accurate dimensions
  • Connected the timer to the OpenGL, and set the position of what will be the emitter. We won’t see this during the actual test, but it will be good for debugging.
  • I need to track mouse clicks and motion in the GL window. That will come tomorrow, and then I’ll work on integrating the audio library. That’s the basics for running the experiments. After that, I’ll work on reading and writing the input and result files.
  • Pix for today: AppProgress6.18.13

Let’s make science!

Alright, so I now have my audio library. Next on the agenda is a test program that tests reactions of users to vibroacoustic input. The test needs to present randomized stimuli to users, so that they can be tested for:

  • Time to respond with a direction
  • Accuracy of direction
  • Efficacy of stimuli

Since this is probably going to be within subjects (multiple stimuli) and also between subjects (same tests on multiple users) we’re going to want to be able to present the same sequence, so we’ll need to seed the random number generator so we get the same sequence.

  • Start with the default random number generator, but maybe run through a wrapper class in case we need something like a Mersenne Twister.
  • Xml file to specify the input and output of the experiment. This library looks reasonable.
    • Input
      • Sounds to use (random distribution of sound use)
      • Test type (Accuracy, Speed, or both)
      • Attempts per test
      • Number of tests (must be even)
      • Random seed
      • min/max delay between test segments
      • output filename
    • Output
      • Test UID
      • Date
      • Time
      • Subject
      • Researcher
      • Free form note field (1024 characters?)
      • Accuracy or Reaction time test
      • Audio configuration
      • Random seed
      • Calibration results
        • Time(s) to click in response to visual cue
        • Time(s) to click in response to audio cue
      • For each played sound
        • Sequence x of total
        • Audio file(s) used (WAV)
        • Audio source position (x, y) in screen coordinates from the origin, where the user’s head is
        • Audio playback matrix (actual speaker relative volume)
        • Time to click after play start
        • Duration of sound
        • Click position (x, y) in screen coordinates from the origin, where the sound is perceived to have come from
  • App
    • Text
      • File navigator for xml file
    • Calibrate
      • Runs a sequence of tests where the user has to click the mouse as quickly as possible in response to the canvas flashing white, and then all(?) speakers in the headpiece playing the calibration sound
      • Calibration cues are have a randomly determined timing between X and Y seconds
      • Test is disabled until calibration is run. Loading a new xml document effectively resets the system, requiring a new calibration sequence
    • Test
      • Shows a label that says either “Accuracy” or “Speed” based on which test is being run. We could change the background of the display as well?
      • The graphics screen shows a circular cursor that resets to the center of the graphics screen at the beginning of each section. Once the audio cue plays, the user can move the mouse away from the center towards the direction of the sound. The circle is clamped in its motion so that the result is always a valid angle, as long as the user moves the cursor far enough away from the center (TBD). Clicking the mouse causes the clock to stop and the cursor to reset.
      • If this is not the last test segment, then a random time period between X and Y seconds elapses before the next test is run.
      • Once the test completes, the system checks to see if that is the last one. If not, a stochastic choice is made to determine if the next test should be speed or accuracy. By the time all tests have run, the number of speed and accuracy runs will be equal.
    • Output file is appended throughout the test (open, write, close? Or read in the DOM, update and write out?)

Started the FLTK wrapper, and probably saved a good deal of time by going back to Erco’s FLTK page and associated videos

Final cleanup on the proof-of concept

  • Ugh.
  • rain
  • Adding comments and velocity accessors to audio code
    • Comments are done
    • Checked in project to Subversion repo, then checked out and compiled. All seems to be working fine.
  • Cleaning up #includes
    • I had been getting the following annoying warning once I started including items like <unordered_map>: 1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\cstring(21): warning C4995: ‘strcat’: name was marked as #pragma deprecated. In the cleanup, I finally got around to testing the need for includes and deleted <strsafe.h>, which seems to be the source of my grief. Yay!
  • Ready to make the audio code a library. Monday. Then time to design the experimental interface.
  • And now that I think I know what’s going on, a good article shows up…

In the end, this is how you do it:

// create the instance
BasicAudio *ba = new BasicAudio(); 

// initialize

// create a sound from a file. In this case a WAV. There can be many of these.
ba->createSound(L"music", L"Wavs\\MusicMono.wav", 0); 

// get the instance to the sound and start(), stop(), run() etc.
	// change some audio condition

	// play the voice on a specified channel or play in 3D
	ba->playOnChannelVoice(L"music", channelIndex); 

	// optional - run periodic checks.

Starting to polish

  • I’m going to add the ability to create and store a named sound within BasicAudio. Sounds really don’t need to be created outside of the instance.
  • Lunch meeting with Shawn about R&D. Good meeting with good chili to boot.
  • Got the createSound method working and cleaned up the Console app some more
int _tmain(int argc, _TCHAR* argv[])
	BasicAudio *ba = new BasicAudio();

	wprintf( L"\nReady to play mono WAV PCM file(s)...\n" );

	WavSampleSound *singleSound = (WavSampleSound *)ba->createSound(L"music", L"Wavs\\MusicMono.wav", 0);
	WavSampleSound *continuousSound = (WavSampleSound *)ba->createSound(L"heli", L"Wavs\\heli.wav", XAUDIO2_LOOP_INFINITE);

	int keyIn;
	printf("Type 'x' to quit\nC start continuous\nc stop continuous\nS start single\n");
	bool doit = true;

	int channelIndex = -1;
			keyIn = getch();
			channelIndex = -1;

			printf("key = %c\n", keyIn);
			case 'x' : doit = false; 

			case 'C' : continuousSound->start();                  // play sound
			case 'c' : continuousSound->stop();                  // cease sound
			case 'S' : singleSound->start();						// play sound
			case 'w' : 
				continuousSound->setEmitterZ(continuousSound->getEmitterZ() + (FLOAT32)0.5);
			case 's' : 
				continuousSound->setEmitterZ(continuousSound->getEmitterZ() - (FLOAT32)0.5);
			case 'a' : 
				continuousSound->setEmitterX(continuousSound->getEmitterX() - (FLOAT32)0.5);
			case 'd' : 
				continuousSound->setEmitterX(continuousSound->getEmitterX() + (FLOAT32)0.5);
			case 'p':
			case '0' : channelIndex = 0; break;
			case '1' : channelIndex = 1; break;
			case '2' : channelIndex = 2; break;
			case '3' : channelIndex = 3; break;
			case '4' : channelIndex = 4; break;
			case '5' : channelIndex = 5; break;
			case '6' : channelIndex = 6; break;
			case '7' : channelIndex = 7; break;

			if(channelIndex == -1){
				IXAudio2SourceVoice* voice = continuousSound->getSourceVoice();
				ba->play3DVoice(continuousSound->getEmitter(), voice);
				printf("channel = %d\n", channelIndex);
				IXAudio2SourceVoice* voice = continuousSound->getSourceVoice();
				ba->playOnChannelVoice(voice, channelIndex);

		ba->run(); // perform periodic sound engine tasks

	wprintf( L"\nFinished playing\n" );

	// All XAudio2 interfaces are released when the engine is destroyed, but being tidy


	// printf("hit return to exit");
	// getchar();

	return 0;

There are days things just work

  • Making nice clean classes for audio
  • Emitter goes into the SampledSound base class – done. Almost easy, though I had to go and relearn how C++ constructors work. Gawd, it’s been a while…
  • Everything else goes into BasicAudio – done. Had some problems with frequency until I realized that I hadn’t zeroed out the listener velocity.
  • And actually, I need to be able to set velocity for doppler effects. Need to add methods like the position methods tomorrow.
  • So the classes are built, and my main() test loop is down to this:
int _tmain(int argc, _TCHAR* argv[])
	BasicAudio *ba = new BasicAudio();
	IXAudio2* pXAudio2 = ba->getXaudioPtr();
	wprintf( L"\nReady to play mono WAV PCM file(s)...\n" );

	WavSampleSound *continuousSound = new WavSampleSound();
	WavSampleSound *singleSound = new WavSampleSound();

	continuousSound->initPCM(pXAudio2, L"Wavs\\heli.wav", XAUDIO2_LOOP_INFINITE );
	singleSound->initPCM(pXAudio2, L"Wavs\\MusicMono.wav", 0 );


	int keyIn;
	printf("Type 'x' to quit\nC start continuous\nc stop continuous\nS start single\n");
	bool doit = true;

	int channelIndex = -1;
			keyIn = getch();
			channelIndex = -1;

			printf("key = %c\n", keyIn);
				case 'x' : doit = false;

				case 'C' : continuousSound->start(); // play sound
				case 'c' : continuousSound->stop(); // cease sound
				case 'S' : singleSound->start(); // play sound
				case 'w' :
				continuousSound->setEmitterZ(continuousSound->getEmitterZ() + (FLOAT32)0.5);
				case 's' :
				continuousSound->setEmitterZ(continuousSound->getEmitterZ() - (FLOAT32)0.5);
				case 'a' :
				continuousSound->setEmitterX(continuousSound->getEmitterX() - (FLOAT32)0.5);
				case 'd' :
				continuousSound->setEmitterX(continuousSound->getEmitterX() + (FLOAT32)0.5);
				case 'p':
				case '0' : channelIndex = 0; break;
				case '1' : channelIndex = 1; break;
				case '2' : channelIndex = 2; break;
				case '3' : channelIndex = 3; break;
				case '4' : channelIndex = 4; break;
				case '5' : channelIndex = 5; break;
				case '6' : channelIndex = 6; break;
				case '7' : channelIndex = 7; break;
			if(channelIndex == -1){
				IXAudio2SourceVoice* voice = continuousSound->getSourceVoice();
				ba->play3DVoice(continuousSound->getEmitter(), voice);
				printf("channel = %d\n", channelIndex);
				IXAudio2SourceVoice* voice = continuousSound->getSourceVoice();
				ba->playOnChannelVoice(voice, channelIndex);
		ba->run(); // perform periodic sound engine tasks

	wprintf( L"\nFinished playing\n" );

	// All XAudio2 interfaces are released when the engine is destroyed, but being tidy


	return 0;

Ye gods, we might actually have something to use here…

  • Well, after two days of not being able to work on this due to Comps prep and trouble with a significant fraction of my vehicles, maybe I can get something working today.
  • Added everything from How to: Integrate X3DAudio with XAudio2, and definitely got a result – when the emitter position moved off of center, the sound cut out. Now you might think that’s a bad thing, but my guess is that I have some variable that either being set with zero or junk, which is messing up the sound matrix calculations.
  • Using the XAudio2Sound3D project as a source of code to mine, I pulled over the (much more extensive) emitter setup and now have things working, although not as clearly as I’d like. Next is to clean up and package the code into the SampleSound-derived classes.
  • And by the way, this might be a good hard hat to try the rig on:
  • Cleared a lot of nonessential (i.e. listening cone)code out of the emitter
  • Realized that I could probably use voice->SetOutputMatrix() to set the channels directly. I added a method that cleans out the dspSettings.matrixCoefficients and then sets a single value in the matrix. Whadaya know – it worked 🙂
  • Need to do some packaging of the code, but I now have enough to do tests for the situational awareness system and to get rid of the MIDI boards for the vibrotactile controller.

Now that XAudio2 is clear, time to be confused with X3DAudio

  • Finished rolling up the SampleSounds(s) into BasicAudio.
  • Starting on 3D audio, using How to: Integrate X3DAudio with XAudio2
    • Adding the 3D calls to the main() in ConsoleSound2, just after the BasicAudio class has been initialized.
    • Had to add x3daudio.lib to the project and <x3daudio.h> to the #includes.
    • This looks to be the meat of the calculation. It looks like X3DCalculate() works on the relative position of an Emitter and the Listener and uses that to populate a DSP. Once that’s done, then the Audio2 source is manipulated appropriately.
    •         X3DAudioCalculate( g_audioState.x3DInstance, &g_audioState.listener, &g_audioState.emitter, dwCalcFlags,
                                 &g_audioState.dspSettings );
              IXAudio2SourceVoice* voice = g_audioState.pSourceVoice;
              if( voice )
                  // Apply X3DAudio generated DSP settings to XAudio2
                  voice->SetFrequencyRatio( g_audioState.dspSettings.DopplerFactor );
                  voice->SetOutputMatrix( g_audioState.pMasteringVoice, INPUTCHANNELS, g_audioState.nChannels,
                                          g_audioState.matrixCoefficients );
                  voice->SetOutputMatrix(g_audioState.pSubmixVoice, 1, 1, &g_audioState.dspSettings.ReverbLevel);
                  XAUDIO2_FILTER_PARAMETERS FilterParametersDirect = { LowPassFilter, 2.0f * sinf(X3DAUDIO_PI/6.0f * g_audioState.dspSettings.LPFDirectCoefficient), 1.0f }; // see XAudio2CutoffFrequencyToRadians() in XAudio2.h for more information on the formula used here
                  voice->SetOutputFilterParameters(g_audioState.pMasteringVoice, &FilterParametersDirect);
                  XAUDIO2_FILTER_PARAMETERS FilterParametersReverb = { LowPassFilter, 2.0f * sinf(X3DAUDIO_PI/6.0f * g_audioState.dspSettings.LPFReverbCoefficient), 1.0f }; // see XAudio2CutoffFrequencyToRadians() in XAudio2.h for more information on the formula used here
                  voice->SetOutputFilterParameters(g_audioState.pSubmixVoice, &FilterParametersReverb);