How does Discord hook into a specific process's audio? - winapi

Going through Google search results, there is no widely known way to capture audio from a specific application on Microsoft Windows, at least without having to resort to workarounds such as sending audio from one process to a separate virtual audio loopback device (which however results in an inability to hear the sound, unless you either use a hardware loopback playback device or "listen" to the emulated input via the main output).
These workarounds are clunky, require configuration for each specific application and software will often misbehave, no longer successfully make any sound or straight-up stop working if their output device is changed during execution. Meanwhile, launching a Discord "Live Streaming" session allows you to easily, without failure, share a single application's sound with a VoIP group call. Sound from other application is completely removed. Looking at audio devices, it appears that no virtual loopback routing is taking place, and there is absolutely zero interruption in audio playback on the client side. The functionality isn't available on the macOS or Linux versions of the software, only on Windows. Capturing sound from a specific process is thus possible in Win32, but why isn't anyone else doing this? What would it take, say, to implement something like this in a fork of software where such functionality would be extremely useful, like OBS or Audacity?

EDIT: Not sure if this is useful at all, but I found this page: https://obsproject.com/forum/threads/audio-sources.465/
In particular, this strikes me as useful information:
It's quite similar to hooking Direct3D. You hook the IAudioRenderClient interface, and intercept GetBuffer to read the audio samples.
Beginner's reverse engineering time!
Also, I cannot give a definitive answer, but I can lead you in the right direction.
Discord has a directory called \modules\discord_hook inside of it's root directory, here we can find there is a JavaScript file, named index.js, a json file named manifest.json, a .node file, named discord_hook.node (which is compiled/encrypted and I cannot read), a directory with .dlls and .exes, and it also generates a log file, named hook.log.
index.js appears to just load discord_hook.node and do some other things that aren't important to us.
Googling manifest.json brings me here: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json
The manifest.json file is the only file that every extension using WebExtension APIs must contain.
In the .json file, we find it is referencing the .exes, .dlls, discord_hook.node, index.js, and itself.
The .node file as previously mentioned is for the most part unreadable by a human being.
hook.log doesn't output anything seemingly helpful, just stuff about the graphics/video share.
This leaves us with looking inside the exe and dll files inside the subdirectory here, I have no knowledge of asm, but we can look at some strings left inside of these binaries.
I found a section of strings referencing audio at offset 1266B4 to offset 126EA6 in DiscordHook.dll (This may and almost definitely WILL change in future versions of discord)
Here are some of the strings that seem to be worth posting here.
Audio buffer stopped, WASAPI capture stopping
Failed to get format of WASAPI audio buffer, not capturing, error code [%d]
Failed to get WASAPI audio client from render client, not capturing
Starting capture of WASAPI buffer with sample rate %d, depth %d, %d channels
Starting capture of Windows Sonic stream with downmix sample rate %d, depth %d, %d channels
ISpatialAudioObjectRenderStream::Stop
ISpatialAudioObjectRenderStream::BeginUpdatingAudioObjects
ISpatialAudioObjectRenderStream::EndUpdatingAudioObjects
ISpatialAudioObject::GetBuffer
HookWasapi failed to load audioses.dll
WaveFormatFromRenderClient failed with error code [%d]
LoadWASAPIOffsets failed with error code [%d]
WASAPI module sizes don't match (expected: %lu, actual: %lu)
WASAPI offsets invalid (stop: %lu, getBuffer: %lu, releaseBuffer: %lu, clientOffset: %lu, endpointOffset: %lu)
WASAPI offsets out of bounds (size: %lu, stop: %lu, getBuffer: %lu, releaseBuffer: %lu)
IAudioClient::Stop
IAudioRenderClient::GetBuffer
IAudioRenderClient::ReleaseBuffer
HookWasapi: MH_ApplyQueued failed 0x%x
Also, I googled "hook process audio" and found this:
https://ywjheart.wordpress.com/2017/02/26/audio-captureapihook-based-for-obs-studio/
It doesn't give any code examples, or downloads, but it describes some stuff on doing this very thing but in OBS. They also link the stuff they used to document it at the bottom.
Good luck, I hope all this information can help in some way!

Related

Would it be possible to blank all graphics card output periodically, even with a proprietary video card driver?

I want to write a program to make the entire screen black every N frames, while using a computer otherwise normally. I'm guessing I can do this by digging around enough in an open source video driver like nouveau, but I also want to do it in windows. Given that I cannot modify a proprietary video driver, is there an easier way to do this in a way that would not hang or make too many timing errors as a result of what the CPU is doing? Perhaps involving system interrupts or something?

Control Chromecast buffering at start

Is there a way to control the amount of buffering CC devices do before they start playback?
My sender apps sends real time audio flac and CC waits +10s before starting to play. I've built a customer receiver and tried to change the autoPauseDuration and autoResumeDuration but it does not seem to matter. I assume it's only used when an underflow event happens, but not at startup.
I realize that forcing a start with low buffering level might endup in underflow, but that's a "risk" that is much better than always waiting such a long time before playback starts. And if it happens, the autoPause/Resume hysteresis would allow a larger re-buffering to take place then.
If you are using the Media Player Library, take a look at player.getBufferDuration. The docs cover more details about how you can customize the player behavior: https://developers.google.com/cast/docs/player#frequently-asked-questions
Finally, it turned to be a problem with the way to send audio to the default receiver. I was streaming flac, and as it is a streamable format, I did not include any header (you might be able to start anywhere in the stream, it's just a matter of finding the synchro). But the flac decoder in the CC does not like that and was talking 10+ second to start. As soon as I've added a STREAMINFO header, problem went away

Outputting Sound to Multiple Audio Devices Simultaneously

OK, the first issue. I am trying to write a virtual soundboard that will output to multiple devices at once. I would prefer OpenAL for this, but if I have to switch over to MS libs (I'm writing this initially on Windows 7) I will.
Anyway, the idea is that you have a bunch of sound files loaded up and ready to play. You're on Skype, and someone fails in a major way, so you hit the play button on the Price is Right fail ditty. Both you and your friends hear this sound at the same time, and have a good laugh about it.
I've gotten OAL to the point where I can play on the default device, and selecting a device at this point seems rather trivial. However, from what I understand, each OAL device needs its context to be current in order for the buffer to populate/propagate properly. Which means, in a standard program, the sound would play on one device, and then the device would be switched and the sound buffered then played on the second device.
Is this possible at all, with any audio library? Would threads be involved, and would those be safe?
Then, the next problem is, in order for it to integrate seamlessly with end-user setups, it would need to be able to either output to the default recording device, or intercept the recording device, mix it with the sound, and output it as another playback device. Is either of these possible, and if both are, which is more feasible? I think it would be preferable to be able to output to the recording device itself, as then the program wouldn't have to be running in order to have the microphone still work for calls.
If I understood well there are two questions here, mainly.
Is it possible to play a sound on two or more audio output devices simultaneously, and how to achieve this?
Is it possible to loop back data through a audio input (recording) device so that is is played on the respective monitor i.e for example sent through the audio stream of Skype to your partner, in your respective case.
Answer to 1: This is absolutely feasable, all independent audio outputs of your system can play sounds simultaneously. For example some professional audio interfaces (for music production) have 8, 16, 64 independent outputs of which all can be played sound simultaneously. That means that each output device maintains its own buffer that it consumes independently (apart from concurrency on eventual shared memory to feed the buffer).
How?
Most audio frameworks / systems provide functions to get a "device handle" which will need you to pass a callback for feeding the buffer with samples (so does Open AL for example). This will be called independently and asynchroneously by the framework / system (ultimately the audio device driver(s)).
Since this all works asynchroneously you dont necessarily need multi-threading here. All you need to do in principle is maintaining two (or more) audio output device handles, each with a seperate buffer consuming callback, to feed the two (or more) seperate devices.
Note You can also play several sounds on one single device. Most devices / systems allow this kind of "resources sharing". Actually, that is one purpose for which sound cards are actually made for. To mix together all the sounds produced by the various programs (and hence take off that heavy burden from the CPU). When you use one (physical) device to play several sounds, the concept is the same as with multiple device. For each sound you get a logical device handle. Only that those handle refers to several "channels" of one physical device.
What should you use?
Open AL seems a little like using heavy artillery for this simple task I would say (since you dont want that much portability, and probably dont plan to implement your own codec and effects ;) )
I would recommend you to use Qt here. It is highly portable (Win/Mac/Linux) and it has a very handy class that will do the job for you: http://qt-project.org/doc/qt-5.0/qtmultimedia/qaudiooutput.html
Check the example in the documentation to see how to play a WAV file, with a couple of lines of code. To play several WAV files simultaneously you simply have to open several QAudioOutput (basically put the code from the example in a function and call it as often as you want). Note that you have to close / stop the QAudioOutput in order for the sound to stop playing.
Answer to 2: What you want to do is called a loopback. Only a very limited number of sound cards i.e audio devices provide a so called loopback input device, which would permit for recording what is currently output by the main output mix of the soundcard for example. However, even this kind of device provided, it will not permit you to loop back anything into the microphone input device. The microphone input device only takes data from the microphone D/A converter. This is deep in the H/W, you can not mix in anything on your level there.
This said, it will be very very hard (IMHO practicably impossible) to have Skype send your sound with a standard setup to your conversation partner. Only thing I can think of would be having an audio device with loopback capabilities (or simply have a physical cable connection a possible monitor line out to any recording line in), and have then Skype set up to use this looped back device as an input. However, Skype will not pick up from your microphone anymore, hence, you wont have a conversation ;)
Note: When saying "simultaneous" playback here, we are talking about synchronizing the playback of two sounds as concerned by real-time perception (in the range of 10-20ms). We are not looking at actual synchronization on a sample level, and the related clock jitter and phase shifting issues that come into play when sending sound onto two physical devices with two independent (free running) clocks. Thus, when the application demands in phase signal generation on independent devices, clock recovery mechanisms are necessary, which may be provided by the drivers or OS.
Note: Virtual audio device software such as Virtual Audio Cable will provide virtual devices to achieve loopback functionnality in Windows. Frameworks such as Jack Audio may achieve the same in UX environment.
There is a very easy way to output audio on two devices at the same time:
For Realtek devices you can use the Audio-mixer "trick" (but this will give you a delay / echo);
For everything else (and without echo) you can use Voicemeeter (which is totaly free).
I have explained BOTH solutions in this video: https://youtu.be/lpvae_2WOSQ
Best Regards

WASAPI: IAudioClient->Initialize succeeds even when IAudioClient->IsFormatSupported fails with same format

I am trying to find out which output formats are supported by a specific audio device in exclusive mode.
To do this, I am using IAudioClient->IsFormatSupported(), which according to the documentation should be usable for this.
Unfortunately, it returns AUDCLNT_E_UNSUPPORTED_FORMAT for almost every format I try to pass, except for default 2-channel, 44.1khz audio.
If I actually try to initialize the audioclient, there are however formats that succeed, but which failed in IsFormatSupported().
Just trying to Initialize every format is not an option because this could result in stopping the audio from other applications.
Has anyone else seen this behavior or know if there is another way to find which formats are supported by a specific audio device?
I have seen this behavior as well. It seems like IsFormatSupported will only accept what is marked as 'supported' in the playback device settings in Windows, but Initialize seems to actually end up asking the drivers if it's indeed possible.
In my specific situation, I have a Xoxar HDAV1.3 setup to use HDMI as output. Two playback devices are always available: Speakers and S/PDIF Pass-through Device. If I try, for example, to request 6 channels for the S/PDIF playback device, IsFormatSupported will reject it (in theory, S/PDIF only supports 2, and that's all I can see in the settings), but calling Initialize will succeed and work (it goes out HDMI after all, for which 6 channels is supported). Talk about misleading device names!
I'm afraid there's no real practical way to work around this issue.

Flex 4 > spark.components.VideoPlayer > How to switch bit rate?

The VideoPlayer (possibly VideoDisplay also) component is capable of somehow automatically picking the best quality video on the list it's given. An example is here:
http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/spark/components/mediaClasses/DynamicStreamingVideoItem.html#includeExamplesSummary
I cannot find the answers to below questions.
Assuming that the server that streams recorded videos is capable of switching across same videos with different bit rates and streaming them from any point within their timelines:
Is the bandwidth test/calculation within this component only done before the video starts playing, at which point it picks the best video source and never uses the other ones? Or, does it continuously or periodically execute its bandwidth tests and does it accordingly switch between video sources during the playback?
Does it support setting the video source through code and can its automatic switching between video sources be turned off (in case I want to provide this functionality to the user in the form of some button/dropdown or similar)? I know that the preferred video source can be set, but this only means that that video source will be tested/attempted first.
What other media servers can be used with this component, besides the one provided by Adobe, to achieve automated and manual switching between different quality of same video?
Obviously, I'd like to create a player that is smart enough to automatically switch between different quality of videos, and that will support manual instructions related to which source to play - both without interrupting the playback, or at least without restarting it (minor interruptions acceptable). Also, the playback needs to be able to start at any given point within the video, after enough data has been buffered (of course), but most importantly, I want to be able to start the playback beyond what's buffered. A note or two about fast-forwarding is not going to hurt, if anyone knows anything.
Thank you for your time.

Resources