reconfigure shellchat net image to use decode_png

This commit is contained in:
nworbnhoj 2022-07-27 11:37:31 +10:00
parent 7cd5ee82ce
commit 1357d39255

View file

@ -17,7 +17,7 @@ use dns::Dns; // necessary to work around https://github.com/rust-lang/rust/issu
#[cfg(feature="ditherpunk")] #[cfg(feature="ditherpunk")]
use std::str::FromStr; use std::str::FromStr;
#[cfg(feature="ditherpunk")] #[cfg(feature="ditherpunk")]
use gam::{Img, PixelType}; use gam::DecodePng;
pub struct NetCmd { pub struct NetCmd {
callback_id: Option<u32>, callback_id: Option<u32>,
@ -287,9 +287,9 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
} }
} }
} }
#[cfg(feature="ditherpunk")] #[cfg(feature="ditherpunk")]
"image" => { "image" => {
let new_limit = 2048 * 1024; let new_limit = 4096;// 2048 * 1024;
let result = xous::rsyscall(xous::SysCall::AdjustProcessLimit( let result = xous::rsyscall(xous::SysCall::AdjustProcessLimit(
xous::Limits::HeapMaximum as usize, xous::Limits::HeapMaximum as usize,
0, 0,
@ -327,7 +327,7 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
let local_guard = local_token.enter(); let local_guard = local_token.enter();
// use std::io::BufRead; // not implemented yet! // use std::io::BufRead; // not implemented yet!
if let Some(url) = tokens.next() { if let Some(mut url) = tokens.next() {
match url.split_once('/') { match url.split_once('/') {
Some((host, path)) => { Some((host, path)) => {
match TcpStream::connect((host, 80)) { match TcpStream::connect((host, 80)) {
@ -347,97 +347,68 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
log::info!("fetching response...."); log::info!("fetching response....");
// let mut reader = std::io::BufReader::new(&mut stream); // let mut reader = std::io::BufReader::new(&mut stream);
log::info!("trying to read entire response..."); log::info!("trying to read entire response...");
let mut received = Vec::<u8>::new();
received.reserve(128 * 1024); // up to 128k image size... let mut buf = Vec::<u8>::new();
let mut rx_len = 0; let mut byte = [0u8; 1];
const CHUNK: usize = 4096; let mut content_length = 0;
/* // consume the header - plucking the content-length on the way
let rx_len = match reader.read_to_end(&mut received) { const HEADER_LIMIT: usize = 20;
Ok(len) => len, let mut line_count = 0;
Err(e) => { while line_count <= HEADER_LIMIT {
log::error!("couldn't read image: {:?}", e); line_count += 1;
write!(ret, "Couldn't read image: {:?}", e).unwrap(); let mut len = buf.len();
return Ok(Some(ret)) // read a line terminated by /r/n
while (len < 2 || buf.as_slice()[(len-2)..] != [0x0d, 0x0a]) && len <= 1024 {
stream.read(&mut byte).expect("png stream read error");
buf.push(byte[0]);
len = buf.len();
} }
}; */ match len {
let mut rx_buf = [0u8; CHUNK]; 2 => {
log::info!("starting read loop"); log::info!("found end of header after {} lines.", line_count);
// stream.set_nonblocking(true).expect("couldn't set stream to nonblocking"); break;
let mut last_chunk = 0;
loop {
match stream.read(&mut rx_buf) {
Ok(len) => {
log::info!("got {} bytes", len);
received.extend_from_slice(&rx_buf[..len]);
rx_len += len;
if len == 0 {
log::info!("got 0-length read, concluding we're at an EOF...");
break;
}
if last_chunk == 0 {
last_chunk = len;
} else {
if len < last_chunk {
log::info!("heuristic termination of read loop");
break;
}
}
}, },
Err(e) => { 1024.. => {
log::info!("quitting read loop with err {:?}", e); let line = std::string::String::from_utf8_lossy(&buf);
log::warn!("header contained line > 4k {:?}", line);
break; break;
} }
_ => {},
} }
} let line = std::string::String::from_utf8_lossy(&buf);
log::info!("read {} bytes", rx_len); log::info!("{:?}", line);
if let Some(start) = find_subsequence( let l_line_split = line.to_ascii_lowercase();
&received, let l_line: Vec<&str> = l_line_split.split(':').collect();
&[0x0d, 0x0a, 0x0d, 0x0a], // this is \r\n\r\n, which indicates end of header. if l_line.len() > 1 {
) { log::info!("attr: {}, {}", l_line[0], l_line[1]);
log::info!("header is {} bytes long", start); match l_line[0] {
let header = std::string::String::from_utf8_lossy(&received[..start]); "content-length" => {
let lines = header.split("\r\n"); content_length = usize::from_str(l_line[1].trim()).unwrap_or(0);
let mut content_length = 0; log::info!("found content-length of {}", content_length);
for line in lines {
let l_line_split = line.to_ascii_lowercase();
let l_line: Vec<&str> = l_line_split.split(':').collect();
if l_line.len() > 1 {
log::info!("attr: {}, {}", l_line[0], l_line[1]);
match l_line[0] {
"content-length" => {
content_length = usize::from_str(l_line[1].trim()).unwrap_or(0);
log::info!("found content-length of {}", content_length);
break;
}
_ => {}
} }
_ => {}
} }
} };
if content_length > 0 { buf.clear();
let modals = modals::Modals::new(&env.xns).unwrap(); }
// have to add 4 to the start because the index is at the beginning of the header sequence,
// not the end of the sequence. if content_length > 0 {
log::info!("heap size: {}", heap_usage()); log::info!("heap size: {}", heap_usage());
log::info!("decoding png starting with: {:x?}", &received[start+4..start+4+64]); let mut png = DecodePng::new(stream).expect("png decode failed");
let decoder = png::Decoder::new_with_limits(&received[start+4..], png::Limits { bytes: 400 * 1024 }); const BORDER: u32 = 3;
log::info!("heap size: {}", heap_usage()); let modal_size = gam::Point::new(
let mut reader = decoder.read_info().expect("failed to read png info"); (gam::IMG_MODAL_WIDTH - 2 * BORDER) as i16,
let mut buf = vec![0; reader.output_buffer_size()]; (gam::IMG_MODAL_HEIGHT - 2 * BORDER) as i16
let info = reader.next_frame(&mut buf).expect("failed to decode png"); );
log::info!("heap size: {}", heap_usage()); let bm = gam::Bitmap::from_png(&mut png, Some(modal_size));
let (width, height) = (info.width, info.height); log::info!("heap size: {}", heap_usage());
log::info!("image is {} x {}", width, height); let modals = modals::Modals::new(&env.xns).unwrap();
log::info!("some image bytes: {:x?}", &buf[..64]); modals.show_image(bm).expect("show image modal failed");
let img = Img::new(buf, width as usize, PixelType::U8x3);
} else {
modals.show_image(&img).expect("show image modal failed"); write!(ret, "content-length was 0, no image read").unwrap();
write!(ret, "Image of {} bytes read successfully", content_length).unwrap();
} else {
write!(ret, "content-length was 0, no image read").unwrap();
}
} }
// reader.consume(received.len());
} }
Err(e) => write!(ret, "Couldn't connect to {}:80: {:?}", host, e).unwrap(), Err(e) => write!(ret, "Couldn't connect to {}:80: {:?}", host, e).unwrap(),
} }
@ -586,12 +557,6 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
} }
} }
// yep. this is from stackoverflow copypasta
#[cfg(feature="ditherpunk")]
fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|window| window == needle)
}
enum Responses { enum Responses {
Uptime, Uptime,
NotFound, NotFound,
@ -758,4 +723,4 @@ fn heap_usage() -> usize {
0 0
}, },
} }
} }