Skip to content

Commit 943e57d

Browse files
ac-freemanclaude
andcommitted
Clean up dead code, fix broken bench, and trim hot-path overhead
Fix the workspace build (framed_to_adder_hd.rs bench used removed Framed/SimulProcArgs/SimulProcessor APIs from the arithmetic-coding refactor). Remove dead code surfaced by clippy: the entirely-unused d_controller module, ~390 lines of commented-out Bevy-era UI in adder-viz, unused struct fields/test helpers, and panic/todo! trait impls kept only to satisfy bounds. Fix clippy warnings (unused vars/imports, swallowed Results, a vec![x; n] pattern that silently dropped Vec capacity) and strip stray dbg!/eprintln! debug leftovers, including one firing every frame in a hot path. Performance: replace a linear D_SHIFT scan in the per-event pixel integration path with a leading_zeros()-based bit-length lookup, preallocate a 3D pixel buffer instead of growing it via nested push(), and write DVS text events directly instead of building an intermediate String per event. All existing tests pass; cargo fmt and clippy are clean. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent a881f3a commit 943e57d

33 files changed

Lines changed: 136 additions & 909 deletions

File tree

adder-codec-core/src/codec/compressed/fenwick/facade.rs

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,22 @@ const D_RESIDUAL_BYTES: usize = size_of::<DResidual>();
1111

1212
#[derive(Debug, Clone)]
1313
enum Phase {
14-
Header { bytes_remaining: usize },
14+
Header {
15+
bytes_remaining: usize,
16+
},
1517
IntraD,
1618
IntraBitshift,
17-
IntraT { bytes_remaining: usize },
18-
InterD { bytes_remaining: usize, d_buf: [u8; 2] },
19+
IntraT {
20+
bytes_remaining: usize,
21+
},
22+
InterD {
23+
bytes_remaining: usize,
24+
d_buf: [u8; 2],
25+
},
1926
InterBitshift,
20-
InterT { bytes_remaining: usize },
27+
InterT {
28+
bytes_remaining: usize,
29+
},
2130
Eof,
2231
}
2332

@@ -84,10 +93,10 @@ impl FacadeModel {
8493
let symbol = symbol.copied();
8594
let phase = std::mem::replace(&mut self.phase, Phase::Eof);
8695
let next_phase = match phase {
87-
Phase::Header { mut bytes_remaining } => {
88-
if bytes_remaining > 0 {
89-
bytes_remaining -= 1;
90-
}
96+
Phase::Header {
97+
mut bytes_remaining,
98+
} => {
99+
bytes_remaining = bytes_remaining.saturating_sub(1);
91100
Phase::Header { bytes_remaining }
92101
}
93102
Phase::IntraD => match symbol {
@@ -108,10 +117,10 @@ impl FacadeModel {
108117
},
109118
None => Phase::IntraBitshift,
110119
},
111-
Phase::IntraT { mut bytes_remaining } => {
112-
if bytes_remaining > 0 {
113-
bytes_remaining -= 1;
114-
}
120+
Phase::IntraT {
121+
mut bytes_remaining,
122+
} => {
123+
bytes_remaining = bytes_remaining.saturating_sub(1);
115124
if bytes_remaining == 0 {
116125
Phase::IntraD
117126
} else {
@@ -155,10 +164,10 @@ impl FacadeModel {
155164
},
156165
None => Phase::InterBitshift,
157166
},
158-
Phase::InterT { mut bytes_remaining } => {
159-
if bytes_remaining > 0 {
160-
bytes_remaining -= 1;
161-
}
167+
Phase::InterT {
168+
mut bytes_remaining,
169+
} => {
170+
bytes_remaining = bytes_remaining.saturating_sub(1);
162171
if bytes_remaining == 0 {
163172
Phase::InterD {
164173
bytes_remaining: D_RESIDUAL_BYTES,

adder-codec-core/src/codec/compressed/source_model/event_structure/event_adu.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,10 +170,8 @@ impl EventAdu {
170170

171171
for block_idx_y in 0..self.event_cubes.nrows() {
172172
for block_idx_x in 0..self.event_cubes.ncols() {
173-
self.event_cubes[[block_idx_y, block_idx_x]].decompress_inter(
174-
&mut decoder,
175-
&contexts,
176-
);
173+
self.event_cubes[[block_idx_y, block_idx_x]]
174+
.decompress_inter(&mut decoder, &contexts);
177175
debug_assert_eq!(
178176
self.event_cubes[[block_idx_y, block_idx_x]].start_t,
179177
self.start_t

adder-codec-core/src/codec/compressed/source_model/event_structure/event_cube.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,21 @@ impl EventCube {
5757
dt_ref: DeltaT,
5858
num_intervals: usize,
5959
) -> Self {
60-
let row: [Pixel; BLOCK_SIZE] = vec![Vec::with_capacity(num_intervals); BLOCK_SIZE]
61-
.try_into()
62-
.unwrap();
63-
let square: [[Pixel; BLOCK_SIZE]; BLOCK_SIZE] = vec![row; BLOCK_SIZE].try_into().unwrap();
64-
let lists = [square.clone(), square.clone(), square];
60+
let new_row = || -> [Pixel; BLOCK_SIZE] {
61+
(0..BLOCK_SIZE)
62+
.map(|_| Vec::with_capacity(num_intervals))
63+
.collect::<Vec<_>>()
64+
.try_into()
65+
.unwrap()
66+
};
67+
let new_square = || -> [[Pixel; BLOCK_SIZE]; BLOCK_SIZE] {
68+
(0..BLOCK_SIZE)
69+
.map(|_| new_row())
70+
.collect::<Vec<_>>()
71+
.try_into()
72+
.unwrap()
73+
};
74+
let lists = [new_square(), new_square(), new_square()];
6575

6676
Self {
6777
start_y,

adder-codec-core/src/codec/compressed/stream.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,6 @@ impl<W: Write + std::marker::Send + std::marker::Sync + 'static + 'static + 'sta
198198
// }
199199
// }
200200

201-
dbg!("compressing partial last adu");
202201
let mut temp_stream = BitWriter::endian(Vec::new(), BigEndian);
203202

204203
let parameters = *self.options.crf.get_parameters();
@@ -233,7 +232,6 @@ impl<W: Write + std::marker::Send + std::marker::Sync + 'static + 'static + 'sta
233232
std::thread::sleep(std::time::Duration::from_secs(1));
234233
}
235234

236-
dbg!("All ADUs written.");
237235
// Kill the written_bytes_tx, so that the Arc only has one reference
238236
self.written_bytes_tx = None; // This will cause the flush_bytes_queue_worker() thread to
239237
// error out from the receiver, because the communication channel is severed
@@ -400,7 +398,7 @@ impl<R: Read + Seek> ReadCompression<R> for CompressedInput<R> {
400398
let adu_bytes = reader.read_to_vec(num_bytes as usize)?;
401399

402400
// Create a temporary u8 stream to read the arithmetic-coded data from
403-
let mut adu_stream = BitReader::endian(Cursor::new(adu_bytes), BigEndian);
401+
let adu_stream = BitReader::endian(Cursor::new(adu_bytes), BigEndian);
404402

405403
// Decompress the Adu
406404
adu.decompress(adu_stream);
@@ -428,7 +426,10 @@ impl<R: Read + Seek> ReadCompression<R> for CompressedInput<R> {
428426
reader: &mut BitReader<R, BigEndian>,
429427
pos: u64,
430428
) -> Result<(), CodecError> {
431-
if pos.saturating_sub(self.meta.header_size as u64) % u64::from(self.meta.event_size) != 0 {
429+
if !pos
430+
.saturating_sub(self.meta.header_size as u64)
431+
.is_multiple_of(u64::from(self.meta.event_size))
432+
{
432433
eprintln!("Attempted to seek to bad position in stream: {pos}");
433434
return Err(CodecError::Seek);
434435
}
@@ -584,8 +585,6 @@ mod tests {
584585

585586
let output = compressed_output.into_writer().unwrap().into_inner();
586587
assert!(!output.is_empty());
587-
dbg!(counter);
588-
dbg!(output.len());
589588
// Check that the size is less than the raw events
590589
assert!((output.len() as u32) < counter * 9);
591590

adder-codec-core/src/codec/decoder.rs

Lines changed: 0 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -327,50 +327,6 @@ mod tests {
327327
writer.into_inner().unwrap()
328328
}
329329

330-
fn setup_encoded_raw_interleaved(codec_version: u8) -> Vec<u8> {
331-
let output = Vec::new();
332-
333-
let bufwriter = BufWriter::new(output);
334-
let compression = RawOutput::new(
335-
CodecMetadata {
336-
codec_version,
337-
header_size: 0,
338-
time_mode: Default::default(),
339-
plane: Default::default(),
340-
tps: 0,
341-
ref_interval: 255,
342-
delta_t_max: 255,
343-
event_size: 0,
344-
source_camera: Default::default(),
345-
adu_interval: 1,
346-
},
347-
bufwriter,
348-
);
349-
let mut encoder: Encoder<BufWriter<Vec<u8>>> = Encoder::new_raw(
350-
compression,
351-
EncoderOptions {
352-
event_drop: Default::default(),
353-
event_order: EventOrder::Interleaved,
354-
crf: Crf::new(
355-
None,
356-
PlaneSize {
357-
width: 100,
358-
height: 100,
359-
channels: 1,
360-
},
361-
),
362-
},
363-
);
364-
365-
let event = stock_event();
366-
encoder.ingest_event(event).unwrap();
367-
let mut writer = encoder.close_writer().unwrap().unwrap();
368-
369-
writer.flush().unwrap();
370-
371-
writer.into_inner().unwrap()
372-
}
373-
374330
#[cfg(feature = "compression")]
375331
fn setup_encoded_compressed(codec_version: u8) -> Vec<u8> {
376332
use crate::codec::CompressedOutput;

adder-codec-core/src/codec/encoder.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ mod tests {
452452
fn compressed() {
453453
let output = Vec::new();
454454
let bufwriter = BufWriter::new(output);
455-
let (written_bytes_tx, written_bytes_rx) = std::sync::mpsc::channel();
455+
let (written_bytes_tx, _written_bytes_rx) = std::sync::mpsc::channel();
456456

457457
let compression = CompressedOutput {
458458
meta: CodecMetadata {

adder-codec-core/src/codec/raw/stream.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -187,8 +187,10 @@ impl<R: Read + Seek> ReadCompression<R> for RawInput<R> {
187187
match self.bincode.deserialize_from::<_, Event>(&*buffer) {
188188
Ok(ev) => ev,
189189
Err(e) => {
190-
dbg!(self.meta.event_size);
191-
eprintln!("Error deserializing event: {e}");
190+
eprintln!(
191+
"Error deserializing event (event_size={}): {e}",
192+
self.meta.event_size
193+
);
192194
return Err(CodecError::Deserialize);
193195
}
194196
}
@@ -213,7 +215,7 @@ impl<R: Read + Seek> ReadCompression<R> for RawInput<R> {
213215
reader: &mut BitReader<R, BigEndian>,
214216
pos: u64,
215217
) -> Result<(), CodecError> {
216-
if (pos - self.meta.header_size as u64) % u64::from(self.meta.event_size) != 0 {
218+
if !(pos - self.meta.header_size as u64).is_multiple_of(u64::from(self.meta.event_size)) {
217219
eprintln!("Attempted to seek to bad position in stream: {pos}");
218220
return Err(CodecError::Seek);
219221
}

adder-codec-core/src/lib.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,6 @@ pub fn open_file_decoder(
477477
Err(CodecError::WrongMagic) => {
478478
#[cfg(feature = "compression")]
479479
{
480-
dbg!("Opening as compressed");
481480
bufreader = BufReader::new(File::open(file_path)?);
482481
let compression = CompressedInput::new(0, 0, 0); // TODO: temporary args. Need to refactor.
483482
bitreader = BitReader::endian(bufreader, BigEndian);
@@ -512,8 +511,8 @@ pub struct EventCoordlessRelative {
512511
}
513512

514513
impl From<EventCoordless> for f64 {
515-
fn from(val: EventCoordless) -> Self {
516-
panic!("Not implemented")
514+
fn from(_val: EventCoordless) -> Self {
515+
unreachable!("From<EventCoordless> for f64 is never called; impl exists only to satisfy a trait bound")
517516
}
518517
}
519518

@@ -538,7 +537,7 @@ impl Add<EventCoordless> for EventCoordless {
538537
type Output = EventCoordless;
539538

540539
fn add(self, _rhs: EventCoordless) -> EventCoordless {
541-
todo!()
540+
unreachable!("Add<EventCoordless> for EventCoordless is never called; impl exists only to satisfy num_traits::Zero's Add supertrait bound")
542541
}
543542
}
544543

adder-codec-rs/benches/framed_to_adder_hd.rs

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use std::path::PathBuf;
1313

1414
use adder_codec_core::TimeMode::DeltaT;
1515
use adder_codec_rs::transcoder::source::framed::Framed;
16+
use adder_codec_rs::transcoder::source::video::VideoBuilder;
1617
use adder_codec_rs::utils::viz::download_file;
1718
use std::thread::sleep;
1819
use std::time::Duration;
@@ -30,22 +31,21 @@ fn simul_proc(video_path: &str, scale: f64, thread_count: u8, _chunk_rows: usize
3031
frame_idx_start: 0,
3132
show_display: false,
3233
input_filename: video_path.to_string(),
33-
output_events_filename: "".parse().unwrap(),
34+
output_events_filename: "".to_string(),
3435
output_raw_video_filename: manifest_path_str + "/benches/run/bench_out",
3536
scale,
36-
c_thresh_pos: 0,
37-
c_thresh_neg: 0,
37+
crf: 0,
3838
thread_count, // Multithreading causes some issues in testing
3939
time_mode: "delta_t".to_string(),
40+
integration_mode: "".to_string(),
4041
};
4142
let source: Framed<BufWriter<File>> =
42-
Framed::new(args.input_filename, args.color_input, args.scale)
43+
Framed::new(args.input_filename.into(), args.color_input, args.scale)
4344
.unwrap()
4445
// TODO: chunk_rows back
4546
.frame_start(args.frame_idx_start)
4647
.unwrap()
47-
.contrast_thresholds(args.c_thresh_pos, args.c_thresh_neg)
48-
.show_display(args.show_display)
48+
.crf(args.crf)
4949
.auto_time_parameters(args.ref_time, args.delta_t_max, Some(DeltaT))
5050
.unwrap();
5151

@@ -62,20 +62,13 @@ fn simul_proc(video_path: &str, scale: f64, thread_count: u8, _chunk_rows: usize
6262
)
6363
.unwrap();
6464

65-
simul_processor.run().unwrap();
65+
simul_processor.run(args.frame_count_max).unwrap();
6666
sleep(Duration::from_secs(2));
6767

6868
let output_path = "./benches/run/bench_out";
6969
fs::remove_file(output_path).unwrap();
7070
}
7171

72-
fn bench_simul_proc_dark() {
73-
let d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
74-
let manifest_path_str = d.as_path().to_str().unwrap().to_owned();
75-
let path_str = manifest_path_str + "/tests/samples/lake_scaled_hd_crop.mp4";
76-
simul_proc(&path_str, 1.0, 1, 4);
77-
}
78-
7972
fn bench_simul_proc_drop(scale: f64, chunk_rows: usize) {
8073
let path_str = "./benches/run/drop.mp4";
8174
let video_url = "https://www.pexels.com/video/2603664/download/";

adder-codec-rs/examples/framed_video_to_adder.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
3939
)?
4040
.auto_time_parameters(255, 255 * 30, None)?;
4141

42-
let pool = rayon::ThreadPoolBuilder::new()
42+
let _pool = rayon::ThreadPoolBuilder::new()
4343
.num_threads(current_num_threads())
4444
.build()
4545
.unwrap();

0 commit comments

Comments
 (0)