Skip to main content

tvpipe/api/
session.rs

1//! [`Session`]: a running command (`play`, `test_pattern`, `preview`,
2//! `share`, and the session inside a [`Stream`](crate::Stream)) on a
3//! thread of its own, with its events, its state and its end.
4
5use std::collections::{BTreeMap, VecDeque};
6use std::sync::mpsc;
7use std::sync::{Arc, Condvar, Mutex, MutexGuard};
8use std::thread::JoinHandle;
9use std::time::{Duration, Instant};
10
11use crate::ctx::Ctx;
12use crate::error::{Error, Result};
13use crate::events::{EndInfo, EndReason, Event, Events, Protocol, ReceiverState, Started, Stats};
14use crate::opts::Command;
15use crate::session::GameIo;
16use crate::util::stop::Stop;
17
18/// Events kept for [`Session::poll_events`]; older ones are dropped.
19const EVENT_QUEUE: usize = 256;
20
21/// Where a session is.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum SessionState {
25    /// Finding and connecting the receivers, opening the input.
26    Connecting,
27    /// Frames flow.
28    Streaming,
29    /// Over (see [`Session::wait`]).
30    Ended,
31}
32
33/// The latest state of one receiver.
34#[derive(Debug, Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct ReceiverInfo {
37    /// The receiver, as given or as discovered.
38    pub name: String,
39    /// Known once it connected (or failed while connecting).
40    pub protocol: Option<Protocol>,
41    /// Its latest state.
42    pub state: ReceiverState,
43    /// What went wrong, with `failed`, `lost`, `gave-up`.
44    pub error: Option<String>,
45    /// A stable code for the error, e.g. `pairing-required`.
46    pub code: Option<String>,
47}
48
49/// A view of a session's state for writers on other threads.
50#[derive(Clone)]
51pub(crate) struct StateHandle(Arc<Shared>);
52
53impl StateHandle {
54    /// The receivers are connected and the session still runs.
55    pub(crate) fn connected(&self) -> bool {
56        let st = self.0.lock();
57        st.connected && !st.finished
58    }
59}
60
61/// A session's event callback (`Options::on_event`).
62pub type Callback = Box<dyn FnMut(&Event) + Send>;
63
64#[derive(Default)]
65struct State {
66    queue: VecDeque<Event>,
67    receivers: BTreeMap<String, ReceiverInfo>,
68    /// Receivers in the order they were first reported.
69    order: Vec<String>,
70    started: Option<Started>,
71    stats: Option<Stats>,
72    player_url: Option<String>,
73    share_url: Option<String>,
74    tunnel_urls: Vec<String>,
75    connected: bool,
76    end: Option<EndInfo>,
77    /// The session thread returned (with this result, taken by `wait`).
78    done: Option<Result<()>>,
79    finished: bool,
80}
81
82pub(crate) struct Shared {
83    state: Mutex<State>,
84    cv: Condvar,
85}
86
87impl Shared {
88    fn lock(&self) -> MutexGuard<'_, State> {
89        self.state.lock().unwrap_or_else(|e| e.into_inner())
90    }
91
92    fn record(&self, e: &Event) {
93        let mut st = self.lock();
94        match e {
95            Event::Receiver(r) => {
96                if !st.receivers.contains_key(&r.name) {
97                    st.order.push(r.name.clone());
98                }
99                let protocol = r
100                    .protocol
101                    .or_else(|| st.receivers.get(&r.name).and_then(|i| i.protocol));
102                st.receivers.insert(
103                    r.name.clone(),
104                    ReceiverInfo {
105                        name: r.name.clone(),
106                        protocol,
107                        state: r.state,
108                        error: r.error.clone(),
109                        code: r.code.clone(),
110                    },
111                );
112            }
113            Event::Connected(_) => st.connected = true,
114            Event::Started(s) => st.started = Some(s.clone()),
115            Event::Stats(s) => st.stats = Some(s.clone()),
116            Event::Player(p) => {
117                st.player_url.get_or_insert_with(|| p.url.clone());
118            }
119            Event::SharePage(p) => st.share_url = Some(p.url.clone()),
120            Event::Tunnel(t) => st.tunnel_urls.push(t.url.clone()),
121            Event::End(e) => st.end = Some(e.clone()),
122            _ => {}
123        }
124        if st.queue.len() >= EVENT_QUEUE {
125            st.queue.pop_front();
126        }
127        st.queue.push_back(e.clone());
128        drop(st);
129        self.cv.notify_all();
130    }
131}
132
133/// A running session. Stop it with [`stop`](Session::stop), let it end
134/// with [`wait`](Session::wait); dropping it stops it (and blocks until
135/// every receiver got its teardown, a few seconds at most).
136///
137/// Events: [`poll_events`](Session::poll_events) drains a queue (the
138/// latest 256), `Options::on_event` calls a function on a thread of the
139/// session's own; the snapshots ([`receivers`](Session::receivers),
140/// [`stats`](Session::stats), …) need neither.
141pub struct Session {
142    shared: Arc<Shared>,
143    stop: Stop,
144    thread: Option<JoinHandle<()>>,
145    dispatcher: Option<JoinHandle<()>>,
146}
147
148impl std::fmt::Debug for Session {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        f.debug_struct("Session")
151            .field("state", &self.state())
152            .finish_non_exhaustive()
153    }
154}
155
156/// Requests a session's stop from anywhere (another thread, a signal
157/// handler's thread). Cloneable; see [`Session::stopper`].
158#[derive(Clone, Debug)]
159pub struct Stopper(Stop);
160
161impl Stopper {
162    /// Stops the session now (no playout of what is queued); the
163    /// receivers get their TEARDOWN/STOP.
164    pub fn stop(&self) {
165        self.0.request();
166    }
167
168    /// Whether a stop was requested.
169    pub fn stopped(&self) -> bool {
170        self.0.requested()
171    }
172}
173
174impl Session {
175    /// Runs `cmd` on a thread of its own. `ctx` brings the stop token and
176    /// the storage; its events go to the session (and then to `ctx.events`
177    /// if that listens, synchronously, as the CLI's `--machine` wants).
178    pub(crate) fn spawn(
179        cmd: Command,
180        mut ctx: Ctx,
181        io: GameIo,
182        mut callback: Option<Callback>,
183    ) -> Result<Session> {
184        crate::util::timer::raise_resolution();
185        let shared = Arc::new(Shared {
186            state: Mutex::new(State::default()),
187            cv: Condvar::new(),
188        });
189        let (tx, rx) = mpsc::channel::<Event>();
190        let dispatcher = match callback.take() {
191            Some(mut f) => Some(
192                std::thread::Builder::new()
193                    .name("tvpipe-events".into())
194                    .spawn(move || {
195                        while let Ok(e) = rx.recv() {
196                            f(&e);
197                        }
198                    })
199                    .map_err(|e| Error::io("spawn the event thread", e))?,
200            ),
201            None => None,
202        };
203        let outer = ctx.events.clone();
204        let s = shared.clone();
205        let send = dispatcher.is_some().then_some(tx);
206        let send = send.map(Mutex::new);
207        ctx.events = Events::to(move |e| {
208            s.record(&e);
209            if let Some(tx) = &send {
210                let _ = tx.lock().unwrap_or_else(|e| e.into_inner()).send(e.clone());
211            }
212            outer.emit(e);
213        });
214        let stop = ctx.stop.clone();
215        let s = shared.clone();
216        let thread = std::thread::Builder::new()
217            .name("tvpipe-session".into())
218            .spawn(move || {
219                let rv = crate::session::run(cmd, &ctx, io);
220                // The events handle (and with it the dispatcher's sender)
221                // goes before the result is published.
222                drop(ctx);
223                let mut st = s.lock();
224                st.done = Some(rv);
225                st.finished = true;
226                drop(st);
227                s.cv.notify_all();
228            })
229            .map_err(|e| Error::io("spawn the session thread", e))?;
230        Ok(Session {
231            shared,
232            stop,
233            thread: Some(thread),
234            dispatcher,
235        })
236    }
237
238    /// Blocks until the receivers are connected (the input opens next),
239    /// or the session ended (then its error).
240    pub(crate) fn wait_connected(&self) -> Result<()> {
241        let mut st = self.shared.lock();
242        loop {
243            if st.connected {
244                return Ok(());
245            }
246            if st.finished {
247                return match st.done.take() {
248                    Some(Err(e)) => {
249                        st.done = Some(Err(e.clone_lossy()));
250                        Err(e)
251                    }
252                    _ => Err(Error::closed("the session ended before it connected")),
253                };
254            }
255            st = self.shared.cv.wait(st).unwrap_or_else(|e| e.into_inner());
256        }
257    }
258
259    pub(crate) fn state_handle(&self) -> StateHandle {
260        StateHandle(self.shared.clone())
261    }
262
263    /// Where the session is.
264    pub fn state(&self) -> SessionState {
265        let st = self.shared.lock();
266        if st.finished || st.end.is_some() {
267            SessionState::Ended
268        } else if st.started.is_some() {
269            SessionState::Streaming
270        } else {
271            SessionState::Connecting
272        }
273    }
274
275    /// The events since the last call (at most the latest 256).
276    pub fn poll_events(&mut self) -> Vec<Event> {
277        self.shared.lock().queue.drain(..).collect()
278    }
279
280    /// The next event, waiting up to `timeout`; `None` when there was none
281    /// (or the session is over and every event was taken).
282    pub fn next_event(&mut self, timeout: Duration) -> Option<Event> {
283        let until = Instant::now() + timeout;
284        let mut st = self.shared.lock();
285        loop {
286            if let Some(e) = st.queue.pop_front() {
287                return Some(e);
288            }
289            let now = Instant::now();
290            if st.finished || now >= until {
291                return None;
292            }
293            st = self
294                .shared
295                .cv
296                .wait_timeout(st, until - now)
297                .unwrap_or_else(|e| e.into_inner())
298                .0;
299        }
300    }
301
302    /// Every receiver's latest state, in the order they were first
303    /// reported.
304    pub fn receivers(&self) -> Vec<ReceiverInfo> {
305        let st = self.shared.lock();
306        st.order
307            .iter()
308            .filter_map(|n| st.receivers.get(n).cloned())
309            .collect()
310    }
311
312    /// The latest counters (once a second while frames flow).
313    pub fn stats(&self) -> Option<Stats> {
314        self.shared.lock().stats.clone()
315    }
316
317    /// The plan, once streaming started.
318    pub fn started(&self) -> Option<Started> {
319        self.shared.lock().started.clone()
320    }
321
322    /// The page of the `browser` receiver, once it listens.
323    pub fn player_url(&self) -> Option<String> {
324        self.shared.lock().player_url.clone()
325    }
326
327    /// `share` without a URL: the page to open and share from.
328    pub fn share_url(&self) -> Option<String> {
329        self.shared.lock().share_url.clone()
330    }
331
332    /// The public links (`tunnel`), once they work.
333    pub fn tunnel_urls(&self) -> Vec<String> {
334        self.shared.lock().tunnel_urls.clone()
335    }
336
337    /// A handle that stops the session from another thread.
338    pub fn stopper(&self) -> Stopper {
339        Stopper(self.stop.clone())
340    }
341
342    /// Stops now (no playout of what is queued): every receiver gets its
343    /// TEARDOWN/STOP. Returns how the session ended.
344    pub fn stop(mut self) -> Result<EndInfo> {
345        self.stop.request();
346        self.join()
347    }
348
349    /// Waits until the session ends by itself (the input ended, every
350    /// receiver left) or is stopped.
351    pub fn wait(mut self) -> Result<EndInfo> {
352        self.join()
353    }
354
355    /// Waits up to `timeout`; `true` when the session is over (then
356    /// [`wait`](Session::wait) returns at once).
357    pub fn wait_timeout(&self, timeout: Duration) -> bool {
358        let until = Instant::now() + timeout;
359        let mut st = self.shared.lock();
360        while !st.finished {
361            let now = Instant::now();
362            if now >= until {
363                return false;
364            }
365            st = self
366                .shared
367                .cv
368                .wait_timeout(st, until - now)
369                .unwrap_or_else(|e| e.into_inner())
370                .0;
371        }
372        true
373    }
374
375    fn join(&mut self) -> Result<EndInfo> {
376        if let Some(t) = self.thread.take() {
377            let _ = t.join();
378        }
379        if let Some(d) = self.dispatcher.take() {
380            let _ = d.join();
381        }
382        let mut st = self.shared.lock();
383        let end = st.end.clone();
384        match st.done.take() {
385            Some(Err(e)) => Err(e),
386            _ => Ok(end.unwrap_or_else(|| {
387                EndInfo::new(if self.stop.requested() {
388                    EndReason::Stopped
389                } else {
390                    EndReason::Done
391                })
392            })),
393        }
394    }
395}
396
397impl Drop for Session {
398    fn drop(&mut self) {
399        if self.thread.is_some() {
400            self.stop.request();
401            let _ = self.join();
402        }
403    }
404}