Skip to main content

stream/
stream.rs

1//! A program streaming its own frames and sound with the tvpipe library:
2//! a moving test card drawn in software and a 440 Hz tone, to a browser
3//! tab (or the receivers named on the command line).
4//!
5//! ```text
6//! cargo run --release --example stream               # a browser tab
7//! cargo run --release --example stream -- "Living Room" browser
8//! ```
9//!
10//! It prints the player page's URL; open it to watch. Ctrl-C ends the
11//! program (dropping the stream stops the receivers).
12
13use std::time::Duration;
14
15use tvpipe::{Event, Options, PixelFormat, PlayerOptions, Written};
16
17const W: usize = 640;
18const H: usize = 360;
19const FPS: u64 = 30;
20const RATE: u32 = 48_000;
21
22fn main() -> tvpipe::Result<()> {
23    let mut targets: Vec<String> = std::env::args().skip(1).collect();
24    if targets.is_empty() {
25        targets.push("browser".into());
26    }
27    let mut options = Options::new()
28        .video(W as u32, H as u32, FPS as u32, PixelFormat::Rgba)
29        .audio(RATE, 2)
30        .player(PlayerOptions::new().port(0))
31        // Pairing with an Apple TV that needs it, on the terminal.
32        .on_pin(|req| {
33            eprint!("PIN shown on {}: ", req.name);
34            let mut line = String::new();
35            std::io::stdin().read_line(&mut line).ok()?;
36            Some(line.trim().to_owned())
37        });
38    for t in &targets {
39        options = options.to(t.as_str());
40    }
41    let mut s = tvpipe::stream(options)?;
42    if let Some(url) = s.player_url() {
43        println!("watch at {url}");
44    }
45
46    let mut frame = vec![0u8; W * H * 4];
47    let mut pcm = Vec::new();
48    let mut phase = 0.0f32;
49    let mut sent = 0u64;
50    for n in 0u64.. {
51        let pts = Duration::from_micros(n * 1_000_000 / FPS);
52        // Pace by the stream's clock: a game would render at its own rate.
53        if let Some(wait) = pts.checked_sub(s.elapsed()) {
54            std::thread::sleep(wait);
55        }
56        draw(&mut frame, n);
57        if s.write_video(&frame, pts)? == Written::Queued {
58            sent += 1;
59        }
60        tone(&mut pcm, &mut phase, (RATE as u64 / FPS) as usize);
61        s.write_audio(&pcm, pts)?;
62        for e in s.poll_events() {
63            match e {
64                Event::Receiver(r) => println!("{}: {}", r.name, r.state),
65                Event::Stats(st) if st.elapsed_ms / 1000 % 5 == 0 => {
66                    println!("{} s, {sent} frames queued", st.elapsed_ms / 1000)
67                }
68                _ => {}
69            }
70        }
71    }
72    s.finish()?;
73    Ok(())
74}
75
76/// Colour bars that scroll, with a white square that moves.
77fn draw(frame: &mut [u8], n: u64) {
78    const BARS: [[u8; 3]; 7] = [
79        [235, 235, 235],
80        [235, 235, 16],
81        [16, 235, 235],
82        [16, 235, 16],
83        [235, 16, 235],
84        [235, 16, 16],
85        [16, 16, 235],
86    ];
87    let shift = (n as usize * 4) % W;
88    let (sx, sy) = ((n as usize * 7) % (W - 40), (n as usize * 3) % (H - 40));
89    for y in 0..H {
90        for x in 0..W {
91            let i = (y * W + x) * 4;
92            let c = if (sx..sx + 40).contains(&x) && (sy..sy + 40).contains(&y) {
93                [255, 255, 255]
94            } else {
95                BARS[((x + shift) % W) * BARS.len() / W]
96            };
97            frame[i..i + 4].copy_from_slice(&[c[0], c[1], c[2], 255]);
98        }
99    }
100}
101
102/// `samples` stereo samples of a 440 Hz tone.
103fn tone(pcm: &mut Vec<i16>, phase: &mut f32, samples: usize) {
104    pcm.clear();
105    for _ in 0..samples {
106        let v = (phase.sin() * 6000.0) as i16;
107        pcm.extend_from_slice(&[v, v]);
108        *phase += 2.0 * std::f32::consts::PI * 440.0 / RATE as f32;
109        if *phase > 2.0 * std::f32::consts::PI {
110            *phase -= 2.0 * std::f32::consts::PI;
111        }
112    }
113}