avtransport
A DLNA-compatible media renderer for Android. Home Assistant, VLC, BubbleUPnP and other control points find the device and tell it what to play.
A UPnP AV MediaRenderer in plain Kotlin, the kind of device DLNA control points cast to. Home
Assistant's DLNA integration, VLC, BubbleUPnP and similar apps find the device on the network, hand it
the URL of a song, a video or a picture, and then play, pause, seek and change the volume. The library
does the protocol: discovery, the device and service descriptions, the control actions and the events
that keep every control point up to date. Playing the media is yours: hand the URL to Media3,
MediaPlayer or an image view.
It has no Pane API, no app classes and no Android dependencies beyond the manifest's INTERNET. The
Glassworks video pane wraps it with settings and entities. Package dev.glassworks.avtransport, MIT
licensed, minSdk 23.
Anyone on your network can cast. UPnP has no pairing and no passwords: whoever can reach the device can play something on it. Decide in
onSetUriwhat you're willing to play, and offer a way to turn the renderer off.
Event subscriptions are kept on a short leash too. A control point gets its events at its own address
only, given as an IP address rather than a name, so nobody on the network can point the device at its
own local services. If a control point sits behind NAT or in a container that names the host's address
for its events, pass allowCallbacksToOtherHosts = true. Events can then go to another address on the
network, but still never to a loopback, link-local, wildcard or multicast one.
Use it in your own app
lateinit var renderer: AvTransportRenderer
renderer = AvTransportRenderer(
name = "Kitchen panel", // what control points show
uuid = AvTransportRenderer.deviceUuid(installId), // the same on every start
listener = object : AvTransportRenderer.Listener {
override fun onSetUri(uri: String, metadata: MediaMetadata?) {
if (!isOnMyNetwork(uri)) return renderer.error()
player.open(uri, metadata?.title)
}
override fun onPlay() = player.play()
override fun onPause() = player.pause()
override fun onStop() = player.stop()
override fun onSeek(positionMs: Long) = player.seekTo(positionMs)
override fun onVolume(volume: Int) { player.setVolume(volume); renderer.volumeChanged(volume, player.muted) }
override fun onMute(muted: Boolean) { player.setMuted(muted); renderer.volumeChanged(player.volume, muted) }
},
)
val multicastLock = wifiManager.createMulticastLock("renderer").apply { acquire() }
renderer.start(wifiAddress, wifiInterface)
renderer.volumeChanged(player.volume, player.muted)
Android drops multicast packets unless an app holds a MulticastLock, so hold one while the renderer
runs, or control points never find it. Give start the device's address on the network control
points are on (it goes into the description URL that discovery hands out) and the interface it belongs
to. Keep the UUID the same from one start to the next, or control points see a new device each time;
deviceUuid makes one from an ID your app keeps. Don't build it from a serial number or a MAC address,
since everyone on the network can see it.
Then tell the renderer how playback goes:
player.onStateChanged = { state, positionMs, durationMs -> renderer.transportChanged(state, positionMs, durationMs) }
player.onEnded = { renderer.mediaEnded() }
Call transportChanged when the state changes (it's TRANSITIONING while loading, then PLAYING),
after a seek, and once you know the duration. Between calls, the position control points read moves on
by itself while it plays, so there's no need to report it every second. Call volumeChanged after
onVolume and onMute, and whenever the volume changes on the device. If you can't play what came in,
call error(). When the media ends, mediaEnded() moves on to the URI a control point queued with
SetNextAVTransportURI, if there is one. Call renderer.stop() when you're done: it says goodbye on the
network, so control points drop the device right away.
What's in it
AvTransportRenderer |
The renderer: SSDP discovery, the HTTP server for the descriptions, SOAP control and GENA events, and the calls that tell control points where playback is (transportChanged, volumeChanged, error, mediaEnded). |
AvTransportRenderer.Listener |
What control points ask for. Calls come in order on their own thread, with no locks held, so a listener may call the renderer back. |
MediaMetadata |
What a control point said about the media: title, artist, album, album art, UPnP class, MIME type and duration, read from its DIDL-Lite. |
TransportState |
Where playback is: no media, stopped, transitioning, playing or paused. |
The library doesn't log. It keeps up to 32 event subscriptions (one more replaces the oldest) and drops a
subscriber after three deliveries in a row fail. Each subscriber gets its events in order, one at a
time. While one is on its way, newer changes merge into the next, so a slow subscriber falls behind by
one event at most and never holds up the others. The server answers a few requests at a time, gives
each client 15 seconds to send its whole request, and closes a connection beyond that at once instead
of letting it pile up. stop() closes every connection, including those still waiting.
How it works
A MediaRenderer is a UPnP device with three services. In the order a control point uses them:
- Discovery (SSDP). The renderer joins the multicast group
239.255.255.250:1900, answersM-SEARCHforssdp:all,upnp:rootdevice, its UUID, its device type and each service type, and announces itself withNOTIFY ssdp:aliveon start and every 10 minutes (each announcement lasts 30). On stop it sendsssdp:byebye. - Description. Each answer points at
/description.xml, the device description: the friendly name, the UUID and the three services. Each service has its own description (SCPD) listing its actions and state variables. - Control (SOAP).
AVTransportloads a URI (SetAVTransportURI, with DIDL-Lite metadata) and plays, pauses, stops and seeks it; it also reports the transport state, position and media.RenderingControlsets and reads the volume and mute.ConnectionManagerlists what the renderer can play. A request it can't carry out gets the UPnP error for it, such as701(that transition isn't available now),714(a MIME type it doesn't play) or716(a URI that isn'thttporhttps). - Events (GENA). A control point subscribes to a service and gets every state variable at once,
then each change as it happens.
AVTransportandRenderingControlsend theirs in one variable,LastChange, an XML document of what changed. Changes within 200 ms go out together. The position isn't evented: control points ask for it withGetPositionInfo.
Every request is size-limited and has a deadline, and XML that declares a DTD or an entity is refused before it's parsed.
Gradle
Not on Maven Central yet. In this repository: implementation(project(":avtransport")). An Android
library (AAR), minSdk 23 (Android 6), with no dependencies beyond the Kotlin standard library.
Tests
./gradlew :avtransport:testDebugUnitTest.
-
SsdpTest,ControlTest,EventingTest,MalformedInputTestandLifecycleTestrun the renderer over loopback. They cover search answers and announcements, every action and its errors, subscriptions, their events and where those may go, and slow subscribers. They also send broken, oversized and hostile requests (DTDs, entity expansion, slow and trickling clients), and check that starting and stopping are clean. -
XmlAndDidlTestreads DIDL-Lite as control points really send it, and UPnP's time strings. -
ControlPointInteropTestdrives the renderer withasync_upnp_client, the library Home Assistant's DLNA integration uses: discovery, the descriptions, play, pause, seek, volume and mute, with the control point's own event server checking every event. It skips unlessAVTRANSPORT_PYTHONpoints at a Python with it installed; CI installs it from the hashedtest-requirements.txt:python3.12 -m venv /tmp/avtransport-venv /tmp/avtransport-venv/bin/pip install --require-hashes --only-binary :all: -r libs/avtransport/test-requirements.txt AVTRANSPORT_PYTHON=/tmp/avtransport-venv/bin/python \ ./gradlew :avtransport:testDebugUnitTest --tests '*ControlPointInteropTest*'
DLNA and UPnP
This library is an independent implementation of the UPnP AV specifications. It is not affiliated with, endorsed by or certified by the Digital Living Network Alliance or the Open Connectivity Foundation. DLNA is a trademark of the Digital Living Network Alliance, and UPnP is a trademark of the Open Connectivity Foundation.