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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#[cfg(feature = "compression")]
use crate::codec::compressed::adu::frame::Adu;
use crate::codec::header::{Magic, MAGIC_RAW};
use crate::codec::{CodecError, CodecMetadata, ReadCompression, WriteCompression};
use crate::{Coord, Event, EventSingle, EOF_PX_ADDRESS};
use bincode::config::{FixintEncoding, WithOtherEndian, WithOtherIntEncoding};
use bincode::{DefaultOptions, Options};
use bitstream_io::{BigEndian, BitRead, BitReader};
use std::collections::BinaryHeap;
use std::io::{Read, Seek, SeekFrom, Write};

/// Write uncompressed (raw) ADΔER data to a stream.
pub struct RawOutput<W> {
    pub(crate) meta: CodecMetadata,
    pub(crate) bincode: WithOtherEndian<
        WithOtherIntEncoding<DefaultOptions, FixintEncoding>,
        bincode::config::BigEndian,
    >,
    pub(crate) stream: Option<W>,
}

/// Write uncompressed (raw) ADΔER data to a stream.
pub struct RawOutputInterleaved<W> {
    pub(crate) meta: CodecMetadata,
    pub(crate) bincode: WithOtherEndian<
        WithOtherIntEncoding<DefaultOptions, FixintEncoding>,
        bincode::config::BigEndian,
    >,
    queue: BinaryHeap<Event>,
    pub(crate) stream: Option<W>,
}

/// Read uncompressed (raw) ADΔER data from a stream.
pub struct RawInput<R: Read + Seek> {
    pub(crate) meta: CodecMetadata,
    pub(crate) bincode: WithOtherEndian<
        WithOtherIntEncoding<DefaultOptions, FixintEncoding>,
        bincode::config::BigEndian,
    >,
    _phantom: std::marker::PhantomData<R>,
}

impl<W: Write> RawOutput<W> {
    /// Create a new raw output stream.
    pub fn new(mut meta: CodecMetadata, writer: W) -> Self {
        let bincode = DefaultOptions::new()
            .with_fixint_encoding()
            .with_big_endian();
        meta.event_size = match meta.plane.c() {
            1 => bincode.serialized_size(&EventSingle::default()).unwrap() as u8,
            _ => bincode.serialized_size(&Event::default()).unwrap() as u8,
        };
        Self {
            meta,
            bincode,
            stream: Some(writer),
        }
    }

    fn stream(&mut self) -> &mut W {
        self.stream.as_mut().unwrap()
    }
}

impl<W: Write> WriteCompression<W> for RawOutput<W> {
    fn magic(&self) -> Magic {
        MAGIC_RAW
    }

    fn meta(&self) -> &CodecMetadata {
        &self.meta
    }

    fn meta_mut(&mut self) -> &mut CodecMetadata {
        &mut self.meta
    }

    fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), std::io::Error> {
        // Silently ignore the returned usize because we don't care about the number of bytes
        self.stream().write(bytes).map(|_| ())
    }

    // Will always be byte-aligned. Do nothing.
    fn byte_align(&mut self) -> std::io::Result<()> {
        Ok(())
    }

    // If `self.writer` is a `BufWriter`, you'll need to flush it yourself after this.
    fn into_writer(&mut self) -> Option<W> {
        let eof = Event {
            coord: Coord {
                x: EOF_PX_ADDRESS,
                y: EOF_PX_ADDRESS,
                c: Some(0),
            },
            d: 0,
            delta_t: 0,
        };
        self.bincode.serialize_into(self.stream(), &eof).unwrap();
        self.flush_writer().unwrap();
        self.stream.take()
    }

    fn flush_writer(&mut self) -> std::io::Result<()> {
        self.stream().flush()
    }

    /// Ingest an event into the codec.
    ///
    /// This will always write the event immediately to the underlying writer.
    fn ingest_event(&mut self, event: Event) -> Result<(), CodecError> {
        // NOTE: for speed, the following checks only run in debug builds. It's entirely
        // possibly to encode nonsensical events if you want to.
        debug_assert!(event.coord.x < self.meta.plane.width || event.coord.x == EOF_PX_ADDRESS);
        debug_assert!(event.coord.y < self.meta.plane.height || event.coord.y == EOF_PX_ADDRESS);

        // TODO: Switch functionality based on what the deltat mode is!

        let output_event: EventSingle;
        if self.meta.plane.channels == 1 {
            // let event_to_write = self.queue.pop()
            output_event = (&event).into();
            self.bincode.serialize_into(self.stream(), &output_event)?;
            // bincode::serialize_into(&mut *stream, &output_event, my_options).unwrap();
        } else {
            self.bincode.serialize_into(self.stream(), &event)?;
        }

        Ok(())
    }

    #[cfg(feature = "compression")]
    fn ingest_event_debug(&mut self, event: Event) -> Result<Option<Adu>, CodecError> {
        todo!()
    }
}

impl<W: Write> RawOutputInterleaved<W> {
    /// Create a new raw output stream.
    pub fn new(mut meta: CodecMetadata, writer: W) -> Self {
        let bincode = DefaultOptions::new()
            .with_fixint_encoding()
            .with_big_endian();
        meta.event_size = match meta.plane.c() {
            1 => bincode.serialized_size(&EventSingle::default()).unwrap() as u8,
            _ => bincode.serialized_size(&Event::default()).unwrap() as u8,
        };
        Self {
            meta,
            bincode,
            queue: BinaryHeap::new(),
            stream: Some(writer),
        }
    }

    fn stream(&mut self) -> &mut W {
        self.stream.as_mut().unwrap()
    }
}

impl<W: Write> WriteCompression<W> for RawOutputInterleaved<W> {
    fn magic(&self) -> Magic {
        MAGIC_RAW
    }

    fn meta(&self) -> &CodecMetadata {
        &self.meta
    }

    fn meta_mut(&mut self) -> &mut CodecMetadata {
        &mut self.meta
    }

    fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), std::io::Error> {
        // Silently ignore the returned usize because we don't care about the number of bytes
        self.stream().write(bytes).map(|_| ())
    }

    // Will always be byte-aligned. Do nothing.
    fn byte_align(&mut self) -> std::io::Result<()> {
        Ok(())
    }

    // If `self.writer` is a `BufWriter`, you'll need to flush it yourself after this.
    fn into_writer(&mut self) -> Option<W> {
        while let Some(first_item) = self.queue.pop() {
            let output_event: EventSingle;
            if self.meta.plane.channels == 1 {
                // let event_to_write = self.queue.pop()
                output_event = (&first_item).into();
                self.bincode
                    .serialize_into(self.stream(), &output_event)
                    .unwrap();
                // bincode::serialize_into(&mut *stream, &output_event, my_options).unwrap();
            } else {
                self.bincode
                    .serialize_into(self.stream(), &first_item)
                    .unwrap();
            }
        }
        let eof = Event {
            coord: Coord {
                x: EOF_PX_ADDRESS,
                y: EOF_PX_ADDRESS,
                c: Some(0),
            },
            d: 0,
            delta_t: 0,
        };
        self.bincode.serialize_into(self.stream(), &eof).unwrap();
        self.flush_writer().unwrap();
        self.stream.take()
    }

    fn flush_writer(&mut self) -> std::io::Result<()> {
        self.stream().flush()
    }

    /// Ingest an event into the codec.
    ///
    /// This will always write the event immediately to the underlying writer.
    fn ingest_event(&mut self, event: Event) -> Result<(), CodecError> {
        // NOTE: for speed, the following checks only run in debug builds. It's entirely
        // possibly to encode nonsensical events if you want to.
        debug_assert!(event.coord.x < self.meta.plane.width || event.coord.x == EOF_PX_ADDRESS);
        debug_assert!(event.coord.y < self.meta.plane.height || event.coord.y == EOF_PX_ADDRESS);

        // TODO: Switch functionality based on what the deltat mode is!

        // First, push the event to the queue
        let dt = event.delta_t;
        self.queue.push(event);

        if let Some(first_item_addr) = self.queue.peek() {
            if first_item_addr.delta_t < dt.saturating_sub(self.meta.delta_t_max) {
                if let Some(first_item) = self.queue.pop() {
                    let output_event: EventSingle;
                    if self.meta.plane.channels == 1 {
                        // let event_to_write = self.queue.pop()
                        output_event = (&first_item).into();
                        self.bincode.serialize_into(self.stream(), &output_event)?;
                        // bincode::serialize_into(&mut *stream, &output_event, my_options).unwrap();
                    } else {
                        self.bincode.serialize_into(self.stream(), &first_item)?;
                    }
                }
            }
        }

        Ok(())
    }

    #[cfg(feature = "compression")]
    fn ingest_event_debug(&mut self, event: Event) -> Result<Option<Adu>, CodecError> {
        todo!()
    }
}

impl<R: Read + Seek> Default for RawInput<R> {
    fn default() -> Self {
        Self::new()
    }
}

impl<R: Read + Seek> RawInput<R> {
    /// Create a new raw input stream.
    pub fn new() -> Self
    where
        Self: Sized,
    {
        Self {
            meta: CodecMetadata::default(),
            bincode: DefaultOptions::new()
                .with_fixint_encoding()
                .with_big_endian(),
            // stream: reader,
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<R: Read + Seek> ReadCompression<R> for RawInput<R> {
    fn magic(&self) -> Magic {
        MAGIC_RAW
    }

    fn meta(&self) -> &CodecMetadata {
        &self.meta
    }

    fn meta_mut(&mut self) -> &mut CodecMetadata {
        &mut self.meta
    }

    fn read_bytes(
        &mut self,
        bytes: &mut [u8],
        reader: &mut BitReader<R, BigEndian>,
    ) -> std::io::Result<()> {
        reader.read_bytes(bytes)
    }

    // fn into_reader(self: Box<Self>, reader: &mut BitReader<R, BigEndian>) -> R {
    //     reader.into_reader()
    // }

    #[inline]
    fn digest_event(&mut self, reader: &mut BitReader<R, BigEndian>) -> Result<Event, CodecError> {
        // TODO: Why is the encoded event size wrong?
        let mut buffer: Vec<u8> = vec![0; self.meta.event_size as usize];
        reader.read_bytes(&mut buffer)?;
        let event: Event = if self.meta.plane.channels == 1 {
            match self.bincode.deserialize_from::<_, EventSingle>(&*buffer) {
                Ok(ev) => ev.into(),
                Err(_e) => return Err(CodecError::Deserialize),
            }
        } else {
            match self.bincode.deserialize_from::<_, Event>(&*buffer) {
                Ok(ev) => ev,
                Err(e) => {
                    dbg!(self.meta.event_size);
                    eprintln!("Error deserializing event: {e}");
                    return Err(CodecError::Deserialize);
                }
            }
        };

        if event.coord.is_eof() {
            return Err(CodecError::Eof);
        }
        Ok(event)
    }

    #[cfg(feature = "compression")]
    fn digest_event_debug(
        &mut self,
        reader: &mut BitReader<R, BigEndian>,
    ) -> Result<(Option<Adu>, Event), CodecError> {
        todo!()
    }

    fn set_input_stream_position(
        &mut self,
        reader: &mut BitReader<R, BigEndian>,
        pos: u64,
    ) -> Result<(), CodecError> {
        if (pos - self.meta.header_size as u64) % u64::from(self.meta.event_size) != 0 {
            eprintln!("Attempted to seek to bad position in stream: {pos}");
            return Err(CodecError::Seek);
        }

        if reader.seek_bits(SeekFrom::Start(pos * 8)).is_err() {
            return Err(CodecError::Seek);
        }

        Ok(())
    }
}