Skip to main content

Crate tvpipe

Crate tvpipe 

Source
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.

  • discover finds receivers; Discovery keeps looking for a program’s receiver menu.
  • pair / Pairing: Apple TVs pair once with a PIN; or give Options::on_pin and a stream pairs when it has to.
  • play (files, URLs, capture through ffmpeg), test_pattern, preview (a browser tab) and share (a tab, window or screen, through a page in the user’s browser) return a Session.
  • 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 the tvpipe command’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

FeatureDefaultBrings
airplayyesAirPlay mirroring: pairing, video, ALAC audio (ring)
castyesGoogle Cast: control over TLS, Cast Streaming, AAC (rustls)
playeryesthe browser receiver: a player page on 127.0.0.1
h264yesthe built-in H.264 encoder (raw frames, the test pattern)
aacwith castthe built-in AAC-LC encoder
fairplaynoFairPlay for AirPlay receivers that need it (LGPL, see below)
sharenoshare: a capture page for a tab, window or screen
headlessnoshare(Some(url), …): a browser of tvpipe’s own
tunnelnopublic HTTPS links for the pages (rustls)
filesnoMP4/MOV/Matroska sent unchanged, without ffmpeg
ffmpegnofiles, 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:

FeaturesWhat you shipObligations
default (no fairplay)Apache-2.0 code onlythe 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)
fairplayLGPL-3.0-or-later code, linked staticallythe 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), and Events, 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 the tvpipe command instead of linking the library.

Structs§

AirPlayService
An AirPlay (or RAOP) service and what its TXT record says.
AudioWriter
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.
CastService
A Google Cast service and what its TXT record says.
Device
A discovered receiver as programs see it (discover --json, the devices event): its name, addresses, and the services it offers.
Discovery
Discovery in the background, for a program’s receiver menu: devices is 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 stable code where the case is known (pairing-required, no-receiver, fairplay-required, feature-disabled, … as in docs/machine.md) and the device it is about.
Frame
A raw frame whose rows are stride bytes apart (a GPU readback’s padded rows, a sub-rectangle of a larger buffer), optionally stored bottom row first (OpenGL’s glReadPixels).
FrameBuffer
A raw frame to fill in place (a GPU readback writing straight into it skips a copy): from Stream::frame_buffer, queued with Stream::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: state says what it needs.
PlayerOptions
The browser receiver: a page on 127.0.0.1 that plays the stream in a browser tab (player).
ReceiverInfo
The latest state of one receiver.
Session
A running session. Stop it with stop, let it end with wait; 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.
StorageFn
A StorageBackend from two closures (see storage_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 before drop returns.

Enums§

ConfigFormat
How Stream::write_h264_config describes the decoder configuration.
Encoder
Which encoder makes the video: one of ffmpeg’s, or our own.
ErrorKind
What went wrong, coarsely. Used for exit codes and retry decisions.
Input
What play streams.
PairingState
Where a Pairing is.
PixelFormat
The pixel layout of raw frames given to a Stream.
SessionState
Where a session is.
TunnelProvider
Who carries the link (--tunnel[=PROVIDER]).
Written
What became of a frame.

Traits§

StorageBackend
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 one Device). paired comes from the default storage.
discover_with
discover with the storage of options for paired.
pair
Pairs with an AirPlay receiver (airplay): the TV shows a PIN, which on_pin returns (None: give up). Blocks until done. The pairing is kept in the default storage; see pair_with.
pair_with
pair with the storage (and events) of options.
play
Plays a file, a URL or an ffmpeg input to the receivers; blocks until they are connected.
preview
play (or the test pattern without input) to a browser tab only: the session’s player_url is the page.
share
Shares a browser tab, window or screen to the receivers (share): without url, the session’s share_url is 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). See Stream::start to 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 of options.

Type Aliases§

Result
A Result with tvpipe’s Error.