You are in a browser tab, a video call or a text editor. The music is playing in some other window you have not looked at for an hour. You press the Play/Pause key and the music stops. Nobody clicked anything in the music app, yet it got the message.
That small moment involves a USB standard, a key code table per operating system, a system service that decides which app "owns" playback right now, and a little protocol that every music player speaks so the lock screen can show a title, a cover and a moving progress bar.
We had to wire all of this up for Spotube on three desktop systems, so here is what we learned, from the key switch to the widget.
The key press: a usage code, not a letter
Keyboards talk to computers using the USB HID class. Every control on a HID device reports a usage: a pair of numbers made of a usage page (a category) and a usage ID (the control inside it). The list lives in the USB-IF's HID Usage Tables.
Letters are on the Keyboard/Keypad page, 0x07. Media keys are not. They live on the Consumer page, 0x0C, next to TV remotes and volume knobs. From version 1.6 of the tables:
| Usage ID | Name | Type |
|---|---|---|
0xB5 |
Scan Next Track | OSC |
0xB6 |
Scan Previous Track | OSC |
0xB7 |
Stop | OSC |
0xCD |
Play/Pause | OSC |
OSC means One Shot Control: a push button that triggers a single event. The spec defines Play/Pause by its effect on "linear media": if it is streaming, momentarily stop it; if it is paused, resume. Notice what is missing: the key has no idea which app is playing. It just says "toggle".
Each OS then translates the usage into its own vocabulary:
-
Linux: the kernel's input layer turns it into an input event code. In
input-event-codes.h,KEY_PLAYPAUSEis 164,KEY_NEXTSONGis 163 andKEY_PREVIOUSSONGis 165. -
Windows: it becomes the virtual key
VK_MEDIA_PLAY_PAUSE, value0xB3. A focused window may also receive it asWM_APPCOMMANDwithAPPCOMMAND_MEDIA_PLAY_PAUSE, which is 14. - macOS: the system handles the key itself and delivers it to apps as a remote command, which we will get to shortly.
One HID usage, three different names, and still no idea which app should hear it
The real question: who is "the player" right now?
A key code is not yet a command for an app. You might have a music app, two browser tabs with videos and a podcast app all open. Somebody has to decide which one hears the toggle. All three systems have the same idea, a current media session, but they expose it differently.
On Windows, Microsoft's GlobalSystemMediaTransportControlsSessionManager exposes this directly: GetCurrentSession() returns "the session the system believes the user would most likely want to control". Note the word "believes". It is a heuristic, not a rule you can look up.
On Apple platforms, one app at a time is the Now Playing app. Apple's sample project Becoming a Now Playable App is all about making your app "eligible to become the Now Playing app" by publishing Now Playing info and registering for remote commands.
Linux is the most decentralized. Every player publishes itself on D-Bus (more below), and anything can talk to any of them. The command line tool playerctl shows the choice plainly: without being told which player to use, it acts on the first player it can find, and if its companion daemon playerctld is running, it acts on players "in order of their last activity". Your desktop environment's media key handling, or a key binding you set up to run playerctl play-pause, makes the same kind of choice.
Every OS has an operator deciding which app gets the key
The practical lesson for app developers: you don't listen for the key. You register with the operator and let it route the command to you. That is also why media keys work while your window is in the background.
Windows: System Media Transport Controls
On Windows the operator is the System Media Transport Controls, or SMTC. Microsoft's older guide describes them as "the controls that pop up when hardware media keys are pressed, such as the volume control on a pair of headphones or the media buttons on keyboards", and says that if the user presses the pause key and your app supports SMTC, your app is notified.
The current guide has three parts:
-
Commands in: set
IsPlayEnabledandIsPauseEnabled, then handle theButtonPressedevent, which tells you which button was pressed. It is not raised on the UI thread, so you marshal back before touching the UI. -
State out: set
PlaybackStatustoPlaying,PausedorStoppedwhenever your player changes state. -
Metadata and timeline out: fill
DisplayUpdater.MusicProperties(title, artist), set aThumbnailfor the cover and callUpdate(). For the progress bar, build aSystemMediaTransportControlsTimelinePropertieswithStartTime,EndTimeandPosition(all three are required for a timeline to show) and pass it toUpdateTimelineProperties.
Apps that play through the WinRT MediaPlayer class get all of this automatically. Apps with their own audio engine do it by hand.
macOS: two objects, two directions
Apple splits the job cleanly between two classes in the MediaPlayer framework, both available on macOS since 10.12.2.
MPNowPlayingInfoCenter is the outgoing half. You hand it a dictionary describing the current item: title, artist, album, duration, elapsed time, playback rate and artwork. Apple is explicit that you don't control how it's drawn: "You set the values in the dictionary and the system or the connected accessory handles displaying the information."
MPRemoteCommandCenter is the incoming half. It "responds to remote control events sent by external accessories and system controls". You never create one; you grab the shared instance and attach handlers to its commands (playCommand, pauseCommand, nextTrackCommand, changePlaybackPositionCommand and so on). Each handler returns a status, such as success or command failed.
Media keys, the system's own Now Playing controls and external accessories all end up as the same command objects. Your app doesn't need to know which one the user touched.
Linux: MPRIS over D-Bus
Linux has no single vendor, so the solution is a shared spec: MPRIS, the Media Player Remote Interfacing Specification (version 2.2 at the time of writing). It runs on D-Bus, the message bus most Linux desktops use for talking between processes.
The contract is short:
- The player requests a bus name starting with
org.mpris.MediaPlayer2, for exampleorg.mpris.MediaPlayer2.vlc. That prefix is how clients list all players: they just ask the bus for every name that starts with it. - It exposes the object path
/org/mpris/MediaPlayer2, which must implement two interfaces:org.mpris.MediaPlayer2(identity, raise, quit) andorg.mpris.MediaPlayer2.Player(playback). - The Player interface has methods like
Play,Pause,PlayPause,Next,Previous,SeekandSetPosition, and properties likePlaybackStatus("Playing", "Paused" or "Stopped"),Metadata,Rate,VolumeandPosition.
Because it's plain D-Bus, you can poke any player by hand:
# Toggle VLC, exactly what a media key handler does
dbus-send --print-reply --dest=org.mpris.MediaPlayer2.vlc \
/org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause
# Or let playerctl find the player for you
playerctl play-pause
playerctl metadata --format "{{ artist }} - {{ title }}"
The Metadata property is a dictionary using keys from the MPRIS metadata spec: xesam:title, xesam:album, mpris:artUrl for the cover and mpris:length for the duration. Two details catch people. xesam:artist is a list of strings, not a string, so a duet is two entries. And lengths are 64-bit integers in microseconds, so a 3 minute 30 second track has mpris:length = 210000000. Send seconds by mistake and your widget will happily claim the song is 0:00 long.
Position: tell the system once, let it do the math
Here is the part we find most elegant. A Now Playing widget shows a progress bar that moves smoothly every second. The naive way to drive it would be for the app to send the position every second, or several times a second. None of the three systems want that.
Apple's docs for MPNowPlayingInfoPropertyElapsedPlaybackTime say: "Elapsed time is automatically calculated, by the system, from the previously provided elapsed time and the playback rate. It isn't necessary to update this property frequently." The playback rate is 1.0 for normal speed. Report a rate of 0.0 (which is what our iOS code does on pause) and the extrapolation keeps the position still.
MPRIS goes further. The Position property does not emit the usual PropertiesChanged signal when it changes. Instead there's a Seeked signal, sent only when the position jumps in a way the current playing state would not predict, like a seek. When no Seeked arrives, clients should assume that "when playing, the position progresses according to the rate property. When paused, it remains constant."
So everyone does the same calculation:
shown_position = last_position + rate × (now - time_of_last_update)
A worked example. At 21:00:00 the app reports elapsed 42.0 s, rate 1.0. Ten seconds later the user opens the lock screen. Nothing new was sent, but the widget computes 42.0 + 1.0 × 10 = 52.0 s. At 21:00:13 the user pauses: one update, elapsed 55.0 s, rate 0.0, and the bar freezes, because 55.0 + 0.0 × anything is still 55.0. Then they drag to 2:00: one more update (or a Seeked(120000000) on Linux). Three messages for 13 seconds, instead of 13 or more. It's the same "send on change, not on a timer" idea we wrote about in why our app refuses to poll.
Send position and rate on change, and the widget does the arithmetic
Windows is the odd one out here: the timeline properties carry a position, and the SMTC has a separate PlaybackRate property, but Microsoft's guide doesn't spell out how the flyout fills in the gaps between updates, so we won't guess.
How Spotube wires it up
On the desktop, Spotube's player is libVLC (the full story is in playing audio everywhere with VLC), which knows nothing about media keys. The bridge is one class, SystemMediaControlService.kt. Its doc comment sums it up: it "publishes now-playing metadata and playback state to the OS media center (MPRIS on Linux, Now Playing on macOS, SMTC on Windows) and forwards media key commands back" into the player. It is created at startup in Modules.jvm.kt.
We don't talk to SMTC, MediaPlayer.framework or D-Bus ourselves. The class sits on the nucleus.media-control library from the Nucleus project, which ships a small native library per OS and gives us one event type. Incoming commands become calls on our player:
// SystemMediaControlService.kt (trimmed)
MediaControlEvent.Play -> scope.launch { audioPlayer.play() }
MediaControlEvent.Next -> scope.launch { audioPlayer.skipToNext() }
is MediaControlEvent.SetPosition -> scope.launch {
audioPlayer.seekTo(event.positionMs.milliseconds)
}
Toggle (what a Play/Pause press arrives as) checks whether we're playing and calls pause() or play(). The events arrive on the Swing UI thread, so we hop onto a coroutine scope before calling the player, the same "don't do it on the event thread" advice Microsoft gives for ButtonPressed.
Outgoing, the service collects three Kotlin flows: the current item becomes metadata (title, artist, album, cover URL, duration), the player state and position become a playback state, and volume goes out on its own. If the library reports no backend for the current system, we log it and skip the whole integration rather than crash.
An honest note: we forward every position tick the player reports, not just the changes. By the rules above, that's more than the OS needs. It works, but it's a spot where we could take our own advice.
On Linux, the Flatpak manifest grants --own-name=org.mpris.MediaPlayer2.org.spotube.spotube, so the MPRIS name is org.mpris.MediaPlayer2 plus our app ID. Flatpak's default D-Bus policy already allows an app to own org.mpris.MediaPlayer2.$FLATPAK_ID, so the line mostly documents intent. Without an explicit grant, a sandboxed app could not claim any other MPRIS name.
On iOS, IosMediaSession.kt uses MPNowPlayingInfoCenter and MPRemoteCommandCenter directly from Kotlin. It sets the rate to 1.0 when playing and 0.0 when paused, exactly as the extrapolation rule expects. On Android, PlaybackService.kt builds a Media3 MediaLibrarySession around the player, which plays the same role there.
Try it yourself
On Linux, run playerctl metadata --follow and play a song in any MPRIS player. You'll see a new line when the track changes, not one per second, because nothing on the bus changed in between. Then press your Play/Pause key with two players open and see which one the operator picks. If it picks the wrong one, now you know who to blame.
References
- HID Usage Tables 1.6 (PDF): Consumer page 0x0C and the Play/Pause, Scan Next/Previous Track and Stop usages.
- HID Usage Tables document page: the USB-IF listing for the current tables.
- USB human interface device class: background on HID devices and reports.
- Linux input-event-codes.h: KEY_PLAYPAUSE and friends.
- Virtual-Key Codes: VK_MEDIA_PLAY_PAUSE = 0xB3.
- WM_APPCOMMAND: APPCOMMAND_MEDIA_PLAY_PAUSE = 14.
- How to use the system media transport controls (Windows 8.1 guide): SMTC as the target of hardware media keys.
- Manual control of the System Media Transport Controls: ButtonPressed, DisplayUpdater and timeline properties.
- SystemMediaTransportControls.UpdateTimelineProperties: the timeline API.
- GlobalSystemMediaTransportControlsSessionManager: GetCurrentSession and the "most likely" session.
- MPNowPlayingInfoCenter: Apple's outgoing Now Playing info.
- MPRemoteCommandCenter: Apple's incoming remote commands.
- MPNowPlayingInfoPropertyElapsedPlaybackTime: the system extrapolates elapsed time from rate.
- MPNowPlayingInfoPropertyPlaybackRate: what rate values mean.
- MPMediaItemPropertyArtwork: artwork key for Now Playing.
- Becoming a Now Playable App: Apple's sample on being the Now Playing app.
- MPRIS D-Bus Interface Specification: bus name policy and entry point.
- MPRIS Player interface: methods, properties, Position and Seeked.
- MPRIS metadata: xesam and mpris keys, microsecond lengths.
- D-Bus: the message bus MPRIS runs on.
- playerctl: command line MPRIS client and the playerctld daemon.
- Flatpak sandbox permissions: default D-Bus filtering and the MPRIS name.
- Nucleus: the framework whose media-control module Spotube uses on desktop.
Originally published on spotube.org.



Top comments (0)