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
use crate::transcoder::event_pixel_tree::DeltaT;
use crate::transcoder::event_pixel_tree::Mode::FramePerfect;
use crate::transcoder::source::video::SourceError;
use crate::transcoder::source::video::SourceError::BufferEmpty;
use crate::transcoder::source::video::Video;
use crate::transcoder::source::video::{Source, VideoBuilder};
use crate::{Coord, Event, TimeMode};
use crate::{PlaneSize, SourceCamera};
use opencv::core::{Mat, Size};
use opencv::videoio::{VideoCapture, CAP_PROP_FPS, CAP_PROP_FRAME_COUNT, CAP_PROP_POS_FRAMES};
use opencv::{imgproc, prelude::*, videoio, Result};
use rayon::ThreadPool;
use std::error::Error;
use std::mem::swap;

#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct IndirectCoord {
    pub(crate) forward: Coord,
    pub(crate) reverse: Coord,
}

/// Attributes of a framed video -> ADΔER transcode
pub struct Framed {
    cap: VideoCapture,
    pub(crate) input_frame_scaled: Mat,
    pub(crate) input_frame: Mat,
    pub frame_idx_start: u32,
    pub source_fps: f64,
    pub scale: f64,
    color_input: bool,
    pub(crate) video: Video,
    pub time_mode: TimeMode,
}
unsafe impl Sync for Framed {}

impl Framed {
    pub fn new(
        input_filename: String,
        color_input: bool,
        scale: f64,
    ) -> Result<Framed, Box<dyn Error>> {
        let mut cap =
            videoio::VideoCapture::from_file(input_filename.as_str(), videoio::CAP_FFMPEG)?;

        // Calculate TPS based on ticks per frame and source FPS
        let source_fps = cap.get(CAP_PROP_FPS)?.round();
        // builder.tps = builder.ref_time * source_fps as u32;
        // if builder.ref_time * cap.get(CAP_PROP_FPS)?.round() as u32 != builder.tps {
        //     return Err(SourceError::BadParams.into());
        // }

        let opened = videoio::VideoCapture::is_opened(&cap)?;
        if !opened {
            return Err("Failed to open video capture".into());
        }
        let mut init_frame = Mat::default();
        cap.read(&mut init_frame)?;
        cap.set(CAP_PROP_POS_FRAMES, 0.0)?;

        // Move start frame back
        // cap.set(CAP_PROP_POS_FRAMES, f64::from(builder.frame_idx_start))?;

        let mut init_frame_scaled = Mat::default();
        resize_input(&mut init_frame, &mut init_frame_scaled, scale)?;
        init_frame = init_frame_scaled;

        let plane = PlaneSize::new(
            init_frame.size()?.width as u16,
            init_frame.size()?.height as u16,
            if color_input { 3 } else { 1 },
        )?;

        let video = Video::new(plane, FramePerfect)?;

        Ok(Framed {
            cap,
            input_frame_scaled: Mat::default(),
            input_frame: Mat::default(),
            frame_idx_start: 0,
            source_fps,
            scale,
            color_input,
            video,
            time_mode: TimeMode::DeltaT,
        })
    }

    // pub fn skip_interval(mut self, frame_skip_interval: u8) -> Self {
    //     self.frame_skip_interval = frame_skip_interval;
    //     self
    // }

    pub fn frame_start(mut self, frame_idx_start: u32) -> Result<Self, Box<dyn Error>> {
        let video_frame_count = self.cap.get(CAP_PROP_FRAME_COUNT)?;
        if frame_idx_start >= video_frame_count as u32 {
            return Err(SourceError::StartOutOfBounds.into());
        };
        self.cap
            .set(CAP_PROP_POS_FRAMES, f64::from(frame_idx_start))?;
        self.frame_idx_start = frame_idx_start;
        Ok(self)
    }

    pub fn time_mode(mut self, time_mode: TimeMode) -> Self {
        self.time_mode = time_mode;
        self
    }

    pub fn auto_time_parameters(
        mut self,
        ref_time: crate::transcoder::event_pixel_tree::DeltaT,
        delta_t_max: crate::transcoder::event_pixel_tree::DeltaT,
    ) -> Result<Self, Box<dyn Error>> {
        if delta_t_max % ref_time == 0 {
            let tps = (ref_time as f64 * self.source_fps) as DeltaT;
            self.video = self.video.time_parameters(tps, ref_time, delta_t_max)?;
        } else {
            eprintln!("delta_t_max must be a multiple of ref_time");
        }
        Ok(self)
    }

    pub fn get_ref_time(&self) -> u32 {
        self.video.state.ref_time
    }
}

impl Source for Framed {
    /// Get pixel-wise intensities directly from source frame, and integrate them with
    /// [`ref_time`](Video::ref_time) (the number of ticks each frame is said to span)
    fn consume(
        &mut self,
        view_interval: u32,
        thread_pool: &ThreadPool,
    ) -> Result<Vec<Vec<Event>>, SourceError> {
        match self.cap.read(&mut self.input_frame) {
            Ok(_) => {
                match resize_frame(
                    &self.input_frame,
                    &mut self.input_frame_scaled,
                    self.color_input,
                    self.scale,
                ) {
                    Ok(_) => {}
                    Err(_) => return Err(SourceError::NoData),
                }
            }
            Err(e) => return Err(SourceError::OpencvError(e)),
        };

        if self.input_frame_scaled.empty() {
            return Err(BufferEmpty);
        }

        let tmp = self.input_frame_scaled.clone();

        thread_pool.install(|| {
            self.video
                .integrate_matrix(tmp, self.video.state.ref_time as f32, view_interval)
        })
    }

    fn get_video_mut(&mut self) -> &mut Video {
        &mut self.video
    }

    fn get_video_ref(&self) -> &Video {
        &self.video
    }

    fn get_video(self) -> Video {
        todo!()
    }
}

impl VideoBuilder for Framed {
    fn contrast_thresholds(mut self, c_thresh_pos: u8, c_thresh_neg: u8) -> Self {
        self.video = self.video.c_thresh_pos(c_thresh_pos);
        self.video = self.video.c_thresh_neg(c_thresh_neg);
        self
    }

    fn c_thresh_pos(mut self, c_thresh_pos: u8) -> Self {
        self.video = self.video.c_thresh_pos(c_thresh_pos);
        self
    }

    fn c_thresh_neg(mut self, c_thresh_neg: u8) -> Self {
        self.video = self.video.c_thresh_neg(c_thresh_neg);
        self
    }

    fn chunk_rows(mut self, chunk_rows: usize) -> Self {
        self.video = self.video.chunk_rows(chunk_rows);
        self
    }

    fn time_parameters(
        mut self,
        tps: crate::transcoder::event_pixel_tree::DeltaT,
        ref_time: crate::transcoder::event_pixel_tree::DeltaT,
        delta_t_max: crate::transcoder::event_pixel_tree::DeltaT,
    ) -> Result<Self, Box<dyn Error>> {
        if delta_t_max % ref_time == 0 {
            self.video = self.video.time_parameters(tps, ref_time, delta_t_max)?;
        } else {
            eprintln!("delta_t_max must be a multiple of ref_time");
        }
        Ok(self)
    }

    fn write_out(
        mut self,
        output_filename: String,
        source_camera: SourceCamera,
        time_mode: TimeMode,
    ) -> Result<Box<Self>, Box<dyn Error>> {
        self.video = self
            .video
            .write_out(output_filename, Some(source_camera), Some(time_mode))?;
        Ok(Box::new(self))
    }

    fn show_display(mut self, show_display: bool) -> Self {
        self.video = self.video.show_display(show_display);
        self
    }
}

/// Resize a grayscale [`Mat`]
fn resize_input(
    input_frame_gray: &mut Mat,
    input_frame_scaled: &mut Mat,
    resize_scale: f64,
) -> Result<(), opencv::Error> {
    if (resize_scale - 1.0).abs() < f64::EPSILON {
        // For performance. We don't need to read input_frame_gray again anyway
        swap(input_frame_gray, input_frame_scaled);
    } else {
        opencv::imgproc::resize(
            input_frame_gray,
            input_frame_scaled,
            Size {
                width: 0,
                height: 0,
            },
            resize_scale,
            resize_scale,
            0,
        )?;
    }
    Ok(())
}

fn resize_frame(
    input: &Mat,
    output: &mut Mat,
    color: bool,
    scale: f64,
) -> Result<(), opencv::Error> {
    let mut holder = Mat::default();
    if color {
        holder = input.clone();
    } else {
        // Yields an 8-bit grayscale mat
        imgproc::cvt_color(&input, &mut holder, imgproc::COLOR_BGR2GRAY, 1)?;
        // don't do anything with the error. This happens when we reach the end of
        // the video, so there's nothing to convert.
    }

    resize_input(&mut holder, output, scale)?;
    Ok(())
}