1use 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
18const EVENT_QUEUE: usize = 256;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum SessionState {
25 Connecting,
27 Streaming,
29 Ended,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct ReceiverInfo {
37 pub name: String,
39 pub protocol: Option<Protocol>,
41 pub state: ReceiverState,
43 pub error: Option<String>,
45 pub code: Option<String>,
47}
48
49#[derive(Clone)]
51pub(crate) struct StateHandle(Arc<Shared>);
52
53impl StateHandle {
54 pub(crate) fn connected(&self) -> bool {
56 let st = self.0.lock();
57 st.connected && !st.finished
58 }
59}
60
61pub type Callback = Box<dyn FnMut(&Event) + Send>;
63
64#[derive(Default)]
65struct State {
66 queue: VecDeque<Event>,
67 receivers: BTreeMap<String, ReceiverInfo>,
68 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 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
133pub 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#[derive(Clone, Debug)]
159pub struct Stopper(Stop);
160
161impl Stopper {
162 pub fn stop(&self) {
165 self.0.request();
166 }
167
168 pub fn stopped(&self) -> bool {
170 self.0.requested()
171 }
172}
173
174impl Session {
175 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 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 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 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 pub fn poll_events(&mut self) -> Vec<Event> {
277 self.shared.lock().queue.drain(..).collect()
278 }
279
280 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 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 pub fn stats(&self) -> Option<Stats> {
314 self.shared.lock().stats.clone()
315 }
316
317 pub fn started(&self) -> Option<Started> {
319 self.shared.lock().started.clone()
320 }
321
322 pub fn player_url(&self) -> Option<String> {
324 self.shared.lock().player_url.clone()
325 }
326
327 pub fn share_url(&self) -> Option<String> {
329 self.shared.lock().share_url.clone()
330 }
331
332 pub fn tunnel_urls(&self) -> Vec<String> {
334 self.shared.lock().tunnel_urls.clone()
335 }
336
337 pub fn stopper(&self) -> Stopper {
339 Stopper(self.stop.clone())
340 }
341
342 pub fn stop(mut self) -> Result<EndInfo> {
345 self.stop.request();
346 self.join()
347 }
348
349 pub fn wait(mut self) -> Result<EndInfo> {
352 self.join()
353 }
354
355 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}