HarmonyOSCCastingVela Player

Casting Video to TVs: Dual Channels, Readahead Relay, and Open-GOP Remuxing

Inside Vela Player 1.1.0 casting (commits 34b77dc, 7bf92fa): why screen mirroring fails for AVPlayer, dual Cast+ and DLNA delivery via CastService.ets, turning the phone into a LAN HTTP relay (/c/<token>/) with bounded 8 MiB Range reads and link refresh, live MKV-to-TS remuxing, and fixing open-GOP DTS collisions in dts_fix.c.

Vela Player added video casting in 1.1.0 (commits 34b77dc and 7bf92fa), supporting both Huawei Cast+ and a custom DLNA stack. By the time it stabilized, entry/src/main/cpp/bridge/http_bridge.c and entry/src/main/ets/services/CastService.ets had grown past 1,500 lines each — not because the protocols are exotic, but because putting a phone between cloud CDNs and picky TV decoders breaks almost every assumption local playback relies on.

Stream casting over mirroring, behind one state machine

System screen mirroring captures the UI compositor, while AVPlayer hardware decoding renders onto a separate hardware layer. Mirroring grabs a black rectangle, and the OS reports it as “DRM-protected content.”

Stream casting hands a URL directly to the TV so the TV decodes on its own hardware. The phone can lock its screen, and 4K playback is no longer capped by the phone’s viewport. CastService.ets wraps both channels behind one set of callbacks (onConnected, onDisconnected, onState, onCompleted, onError) and a switchingChannel mutex:

  • Huawei Cast+: uses AVSession and AVCastController, receiving playbackStateChange and endOfStream events and passing startPosition (in ms) upfront.
  • Custom DLNA: uses SSDP discovery and SOAP transport (DlnaCast.ets) with a 2-second poll guarded by a polling flag so slow TVs never trigger a request avalanche. Because DLNA’s SetAVTransportURI takes no start offset — and Seek during TRANSITIONING fails with UPnP 701 — dlnaSeekMs waits until the poll observes PLAYING.

The phone as a local HTTP relay: headers and CDN throttling

The hard constraint of stream casting is that neither AVMediaDescription.mediaUri nor DLNA CurrentURI accepts HTTP headers.

That immediately locks out three source classes: local/offline files, native protocol streams (SMB/NFS/FTP/SFTP/ISO slices bound to 127.0.0.1), and authenticated HTTP sources (WebDAV and Quark/UC/Tianyi/China Mobile cloud drives requiring Cookie/Referer/Authorization headers).

http_bridge.c solves this with /c/<token>/<name> relay slots:

  • Per-slot LAN access control: when Features.CAST is enabled, mq_bridge_start() binds 0.0.0.0 (paired with switching back to INADDR_LOOPBACK if Features.CAST is disabled). conn_run() checks peer != htonl(INADDR_LOOPBACK) && !slot->lan: local playback /t/ and /x/ slots return 404 (never 403, avoiding token-existence leaks) to any non-loopback peer on the same Wi-Fi.
  • Bounded 8 MiB Range reads + readahead: initially, sharing a single MqTcRaw handle across TV connections or letting avformat_open_input open an unbounded Range: bytes=N- stream failed on cloud CDNs. On a real device against Quark’s dl-pc CDN, unbounded connections were throttled to roughly 100 KB/s (0.84 Mbps, forcing a 35-second wait for 3 MiB), whereas bounded 2 MiB requests hit 20+ Mbps.

transcoder.c’s raw_http_open() now fetches every HTTP source in bounded RAW_HTTP_CHUNK (8 MiB) slices. mq_bridge_register_cast() pairs the relay with readahead.c, capped by RELAY_MAX_BYTES (192 MiB) and BufferPolicy.memoryBudgetBytes (1/16 total RAM, 1/4 available RAM, 128 MiB in background). mq_ra_probe_kind() treats short TV requests (<= MQ_CAST_PROBE) under lan=1 as direct probes so pre-seek tail probing never drags the sequential readahead window off the main playback position.

When cloud-drive links expire (Quark’s __puus cookie or short-lived AList signatures), mq_bridge_cast_refresh() swaps the URL and headers inside RaCtx and wakes the readahead thread via mq_ra_kick(). CastService refreshes proactively every 20 minutes (LINK_TTL_MS) and reactively on upstream read failures (rate-limited by REFRESH_GAP_MS = 15s), without dropping buffered memory or killing healthy in-flight sockets.

When TVs refuse MKV/HEVC: live TS remuxing and 90-day memory

Testing against a Xiaomi TV revealed the next wall: the exact same HEVC bitstream fails with DLNA error 714 or spins forever inside .mkv, yet plays smoothly when remuxed into MPEG-TS.

CastService runs a startup watchdog after sending media: 5 poll rounds (10s) for direct LAN sources, or 8 rounds (16s) for relayed cloud sources. If the TV never reaches PLAYING and the source is MKV, CastService falls back to /x/<token>/<name>.ts via mq_bridge_register_cast_transcode(), wrapping transcoder.c’s streaming output inside ra_for_tc() so readahead.c caches the remuxed TS bytes against small TV seek retries.

Video is copied (using a custom hevc_to_annexb() that prepends hvcC parameter sets at the start of access units when IRAP frames lack inline VPS/SPS/PPS, avoiding an FFmpeg 6.1 hevc_mp4toannexb bug that corrupts 4K HEVC playback), while audio is copied or re-encoded to stereo AAC. Once the TV actually reaches PLAYING, CastMemory persists the device’s UDN in preferences for 90 days (TTL_MS) so future MKVs skip the 10-second wait. Users can also switch audio tracks during remuxed casting by setting audioOrdinal to emit a single chosen audio stream.

Open-GOP seek freezes and dts_fix.c

Once compatibility remuxing worked, seeking or resuming on open-GOP x265 MKVs froze the TV completely while the TV re-requested offsets in a loop.

Inspecting the emitted TS stream showed why: FFmpeg’s mpegts muxer does not set AVFMT_TS_NONSTRICT and rejects non-monotonic or duplicate DTS with EINVAL. After seeking an open-GOP stream (CRA keyframes followed by RASL leading frames), matroskadec leaves DTS unset on the first two packets; the muxer’s pts_buffer estimate collides with the third packet’s explicit DTS. Worse, worker_main previously treated av_interleaved_write_frame failures as clean EOF, causing http_bridge.c to pad the remaining gigabytes of Content-Length with 0x1FFF TS null packets — freezing the screen permanently.

I extracted entry/src/main/cpp/transcode/dts_fix.c. mq_dts_fix() computes missing DTS using the muxer’s own pts_buffer logic and bumps any colliding DTS to lastDts + 1 (clamping pts >= dts). At the same time, worker_main now distinguishes pb->error < 0 I/O failures from genuine EOF, dropping the TCP connection on upstream errors rather than padding null packets so the TV reconnects cleanly.

Subtitles alongside the stream, and a 64-slot leak

Finally, CastService.setSubtitle() serializes the active subtitle track into plain SRT, exposes it through ensureSubtitleRelay() on a 1 MiB /c/ relay, writes it into DLNA DIDL metadata, and sets the CaptionInfo.sec response header on the video stream via mq_bridge_set_caption().

One bug caught right before wrapping up: http_bridge.c has MQ_MAX_STREAMS = 64 fixed slots, and token_from_url() originally parsed only /t/ and /x/, ignoring /c/. Every cast session silently leaked its slot on mq_bridge_unregister(), locking out all local and cast streams after 64 casts. Adding /c/ to token_from_url() closed that leak.

✦

Comments

  • Loading…

Comments are reviewed before publishing; email is visible only to me.