From f61fef9b32ec9429b7c5a79d27634f9fb0cd5d09 Mon Sep 17 00:00:00 2001 From: Andrew Date: Sat, 15 Apr 2023 14:30:25 +0700 Subject: [PATCH] Allow decode across EOF --- crates/core/src/bc/codex.rs | 19 +++++++++ .../src/bc_protocol/connection/udpsource.rs | 40 +++++-------------- crates/core/src/bc_protocol/stream.rs | 16 +++++++- crates/core/src/bcmedia/codex.rs | 9 +++++ src/rtsp/states/streaming.rs | 23 ++++++----- 5 files changed, 64 insertions(+), 43 deletions(-) diff --git a/crates/core/src/bc/codex.rs b/crates/core/src/bc/codex.rs index b19decb..203a143 100644 --- a/crates/core/src/bc/codex.rs +++ b/crates/core/src/bc/codex.rs @@ -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 for BcCodex { impl Decoder for BcCodex { type Item = Bc; type Error = Error; + + fn decode_eof(&mut self, buf: &mut BytesMut) -> Result> { + 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> { // trace!("Decoding: {:X?}", src); let bc = Bc::deserialize(&self.context, src); diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index f236078..a05553f 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -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>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - 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)))); } } diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index ef3f6df..6457d36 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -31,7 +31,6 @@ pub enum StreamKind { /// /// When this object is dropped the streaming is stopped pub struct StreamData { - #[allow(dead_code)] handle: Option>>, rx: Receiver>, abort_handle: Arc, @@ -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> { + 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) + } } } } diff --git a/crates/core/src/bcmedia/codex.rs b/crates/core/src/bcmedia/codex.rs index 46dadb7..b006532 100644 --- a/crates/core/src/bcmedia/codex.rs +++ b/crates/core/src/bcmedia/codex.rs @@ -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> { + match self.decode(buf)? { + Some(frame) => Ok(Some(frame)), + None => Ok(None), + } + } + fn decode(&mut self, src: &mut BytesMut) -> Result> { let mut amount_skipped: usize = 0; loop { diff --git a/src/rtsp/states/streaming.rs b/src/rtsp/states/streaming.rs index b98e12d..f6b5394 100644 --- a/src/rtsp/states/streaming.rs +++ b/src/rtsp/states/streaming.rs @@ -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 { 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 { .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?; } });