Expand description
§tvpipe
Stream a program’s own frames and sound — or a file, a web page, a
screen — to an Apple TV, a Chromecast or Google TV, or a browser tab,
with low latency, from Rust. In process: no tvpipe binary, no async
runtime, no ffmpeg needed for raw frames.
use std::time::Duration;
use tvpipe::{Options, PixelFormat};
fn main() -> tvpipe::Result<()> {
let mut s = tvpipe::stream(
Options::new()
.to("Living Room") // a name from tvpipe::discover(), or "browser"
.video(1280, 720, 60, PixelFormat::Rgba)
.audio(48_000, 2),
)?;
let frame = vec![0u8; 1280 * 720 * 4];
let pcm = vec![0i16; 48_000 / 60 * 2];
for _ in 0..600 {
let pts = s.elapsed();
let _ = s.write_video(&frame, pts)?; // never blocks; may drop
s.write_audio(&pcm, pts)?;
std::thread::sleep(Duration::from_millis(16));
}
s.finish()?; // or drop it: the TVs get their TEARDOWN/STOP
Ok(())
}Raw frames go to a built-in H.264 encoder (keyframes on demand, so a TV
that joins or loses a packet recovers at once); a program with a
hardware encoder sends its own H.264 instead (Options::h264,
Stream::write_h264). Several receivers play on one timeline.
discoverfinds receivers;Discoverykeeps looking for a program’s receiver menu.pair/Pairing: Apple TVs pair once with a PIN; or giveOptions::on_pinand a stream pairs when it has to.play(files, URLs, capture through ffmpeg),test_pattern,preview(a browser tab) andshare(a tab, window or screen, through a page in the user’s browser) return aSession.- Events (
Event): poll them, get a callback, or read the snapshots (receivers(),stats(),player_url()). - Pairings live in a
Storage: by default the program’s own directory;Storage::cli()shares thetvpipecommand’s. - Logging is off until the program installs a handler
(
log::set_logger); the library never writes to stdout or stderr.
The recipes cover wgpu readbacks, Bevy, macroquad, cpal audio and
hardware encoders. The tvpipe command-line tool (the tvpipe-cli
crate, and release binaries) is built on this crate:
https://mitsuhiko.github.io/tvpipe/.
§Debug builds
The built-in encoder is too slow without optimizations. Add to the
program’s Cargo.toml:
[profile.dev.package.tvpipe]
opt-level = 3
[profile.dev.package.ring]
opt-level = 3§Features
| Feature | Default | Brings |
|---|---|---|
airplay | yes | AirPlay mirroring: pairing, video, ALAC audio (ring) |
cast | yes | Google Cast: control over TLS, Cast Streaming, AAC (rustls) |
player | yes | the browser receiver: a player page on 127.0.0.1 |
h264 | yes | the built-in H.264 encoder (raw frames, the test pattern) |
aac | with cast | the built-in AAC-LC encoder |
fairplay | no | FairPlay for AirPlay receivers that need it (LGPL, see below) |
share | no | share: a capture page for a tab, window or screen |
headless | no | share(Some(url), …): a browser of tvpipe’s own |
tunnel | no | public HTTPS links for the pages (rustls) |
files | no | MP4/MOV/Matroska sent unchanged, without ffmpeg |
ffmpeg | no | files, URLs and capture through an ffmpeg subprocess |
A program that only wants AirPlay with its own encoder takes
default-features = false, features = ["airplay"] (no rustls). Asking
for something a build leaves out fails with the error code
feature-disabled.
§Licensing
tvpipe is Apache-2.0. FairPlay, which some AirPlay receivers need, is a
port of doubletake under
LGPL-3.0-or-later, in its own crate, tvpipe-fairplay, which only the
fairplay feature pulls in. Rust links statically, so:
| Features | What you ship | Obligations |
|---|---|---|
default (no fairplay) | Apache-2.0 code only | the Apache-2.0 notice, and the third-party notices in LICENSES/ (openh264 tables BSD-2-Clause; OFL fonts with player/share; CDLA roots with tunnel) |
fairplay | LGPL-3.0-or-later code, linked statically | the above, plus LGPLv3: the license texts, a notice, and relinkability (your object files or source) |
Without fairplay, Apple TVs (pairing with a PIN) work; a receiver that
needs FairPlay fails with the code fairplay-required. Cargo unifies
features across a dependency graph, so check your own build:
cargo tree -e normal --prefix none --format "{p} {l}" | grep LGPL must
print nothing. This is not legal advice.
Programs that want FairPlay without linking it can run the tvpipe
command as a child process (see recipes).
Re-exports§
pub use events::EndInfo;pub use events::Event;pub use events::Paired;pub use events::PinRequest;pub use events::Started;pub use events::Stats;
Modules§
- events
- What sessions and commands report:
Event, the typed form of the machine interface’s events (docs/machine.md), andEvents, the per-session handle they go out through. - log
- Logging: off by default, a global handler the program may install.
- recipes
- Recipes: getting frames and sound out of common engines and libraries.
- slrw
- The game input format (docs/slrw.md): what
tvpipe play -reads on stdin, for programs that run thetvpipecommand instead of linking the library.
Structs§
- AirPlay
Service - An AirPlay (or RAOP) service and what its TXT record says.
- Audio
Writer - Writes audio from another thread (a sound card callback): cloneable, never blocks for long, timestamps by sample count from its first write on the stream’s clock.
- Cast
Service - A Google Cast service and what its TXT record says.
- Device
- A discovered receiver as programs see it (
discover --json, thedevicesevent): its name, addresses, and the services it offers. - Discovery
- Discovery in the background, for a program’s receiver menu:
devicesis what was found so far. Stops when dropped. - Endpoint
- Where a service is reached.
- Error
- What went wrong: a
kind, a message for people, a stablecodewhere the case is known (pairing-required,no-receiver,fairplay-required,feature-disabled, … as in docs/machine.md) and thedeviceit is about. - Frame
- A raw frame whose rows are
stridebytes apart (a GPU readback’s padded rows, a sub-rectangle of a larger buffer), optionally stored bottom row first (OpenGL’sglReadPixels). - Frame
Buffer - A raw frame to fill in place (a GPU readback writing straight into
it skips a copy): from
Stream::frame_buffer, queued withStream::submit. Derefs to the frame’s packed bytes. - H264
- One access unit of the program’s own H.264.
- Options
- The settings of a command: receivers, the stream’s shape, the browser receiver, storage and callbacks. Fields a command does not use are ignored. Cloning shares the callbacks.
- Pairing
- Pairing over several frames of a program’s UI:
statesays what it needs. - Player
Options - The
browserreceiver: a page on 127.0.0.1 that plays the stream in a browser tab (player). - Receiver
Info - The latest state of one receiver.
- Session
- A running session. Stop it with
stop, let it end withwait; dropping it stops it (and blocks until every receiver got its teardown, a few seconds at most). - Stopper
- Requests a session’s stop from anywhere (another thread, a signal
handler’s thread). Cloneable; see
Session::stopper. - Storage
- Where pairings and the player token are kept. Cloning shares it.
- Storage
Fn - A
StorageBackendfrom two closures (seestorage_fn). - Stream
- A live stream of the program’s own frames and sound to the receivers
of its
Options. Dropping it stops it: every receiver gets its teardown beforedropreturns.
Enums§
- Config
Format - How
Stream::write_h264_configdescribes the decoder configuration. - Encoder
- Which encoder makes the video: one of ffmpeg’s, or our own.
- Error
Kind - What went wrong, coarsely. Used for exit codes and retry decisions.
- Input
- What
playstreams. - Pairing
State - Where a
Pairingis. - Pixel
Format - The pixel layout of raw frames given to a
Stream. - Session
State - Where a session is.
- Tunnel
Provider - Who carries the link (
--tunnel[=PROVIDER]). - Written
- What became of a frame.
Traits§
- Storage
Backend - A program’s own storage for
Storage::custom: text items by name ("credentials","player-token").
Functions§
- discover
- The receivers on the local network, after browsing for
timeout(AirPlay and Cast records of one TV are oneDevice).pairedcomes from the default storage. - discover_
with discoverwith the storage ofoptionsforpaired.- pair
- Pairs with an AirPlay receiver (
airplay): the TV shows a PIN, whichon_pinreturns (None: give up). Blocks until done. The pairing is kept in the default storage; seepair_with. - pair_
with pairwith the storage (and events) ofoptions.- play
- Plays a file, a URL or an ffmpeg input to the receivers; blocks until they are connected.
- preview
play(or the test pattern withoutinput) to a browser tab only: the session’splayer_urlis the page.- share
- Shares a browser tab, window or screen to the receivers (
share): withouturl, the session’sshare_urlis a page to open and press Share on; with one, tvpipe’s own browser shows the page and shares it (headless). Returns once the session runs (the receivers connect after the capture starts). - storage_
fn - A backend from a load and a save function:
Storage::custom(storage_fn(|item| load(item), |item, text| save(item, text))). - stream
- Streams the program’s own frames and sound (
Stream); blocks until the receivers are connected (seconds). SeeStream::startto keep rendering meanwhile. - test_
pattern - The built-in test pattern (colour bars, a clock and a beep every second, for measuring latency); blocks until the receivers are connected.
- unpair
- Forgets the pairing with
target(a name or an address) in the storage ofoptions.