1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#![cfg_attr(feature = "backtrace", feature(error_generic_member_access))]

use parking_lot::Mutex;
use std::{collections::HashMap, sync::Arc};

use tokio_stream::StreamExt;

use basic_frame::DynamicFrame;
use bui_backend_session_types::ConnectionKey;
use event_stream_types::{ConnectionEvent, ConnectionEventType, EventChunkSender};

pub use http_video_streaming_types::{
    CircleParams, DrawableShape, FirehoseCallbackInner, Point, Shape, ToClient,
};

type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("unknown path")]
    UnknownPath(#[cfg(feature = "backtrace")] std::backtrace::Backtrace),
    #[error(transparent)]
    ConvertImageError(
        #[from]
        #[cfg_attr(feature = "backtrace", backtrace)]
        convert_image::Error,
    ),
}

// future: use MediaSource API? https://w3c.github.io/media-source

#[derive(Debug)]
pub struct AnnotatedFrame {
    pub frame: DynamicFrame,
    pub found_points: Vec<Point>,
    pub valid_display: Option<Shape>,
    pub annotations: Vec<DrawableShape>,
}

fn _test_annotated_frame_is_send() {
    // Compile-time test to ensure AnnotatedFrame implements Send trait.
    fn implements<T: Send>() {}
    implements::<AnnotatedFrame>();
}

#[derive(Debug)]
pub struct FirehoseCallback {
    pub arrival_time: chrono::DateTime<chrono::Utc>,
    pub inner: FirehoseCallbackInner,
}

struct PerSender {
    out: EventChunkSender,
    frame_lifo: Option<Arc<Mutex<AnnotatedFrame>>>,
    ready_to_send: bool,
    conn_key: ConnectionKey,
    fno: u64,
}

fn _test_per_sender_is_send() {
    // Compile-time test to ensure PerSender implements Send trait.
    fn implements<T: Send>() {}
    implements::<PerSender>();
}

#[derive(Debug)]
pub enum NameSelector {
    All,
    None,
    Name(String),
}

impl PerSender {
    fn new(
        out: EventChunkSender,
        conn_key: ConnectionKey,
        frame: Arc<Mutex<AnnotatedFrame>>,
    ) -> PerSender {
        PerSender {
            out,
            frame_lifo: Some(frame),
            ready_to_send: true,
            conn_key,
            fno: 0,
        }
    }
    fn push(&mut self, frame: Arc<Mutex<AnnotatedFrame>>) {
        self.fno += 1;
        self.frame_lifo = Some(frame);
    }
    fn got_callback(&mut self, msg: FirehoseCallback) {
        match chrono::DateTime::parse_from_rfc3339(&msg.inner.ts_rfc3339) {
            // match chrono::DateTime<chrono::FixedOffset>::parse_from_rfc3339(&msg.inner.ts_rfc3339) {
            Ok(sent_time) => {
                let latency = msg.arrival_time.signed_duration_since(sent_time);
                tracing::trace!("latency: {:?}", latency);
            }
            Err(e) => {
                tracing::error!("failed to parse timestamp in callback: {:?}", e);
            }
        }
        self.ready_to_send = true;
    }
    async fn service(&mut self) -> Result<()> {
        // check if we should send frame(s) and send if so.

        // should we send it?
        // TODO cache the converted frame.
        // TODO allow client to throttle?
        // TODO make algorithm smarter to have more in-flight frames?
        // TODO include sent time in message to clients so we don't maintain that

        if let Some(ref most_recent_frame_data) = self.frame_lifo {
            if self.ready_to_send {
                // sent_time computed early so that latency includes duration to encode, etc.
                let sent_time: chrono::DateTime<chrono::Utc> = chrono::Utc::now();
                let tc = {
                    let most_recent_frame_data = most_recent_frame_data.lock();
                    let bytes = basic_frame::match_all_dynamic_fmts!(
                        &most_recent_frame_data.frame,
                        x,
                        convert_image::frame_to_image(x, convert_image::ImageOptions::Jpeg(80),)
                    )?;
                    let firehose_frame_base64 = base64::encode(&bytes);
                    let data_url = format!("data:image/jpeg;base64,{}", firehose_frame_base64);
                    // most_recent_frame_data.data_url = Some(data_url.clone()); // todo: cache like this
                    let found_points = most_recent_frame_data.found_points.clone();
                    ToClient {
                        firehose_frame_data_url: data_url,
                        found_points,
                        valid_display: most_recent_frame_data.valid_display.clone(),
                        annotations: most_recent_frame_data.annotations.clone(),
                        fno: self.fno,
                        ts_rfc3339: sent_time.to_rfc3339(),
                        ck: self.conn_key,
                    }
                };
                let buf = serde_json::to_string(&tc).expect("encode");
                let buf = format!(
                    "event: {}\ndata: {}\n\n",
                    http_video_streaming_types::VIDEO_STREAM_EVENT_NAME,
                    buf
                );
                let hc = http_body::Frame::data(bytes::Bytes::from(buf));

                match self.out.send(Ok(hc)).await {
                    Ok(()) => {}
                    Err(_) => {
                        tracing::info!("failed to send data to connection. dropping.");
                        // Failed to send data to event stream key.
                        // TODO: drop this sender.
                    }
                }
                self.ready_to_send = false;
            }
        }

        self.frame_lifo = None;

        Ok(())
    }
}

struct TaskState {
    /// cache of senders
    per_sender_map: HashMap<ConnectionKey, PerSender>,
    /// most recent image frame, with annotations
    frame: Arc<Mutex<AnnotatedFrame>>,
}

fn _test_task_state_is_send() {
    // Compile-time test to ensure PerSender implements Send trait.
    fn implements<T: Send>() {}
    implements::<TaskState>();
}

impl TaskState {
    async fn service(&mut self) -> Result<()> {
        // TODO: make sending concurrent on all listeners and set a timeout.
        for ps in self.per_sender_map.values_mut() {
            ps.service().await?;
        }
        Ok(())
    }
    fn handle_connection(&mut self, conn_evt: ConnectionEvent) -> Result<()> {
        match conn_evt.typ {
            ConnectionEventType::Connect(chunk_sender) => {
                // sender was added.
                let ps = PerSender::new(chunk_sender, conn_evt.connection_key, self.frame.clone());
                self.per_sender_map.insert(conn_evt.connection_key, ps);
            }
            ConnectionEventType::Disconnect => {
                self.per_sender_map.remove(&conn_evt.connection_key);
            }
        }
        Ok(())
    }
    fn handle_frame(&mut self, new_frame: AnnotatedFrame) -> Result<()> {
        // Move the frame into a reference-counted pointer.
        self.frame = Arc::new(Mutex::new(new_frame));
        for ps in self.per_sender_map.values_mut() {
            // Clone the pointer and move the pointer into each sender.
            ps.push(self.frame.clone());
        }
        Ok(())
    }
    fn handle_callback(&mut self, callback: FirehoseCallback) -> Result<()> {
        if let Some(ps) = self.per_sender_map.get_mut(&callback.inner.ck) {
            ps.got_callback(callback)
        } else {
            tracing::warn!(
                "Got firehose_callback for non-existant connection key. \
                            Did connection disconnect?"
            );
        }
        Ok(())
    }
}

pub async fn firehose_task(
    connection_callback_rx: tokio::sync::mpsc::Receiver<ConnectionEvent>,
    mut firehose_rx: tokio::sync::mpsc::Receiver<AnnotatedFrame>,
    firehose_callback_rx: tokio::sync::mpsc::Receiver<FirehoseCallback>,
) -> Result<()> {
    // Wait for the first frame so we don't need to deal with an Option<>.
    let first_frame = firehose_rx.recv().await.unwrap();
    let frame = Arc::new(Mutex::new(first_frame));

    let mut task_state = TaskState {
        per_sender_map: HashMap::new(),
        frame,
    };

    let mut connection_callback_rx =
        tokio_stream::wrappers::ReceiverStream::new(connection_callback_rx);
    let mut firehose_callback_rx =
        tokio_stream::wrappers::ReceiverStream::new(firehose_callback_rx);
    loop {
        tokio::select! {
            opt_new_connection = connection_callback_rx.next() => {
                match opt_new_connection {
                    Some(new_connection) => {
                        task_state.handle_connection(new_connection)?;
                    }
                    None => {
                        tracing::debug!("new connection senders done.");
                        // All senders done.
                        break;
                    }
                }
            }
            opt_new_frame = firehose_rx.recv() => {
                match opt_new_frame {
                    Some(new_frame) => {
                        task_state.handle_frame(new_frame)?;
                    }
                    None => {
                        tracing::debug!("new frame senders done.");
                        // All senders done.
                        break;
                    }
                }
            },
            opt_callback = firehose_callback_rx.next() => {
                match opt_callback {
                    Some(callback) => {
                        task_state.handle_callback(callback)?;
                    }
                    None => {
                        tracing::debug!("new callback senders done.");
                        // All senders done.
                        break;
                    }
                }
            },
        }
        task_state.service().await?; // should use a timer for this??
    }
    tracing::debug!("firehose task done.");
    Ok(())
}