thermalcam_decoder/examples/live.rs

79 lines
2.3 KiB
Rust

use dotenv::dotenv;
use std::io::Write;
use thermaldecoder::{Header, HDR_SIZE};
use v4l::video::Output;
fn main() -> anyhow::Result<()> {
dotenv().ok();
let device = match std::env::var("THERMALCAM_IFACE=enp1s0f0") {
Ok(d) => {
let device = pcap::Device::list()
.expect("device list failed")
.into_iter()
.find(|x| x.name == d)
.expect(&format!("could not find device {}", d));
device
}
Err(_) => pcap::Device::lookup()
.expect("device lookup failed")
.expect("no device available"),
};
// get the default Device
println!("Using device {}", device.name);
let output = std::env::args()
.nth(1)
.expect("required output file argument");
println!("Using output v4l2loopback device {}", output);
const WIDTH: usize = 288;
const HEIGHT: usize = 384;
let mut out = v4l::Device::with_path(output)?;
// To find the fourcc code, use v4l2-ctl --list-formats-out /dev/video0
// (or read the source :)
let format = v4l::Format::new(
WIDTH as u32,
HEIGHT as u32,
v4l::format::FourCC::new(b"Y16 "),
);
Output::set_format(&out, &format)?;
// Setup Capture
let mut cap = pcap::Capture::from_device(device)
.unwrap()
.immediate_mode(true)
.open()
.unwrap();
// get a packet and print its bytes
const PACKET_LEN: usize = 6972;
const FRAME_LEN: usize = WIDTH * HEIGHT * 2;
let mut frame = [0u8; FRAME_LEN];
let mut len = 0;
while let Ok(p) = cap.next_packet() {
let data = p.data;
if data.len() != PACKET_LEN {
continue;
}
let data = &data[0x2a..];
let header = match Header::read(data) {
Ok(header) => header,
Err(_) => continue,
};
let data = &data[HDR_SIZE..];
if (header.part == 0 && len > 0)
// do not write out of bounds - would panic, instead just skip
|| (data.len() + len > FRAME_LEN)
{
if len == FRAME_LEN {
out.write_all(&frame[..])?;
}
len = 0;
}
frame[len..len + data.len()].copy_from_slice(data);
len += data.len();
}
Ok(())
}