Allow decode across EOF

This commit is contained in:
Andrew committed 2023-04-16 16:08:44 +07:00
1 parent 37049f7ca4
commit f61fef9b32
5 files changed
+64 -43

No files matched your search

+19
View File
@@ -7,6 +7,7 @@ use crate::bc::model::*;
use crate::bc::xml::*;
use crate::{Credentials, Error, Result};
use bytes::BytesMut;
use std::io;
use tokio_util::codec::{Decoder, Encoder};
pub(crate) struct BcCodex {
@@ -45,6 +46,24 @@ impl Encoder<Bc> for BcCodex {
impl Decoder for BcCodex {
type Item = Bc;
type Error = Error;
fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> {
match self.decode(buf)? {
Some(frame) => Ok(Some(frame)),
None => {
if buf.is_empty() {
Ok(None)
} else {
Err(io::Error::new(
io::ErrorKind::Other,
format!("bytes remaining on BC stream: {:X?}", buf),
)
.into())
}
}
}
}
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
// trace!("Decoding: {:X?}", src);
let bc = Bc::deserialize(&self.context, src);
@@ -277,14 +277,12 @@ impl UdpPayloadSource {
fn maintanence(&mut self, cx: &mut Context<'_>) {
// Check for periodic resends
if self.resend_interval.poll_tick(cx).is_ready() {
trace!("UDPSource.RecievedPacket: Resend");
for (_, resend) in self.sent.iter() {
self.send_buffer.push_back(BcUdp::Data(resend.clone()));
}
}
if self.ack_interval.poll_tick(cx).is_ready() {
let ack = BcUdp::Ack(self.build_send_ack());
trace!("UDPSource.RecievedPacket: QueueingAck");
self.send_buffer.push_back(ack);
self.state = State::Flushing;
}
@@ -295,15 +293,12 @@ impl Stream for UdpPayloadSource {
type Item = IoResult<Vec<u8>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
trace!("UdpPayloadSource.poll_next");
let camera_addr = self.inner.addr;
let mut this = self.get_mut();
match this.state {
State::Normal => {
trace!("UdpPayloadSource.State: Normal");
// Data ready to go
if let Some(payload) = this.recieved.remove(&this.packets_want) {
trace!("UdpPayloadSource.Data: PreReady: {}", this.packets_want);
this.packets_want += 1;
// error!("packets_want: {}", this.packets_want);
return Poll::Ready(Some(Ok(payload)));
@@ -324,20 +319,12 @@ impl Stream for UdpPayloadSource {
&& packet_id >= this.packets_want =>
{
if packet_id == this.packets_want {
trace!(
"UdpPayloadSource.RecievedPacker: NewData: {}",
this.packets_want
);
this.packets_want += 1;
// error!("packets_want: {}", this.packets_want);
let ack = BcUdp::Ack(this.build_send_ack());
this.send_buffer.push_back(ack);
return Poll::Ready(Some(Ok(payload)));
} else {
trace!(
"UdpPayloadSource.RecievedPacker: Future Data: {}",
packet_id
);
this.recieved.insert(packet_id, payload);
}
}
@@ -358,17 +345,14 @@ impl Stream for UdpPayloadSource {
BcUdp::Ack(ack @ UdpAck { connection_id, .. }),
addr,
)))) if connection_id == this.client_id && addr == camera_addr => {
trace!("UdpPayloadSource.RecievedPacket: Ack: {:?}", ack);
this.handle_ack(ack);
// Rather then immediatly flush wait for the next call
// this.state = State::Flushing;
}
Poll::Ready(Some(Err(e))) => {
trace!("UdpPayloadSource.RecievedPacker: Error");
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))));
}
Poll::Ready(None) => {
trace!("UdpPayloadSource.RecievedPacker: Empty");
return Poll::Ready(None);
}
Poll::Pending => {
@@ -386,22 +370,18 @@ impl Stream for UdpPayloadSource {
// }
}
}
State::Flushing => {
trace!("UdpPayloadSource.State: Flushing");
match this.poll_flush_unpin(cx) {
Poll::Ready(Ok(())) => {
this.state = State::Normal;
}
Poll::Ready(Err(e)) => {
return Poll::Ready(Some(Err(e)));
}
Poll::Pending => {
return Poll::Pending;
}
State::Flushing => match this.poll_flush_unpin(cx) {
Poll::Ready(Ok(())) => {
this.state = State::Normal;
}
}
Poll::Ready(Err(e)) => {
return Poll::Ready(Some(Err(e)));
}
Poll::Pending => {
return Poll::Pending;
}
},
State::Closed => {
trace!("UdpPayloadSource.State: Closed");
return Poll::Ready(Some(Err(IoError::from(ErrorKind::ConnectionAborted))));
}
}
+14 -2
View File
@@ -31,7 +31,6 @@ pub enum StreamKind {
///
/// When this object is dropped the streaming is stopped
pub struct StreamData {
#[allow(dead_code)]
handle: Option<JoinHandle<Result<()>>>,
rx: Receiver<Result<BcMedia>>,
abort_handle: Arc<AtomicBool>,
@@ -41,9 +40,22 @@ impl StreamData {
/// Pull data from the camera's buffer
/// This returns raw BcMedia packets
pub async fn get_data(&mut self) -> Result<Result<BcMedia>> {
if let Some(handle) = self.handle.as_mut() {
if handle.is_finished() {
self.abort_handle.store(true, Ordering::Relaxed);
handle.await??;
return Err(Error::DroppedConnection);
}
} else {
self.abort_handle.store(true, Ordering::Relaxed);
return Err(Error::DroppedConnection);
}
match self.rx.recv().await {
Some(data) => Ok(data),
None => Err(Error::DroppedConnection),
None => {
self.abort_handle.store(true, Ordering::Relaxed);
Err(Error::DroppedConnection)
}
}
}
}
+9
View File
@@ -36,6 +36,15 @@ impl Decoder for BcMediaCodex {
type Item = BcMedia;
type Error = Error;
/// Since frames can cross EOF boundaries we overload this so it dosen't error if
/// there are bytes left on the stream
fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> {
match self.decode(buf)? {
Some(frame) => Ok(Some(frame)),
None => Ok(None),
}
}
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
let mut amount_skipped: usize = 0;
loop {
+12 -11
View File
@@ -4,6 +4,7 @@
use anyhow::{anyhow, Error, Result};
use log::*;
use neolink_core::bcmedia::model::BcMedia;
use tokio::time::{timeout, Duration};
use tokio::{sync::RwLock, task::JoinSet};
@@ -43,7 +44,7 @@ impl Camera<Streaming> {
let stream_thead = *stream;
let strict_thread = loggedin.shared.config.strict;
// let tag_thread = tag.clone();
let tag_thread = tag.clone();
let mut stream_data = loggedin
.state
.camera
@@ -51,17 +52,17 @@ impl Camera<Streaming> {
.await?;
set.spawn(async move {
loop {
// debug!("{}: BcMediaStreamRecv", &tag_thread);
debug!("{}: BcMediaStreamRecv", &tag_thread);
let data = timeout(Duration::from_secs(15), stream_data.get_data()).await??;
// match &data {
// Ok(BcMedia::InfoV1(_)) => debug!("{}: - InfoV1", &tag_thread),
// Ok(BcMedia::InfoV2(_)) => debug!("{}: - InfoV2", &tag_thread),
// Ok(BcMedia::Iframe(_)) => debug!("{}: - Iframe", &tag_thread),
// Ok(BcMedia::Pframe(_)) => debug!("{}: - Pframe", &tag_thread),
// Ok(BcMedia::Aac(_)) => debug!("{}: - Aac", &tag_thread),
// Ok(BcMedia::Adpcm(_)) => debug!("{}: - Adpcm", &tag_thread),
// Err(_) => debug!(" - Error"),
// }
match &data {
Ok(BcMedia::InfoV1(_)) => debug!("{}: - InfoV1", &tag_thread),
Ok(BcMedia::InfoV2(_)) => debug!("{}: - InfoV2", &tag_thread),
Ok(BcMedia::Iframe(_)) => debug!("{}: - Iframe", &tag_thread),
Ok(BcMedia::Pframe(_)) => debug!("{}: - Pframe", &tag_thread),
Ok(BcMedia::Aac(_)) => debug!("{}: - Aac", &tag_thread),
Ok(BcMedia::Adpcm(_)) => debug!("{}: - Adpcm", &tag_thread),
Err(_) => debug!(" - Error"),
}
sender.send(data?).await?;
}
});