DEV Community

Cover image for How media keys and Now Playing widgets work on Windows, macOS and Linux
Team Spotube
Team Spotube

Posted on Originally published at spotube.org

How media keys and Now Playing widgets work on Windows, macOS and Linux

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_PLAYPAUSE is 164, KEY_NEXTSONG is 163 and KEY_PREVIOUSSONG is 165.
  • Windows: it becomes the virtual key VK_MEDIA_PLAY_PAUSE, value 0xB3. A focused window may also receive it as WM_APPCOMMAND with APPCOMMAND_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.

A walnut and brass switchboard. On the left, an ivory keyboard key labelled "Play/Pause" is pressed and an ivory ticket pops out beside it reading "HID usage: Consumer page 0x0C, usage 0xCD". An amber spark runs along a patch cord to a brass junction, where a hanging tag reads "Which app? the key has no idea". The spark splits into three cords, one per column, and each column's amber lamp lights: Windows shows "VK_MEDIA_PLAY_PAUSE = 0xB3", macOS shows "remote command: MPRemoteCommandCenter" and Linux shows "KEY_PLAYPAUSE = 164".

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.

The switchboard with three columns titled "Windows", "macOS" and "Linux". Each column has an ivory strip naming its operator, "GetCurrentSession()", "Now Playing app" and "playerctld: most recent activity", and three app jacks with lamps. Pressing the "Play/Pause" key on the shelf sends a spark along three cords, then an operator's hand lifts one plug per column into a jack and its lamp lights: "music app" on Windows and on macOS. On Linux the jacks are "org.mpris.MediaPlayer2.vlc" (active 2 min ago), "org.mpris.MediaPlayer2.audacious" (active 1 h ago) and "org.mpris.MediaPlayer2.org.spotube.spotube" (active now); an amber bracket compares them row by row and the plug goes into the one active now.

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:

  1. Commands in: set IsPlayEnabled and IsPauseEnabled, then handle the ButtonPressed event, which tells you which button was pressed. It is not raised on the UI thread, so you marshal back before touching the UI.
  2. State out: set PlaybackStatus to Playing, Paused or Stopped whenever your player changes state.
  3. Metadata and timeline out: fill DisplayUpdater.MusicProperties (title, artist), set a Thumbnail for the cover and call Update(). For the progress bar, build a SystemMediaTransportControlsTimelineProperties with StartTime, EndTime and Position (all three are required for a timeline to show) and pass it to UpdateTimelineProperties.

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 example org.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) and org.mpris.MediaPlayer2.Player (playback).
  • The Player interface has methods like Play, Pause, PlayPause, Next, Previous, Seek and SetPosition, and properties like PlaybackStatus ("Playing", "Paused" or "Stopped"), Metadata, Rate, Volume and Position.

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 }}"
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.

A horizontal brass timeline running from 0 s to 130 s with a sliding amber needle. At "21:00:00" a lamp flashes and a ticket reads "elapsed 42.0 s, rate 1.0"; the needle then moves by itself while a slate shows the widget's own sum, and at 21:00:10 a tag records "52.0 s at 21:00:10". At "21:00:13" a second lamp flashes with "elapsed 55.0 s, rate 0.0" and the needle stops dead at 55.0. A third lamp flashes with "Seeked: 120.0 s" and the needle jumps to 120.0. A tally along the bottom reads "messages sent: 3", next to a row of 13 small lamps for what "polling once a second would send".

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)
}
Enter fullscreen mode Exit fullscreen mode

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


Originally published on spotube.org.

Top comments (0)