How does macOS route keyboard events?
I'm not sure how OS X decides which app to send the command. It might have to do with launch order, or last visited order. What I know is that it's decided by rcd: Remote Control Daemon.

When a media key is pressed, Launch Daemon matches the LaunchEvents to com.apple.rcdevent.matching and calls up rcd. Then it just sort of hangs out in the background. You can see it in Activity Monitor. You can kill it and it wouldn't respawn. It just comes back when you press a media key again. The app itself is stored here:

/System/Library/CoreServices/rcd.app


It's launch daemon is here:

/System/Library/LaunchAgents/com.apple.rcd.plist