Interface Obscura – DXGI, DXVA, MMDevice…

If you have programmed with Windows over the years, you have been subjected to a plethora of languages, paradigms, frameworks, APIs, tectonic shifts, and the like. Why is this so? Well, because Windows is fairly old, and stuff that worked 30 years ago still works today, mostly. Hardware has evolved, gained and changed capabilities, and along with these changes, so too have the frameworks that support it.

One interesting trend that has been occurring with Windows over the past few OS releases, is that things are becoming more modular, and more properly layered. For example, the API sets that now exist in the core of Windows properly layer and segregate APIs such that you don’t have to pull in the entire world just to do a conversion from an Ansi string to a multi-byte string.

There are some parts of the system that offer up more obscure interfaces that most programmers won’t experience directly. Recently I’ve been wanting to get at the core of audio and visual stuff. In Windows, you could be using the Media Foundation framework, or you would be using the older ‘Wave’ media framework. Both of these at their core are supported by the MMDevice library. That’s an obscure library which gives you things like the names of your audio endpoints, and various attributes about them. Ultimately you can open up an audio stream on a device and get bytes out of it.

Another one, a little less obscure is the Direct X Graphics Interface (DXGI). This one gives you access to low level information about the graphics adapters and capabilities of your machine. How is it that the control panel knows about your different monitors for example? It ultimately calls down to DXGI I would bet.

Yet another one is DXVA. This one, closely related to DXGI, gives you access to graphics ‘surfaces’. This is how you can actually do high speed rendering directly to the screen for example. You can also make a high speed screen capture program, without the use of mirror drivers, because you can get a handle on the actual graphics surface that’s being used to render the screen. This is how the application and desktop thumbnails are able to be rendered.

In most cases, these interfaces are steeped in the Component Object Model (COM). COM is a fairly mature part of the system which was created to ease the task of joining disparate programming languages and system components using a common runtime infrastructure. It is the dynamic type system of Windows if you will. COM served a world where there was no universal type system, and you had to be able to marshal data across disparate libraries and application domains. If I were to do it from scratch today, I’d probably use something like LuaJIT’s ffi and just write the interfaces in standard ‘C’ headers, but this came from a different time.

Recently I wanted to get a handle on the audio endpoints of my machine, and just print out the various attributes of each endpoint. Here’s the code:

local MMDevice = require("MMDevice")

for device in MMDevice:AudioEndpoints() do
  print("Device ID: ", device:getID())

  for property in device:properties() do
    print("  Property: ", property.vt, tostring(property))
  end
end

Audio endpoints are things like ‘microphone’ and ‘speaker’. They either render sound (speaker), or capture sound (microphone). The MMDevice:AudioEndpoints() function is a typical Lua iterator on the IMMDevice interfaces that represent the various endpoints in the system. Since this is an iterator, it can be used with the Lua Fun functional programming library to do all sorts of filtering, reductions, and the like. But, in this particular case, I just want to print out the various properties associated with the endpoint.

Each device has an iterator that will feed out the properties. That is the ‘properties()’ function. Again, a standard Lua iterator which will just spew out the properties one by one. In this case, the properties are represented by a very COM like VARIANT structure. When you look it up, the VARIANT, is nothing more than a giant union of all the base types that the COM system understands. In a modern language such as Lua, I can actually return the base type instead of the boxed up union, but for now it’s good enough.

Here, the VARIANT object has a simple __tostring() implementation, to turn some of the more common types into their string equivalents, it looks something like this:

local PROPVARIANT = ffi.typeof("PROPVARIANT")
local PROPVARIANT_mt = {
    __tostring = function(self)
        if self.vt == ffi.C.VT_BLOB then
            return tostring(self.blob)
        elseif self.vt == ffi.C.VT_BOOL then
            return not (self.boolVal == 0);
        elseif self.vt == ffi.C.VT_CLSID then
            return tostring(ffi.cast("CLSID *", self.puuid))
        elseif self.vt == ffi.C.VT_LPWSTR then
            return core_string.toAnsi(self.pwszVal)
        elseif self.vt == ffi.C.VT_UI4 then
            return tonumber(self.uintVal)
        end

        return tostring(self.pcVal)
    end,
}
ffi.metatype(PROPVARIANT, PROPVARIANT_mt)

There are various levels of “COM Support” within the APIs of the Windows system. Some are fairly basic, providing nothing more than a fairly thin veneer over an otherwise standard C interface. The Kinect interface is like this, as is the DXGI interface. There may not be any usage of things like VARIANT, and there is not much ‘inheritance’ of interfaces other than from ‘IUnknown’. Then, there are other interfaces that pull you further down into the COM rabbit hole. MMDevice is one such interface. You need VARIANT, and IDispatch (at least in a cursory way), IStorage, IPropertyStorage, and quite a few GUIDs along the way. Everything is done with GUIDs, and you have to worry about using “Release()” on your interfaces, CoMemoryFree() and a whole bunch of other stuff which, if not done properly, will lead to leaks, bugs, and worse.

And this is why the various frameworks exist. This knowledge is too obscure and esoteric for most developers to have to concern themselves with it. Better someone who really knows and understands the intricacies to deal with it, and provide a higher level abstraction that smooths over some of the rough spots.

Why not just make the lower level stuff more approachable in the first place? Well, yah, it’s that legacy thing isn’t it? In some cases you can make a complete break and just code something up from scratch. The Kinect API does this. I can get frames out of my Kinect without having to worry about any multimedia frameworks, and without pulling in half the COM world.

It took me a good couple of days of pulling on the COM thread to bring in just enough support to make these interfaces work. Now that the basics of COM are in the system though, it’s much easier to pull in more interfaces. Mostly it’s a tedious job of looking up all the interfaces, putting them into a ffi header file, coding up the stubs to make the viable calls, making sure the __gc method is implemented to call “Release()”, etc. At the end of it, you gain access to what is likely a fairly useful interface without all the fuss of dealing with the low level COM stuff.

I implemented the MMDevice interface, not just to gain access to the audio endpoints, but really as a practice run for implementing the DXVA interfaces. In Windows 8, the DXVA interfaces contain the desktop duplication API, which replaces the old mirror driver API for screen copying. Using this low level API, I will redo the plumbing on my screen capture application, and dramatically improve the performance browser based screen sharing. The basic screen capture portion should remain fairly small, at a couple hundred lines of code, but the capabilities will be dramatically improved, while reducing the bandwidth requirements, which will mean even faster frame rates. It’s all goodness.

And so it goes. Windows has a rich history of APIs, and with that history comes a lot of baggage that most developers probably don’t want to deal with. There are new, more modern APIs introduced all the time. LuaJIT forms a pretty easy bridge to some of the less trod parts of the system, and gives rapid scriptable access to the new parts. Once that bridge has been formed, you can do some pretty nice things within the Lua environment on Windows.

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s