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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use std::{cmp::Ordering, pin::Pin};

use futures::{
    stream::Stream,
    task::{Context, Poll},
};
use pin_project::pin_project;

use crate::FrameDataAndPoints;

use crate::bundled_data::BundledAllCamsOneFrameDistorted;
use crate::connected_camera_manager::HasCameraList;

/// Orders data from all available cameras from a given frame.
///
/// The returned stream will be monotonically increasing. Note that out-of-order
/// data will be dropped and, although the returned values will be monotonically
/// increasing, it will not, in general, be contiguous. In otherwords, it is
/// possible that there will be gaps in the resulting monotonically increasing
/// sequence.
#[pin_project]
pub(crate) struct OrderedLossyFrameBundler<St, HCL>
where
    St: Stream<Item = StreamItem>,
    HCL: HasCameraList,
{
    #[pin]
    stream: St,
    ccm: HCL,
    current: Option<BundledAllCamsOneFrameDistorted>,
    #[pin]
    pending: Option<StreamItem>,
}

#[derive(Debug)]
pub enum StreamItem {
    EOF,
    Packet(FrameDataAndPoints),
}

impl<St, HCL> OrderedLossyFrameBundler<St, HCL>
where
    St: Stream<Item = StreamItem>,
    HCL: HasCameraList,
{
    fn new(stream: St, ccm: HCL) -> Self {
        Self {
            stream,
            ccm,
            current: None,
            pending: None,
        }
    }
}

impl<St, HCL> Stream for OrderedLossyFrameBundler<St, HCL>
where
    St: Stream<Item = StreamItem>,
    HCL: HasCameraList,
{
    // In theory, it would be possible to return contiguous frame values,
    // but this would require more complexity here.
    type Item = BundledAllCamsOneFrameDistorted;
    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<BundledAllCamsOneFrameDistorted>> {
        use futures::ready;

        loop {
            let all_cameras = self.ccm.camera_list();

            let mut this = self.as_mut().project();

            // ensure that we have a pending item to work with, return if not.
            if this.pending.is_none() {
                let item = match ready!(this.stream.poll_next(cx)) {
                    Some(e) => e,
                    None => {
                        return Poll::Ready(None);
                    }
                };
                this.pending.set(Some(item));
            }

            // The following unwrap cannot fail because of above.
            let new_item: FrameDataAndPoints = match this.pending.take().unwrap() {
                StreamItem::EOF => {
                    return Poll::Ready(this.current.take());
                }
                StreamItem::Packet(new_item) => new_item,
            };

            if this.current.is_none() {
                // In the case of no existing data, save this new frame data.
                *this.current = Some(BundledAllCamsOneFrameDistorted::new(new_item));
            } else {
                // In the case of existing data, check if we are done or not.
                let dt = {
                    let current = this.current.as_ref().unwrap();
                    new_item.frame_data.synced_frame.0 as i64 - current.frame().0 as i64
                };

                match dt.cmp(&0) {
                    Ordering::Equal => {
                        // new packet from ongoing frame.
                        let current: &mut Option<BundledAllCamsOneFrameDistorted> = this.current;
                        let current_cameras = {
                            let x = current.as_mut().unwrap();
                            x.push(new_item);
                            x.cameras()
                        };

                        if current_cameras == &all_cameras {
                            let previous = current.take().unwrap();
                            *current = None;
                            return Poll::Ready(Some(previous));
                        }
                    }
                    Ordering::Greater => {
                        // New packet from future frame. Return the accumulated-
                        // until now data and start accumulating from this new
                        // data.
                        let current: &mut Option<BundledAllCamsOneFrameDistorted> = this.current;
                        let previous = current.take().unwrap();
                        *current = Some(BundledAllCamsOneFrameDistorted::new(new_item));
                        return Poll::Ready(Some(previous));
                    }
                    Ordering::Less => {
                        // Drop `new_item` because it has higher latency.
                    }
                }
            }
        }
    }
}

pub(crate) fn bundle_frames<St, HCL>(stream: St, ccm: HCL) -> OrderedLossyFrameBundler<St, HCL>
where
    St: Stream<Item = StreamItem>,
    HCL: HasCameraList,
{
    OrderedLossyFrameBundler::new(stream, ccm)
}

#[test]
fn test_frame_bundler() {
    use futures::stream::{self, StreamExt};

    use crate::{FlydraFloatTimestampLocal, FrameData, SyncFno};

    let cam_name_1 = crate::RawCamName::new("cam1".into());
    let cam_num_1 = crate::CamNum(1);
    let cam_name_2 = crate::RawCamName::new("cam2".into());
    let cam_num_2 = crate::CamNum(2);
    let trigger_timestamp = None;

    let packet1_frame1_cam1 = FrameDataAndPoints {
        frame_data: FrameData::new(
            cam_name_1,
            cam_num_1,
            SyncFno(1),
            trigger_timestamp.clone(),
            FlydraFloatTimestampLocal::from_f64(0.0),
            None,
            None,
        ),
        points: Vec::new(),
    };

    let packet2_frame1_cam2 = FrameDataAndPoints {
        frame_data: FrameData::new(
            cam_name_2.clone(),
            cam_num_2,
            SyncFno(1),
            trigger_timestamp.clone(),
            FlydraFloatTimestampLocal::from_f64(0.0),
            None,
            None,
        ),
        points: Vec::new(),
    };

    let packet2_frame0_cam2 = FrameDataAndPoints {
        frame_data: FrameData::new(
            cam_name_2.clone(),
            cam_num_2,
            SyncFno(0),
            trigger_timestamp.clone(),
            FlydraFloatTimestampLocal::from_f64(0.0),
            None,
            None,
        ),
        points: Vec::new(),
    };

    let packet2_frame2_cam2 = FrameDataAndPoints {
        frame_data: FrameData::new(
            cam_name_2.clone(),
            cam_num_2,
            SyncFno(2),
            trigger_timestamp.clone(),
            FlydraFloatTimestampLocal::from_f64(0.0),
            None,
            None,
        ),
        points: Vec::new(),
    };

    let packet2_frame3_cam2 = FrameDataAndPoints {
        frame_data: FrameData::new(
            cam_name_2,
            cam_num_2,
            SyncFno(3),
            trigger_timestamp,
            FlydraFloatTimestampLocal::from_f64(0.0),
            None,
            None,
        ),
        points: Vec::new(),
    };

    // with zero packets

    let inputs: Vec<_> = vec![StreamItem::EOF];

    let cameras = crate::connected_camera_manager::CameraList::new(&[1, 2]);
    let bundled = bundle_frames(stream::iter(inputs), cameras.clone());
    let actual: Vec<_> = futures::executor::block_on(bundled.collect());
    assert_eq!(actual.len(), 0);

    // with one packet

    let inputs: Vec<_> = vec![
        StreamItem::Packet(packet1_frame1_cam1.clone()),
        StreamItem::EOF,
    ];

    let expected = packet1_frame1_cam1.clone();
    let bundled = bundle_frames(stream::iter(inputs), cameras.clone());
    let actual: Vec<_> = futures::executor::block_on(bundled.collect());
    assert_eq!(actual.len(), 1);
    assert_eq!(
        actual[0],
        BundledAllCamsOneFrameDistorted::new(expected.clone())
    );

    // with two packets from same frame

    let inputs: Vec<_> = vec![
        StreamItem::Packet(packet1_frame1_cam1.clone()),
        StreamItem::Packet(packet2_frame1_cam2.clone()),
        StreamItem::EOF,
    ];

    let bundled = bundle_frames(stream::iter(inputs), cameras.clone());
    let actual: Vec<_> = futures::executor::block_on(bundled.collect());
    assert_eq!(actual.len(), 1);
    assert_eq!(actual[0].num_cameras(), 2);

    // with two packets from with a later outdated frame

    let inputs: Vec<_> = vec![
        StreamItem::Packet(packet1_frame1_cam1.clone()),
        StreamItem::Packet(packet2_frame0_cam2),
        StreamItem::EOF,
    ];

    let bundled = bundle_frames(stream::iter(inputs), cameras.clone());
    let actual: Vec<_> = futures::executor::block_on(bundled.collect());
    assert_eq!(actual.len(), 1);
    assert_eq!(actual[0], BundledAllCamsOneFrameDistorted::new(expected));

    // with two subsequent packets

    let inputs: Vec<_> = vec![
        StreamItem::Packet(packet1_frame1_cam1.clone()),
        StreamItem::Packet(packet2_frame2_cam2),
        StreamItem::EOF,
    ];

    let bundled = bundle_frames(stream::iter(inputs), cameras.clone());
    let actual: Vec<_> = futures::executor::block_on(bundled.collect());
    assert_eq!(actual.len(), 2);
    assert_eq!(actual[0].num_cameras(), 1);
    assert_eq!(actual[1].num_cameras(), 1);

    // with non-adjacent subsequent packets

    let inputs: Vec<_> = vec![
        StreamItem::Packet(packet1_frame1_cam1.clone()),
        StreamItem::Packet(packet2_frame3_cam2),
        StreamItem::EOF,
    ];

    let bundled = bundle_frames(stream::iter(inputs), cameras.clone());
    let actual: Vec<_> = futures::executor::block_on(bundled.collect());
    assert_eq!(actual.len(), 2);
    assert_eq!(actual[0].num_cameras(), 1);
    assert_eq!(actual[1].num_cameras(), 1);

    // At the moment all frames arrived and not one frame later. Thus, no EOF
    // marker.

    let inputs: Vec<_> = vec![
        StreamItem::Packet(packet1_frame1_cam1.clone()),
        StreamItem::Packet(packet2_frame1_cam2),
    ];

    let bundled = bundle_frames(stream::iter(inputs), cameras.clone());
    let actual: Vec<_> = futures::executor::block_on(bundled.collect());
    assert_eq!(actual.len(), 1);
    assert_eq!(actual[0].num_cameras(), 2);

    // But not if only one frame arrives.

    let inputs: Vec<_> = vec![StreamItem::Packet(packet1_frame1_cam1)];

    let bundled = bundle_frames(stream::iter(inputs), cameras);
    let actual: Vec<_> = futures::executor::block_on(bundled.collect());
    assert_eq!(actual.len(), 0);
}

#[test]
fn test_async_stream_ops() {
    use futures::future;
    use futures::stream::{self, StreamExt};

    let stream = stream::iter(1..=10);
    let evens = stream.filter_map(|x| {
        let ret = if x % 2 == 0 { Some(x + 1) } else { None };
        future::ready(ret)
    });

    let result: Vec<_> = futures::executor::block_on(evens.collect());
    assert_eq!(vec![3, 5, 7, 9, 11], result);
}