Configurable strict BCMedia

This commit is contained in:
QuantumEntangledAndy authored and Andrew King committed 2023-02-28 12:41:04 +07:00
1 parent 17846c7bfc
commit 7fccda4aa7
11 files changed
+124 -38

No files matched your search

+1 -1
View File
@@ -246,7 +246,7 @@ impl BcCamera {
trace!("Starting Map");
let result = Discovery::map(&uid_relay).await;
if let Ok(disc) = &result {
info!("Mao success {} at {}", uid_relay, disc.get_addr());
info!("Map success {} at {}", uid_relay, disc.get_addr());
}
result
});
@@ -138,17 +138,21 @@ impl BcConnection {
}
(None, Some(occ)) => {
if occ.capacity() == 0 {
warn!("Reaching limit of channel.");
warn!("Reaching limit of channel");
warn!(
"Remaining: {} of {} message space",
"Remaining: {} of {} message space for {} (ID: {})",
occ.capacity(),
occ.max_capacity()
occ.max_capacity(),
&msg_num,
&msg_id
);
} else {
trace!(
"Remaining: {} of {} message space",
"Remaining: {} of {} message space for {} (ID: {})",
occ.capacity(),
occ.max_capacity()
occ.max_capacity(),
&msg_num,
&msg_id
);
}
if occ.send(Ok(response)).await.is_err() {
+12 -13
View File
@@ -48,9 +48,9 @@ impl<'a> Stream for BcPayloadStream<'a> {
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<IoResult<Vec<u8>>>> {
match Pin::new(&mut self.rx).poll_next(cx) {
Poll::Ready(Some(Ok(bc))) => {
match bc {
loop {
match Pin::new(&mut self.rx).poll_next(cx) {
Poll::Ready(Some(Ok(bc))) => match bc {
Bc {
body:
BcBody::ModernMsg(ModernMsg {
@@ -58,16 +58,15 @@ impl<'a> Stream for BcPayloadStream<'a> {
..
}),
..
} => Poll::Ready(Some(Ok(data))),
_ => {
cx.waker().wake_by_ref(); // Make it wake in next frame for another attempt at rx.poll_next(cx)
Poll::Pending
}
} => return Poll::Ready(Some(Ok(data))),
_ => continue,
},
Poll::Ready(Some(Err(e))) => {
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))))
}
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
}
Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e)))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
@@ -114,10 +113,10 @@ impl<'a> BcSubscription<'a> {
}
#[allow(unused)]
pub fn bcmedia_stream(&'_ mut self) -> BcMediaStream<'_> {
pub fn bcmedia_stream(&'_ mut self, strict: bool) -> BcMediaStream<'_> {
let async_read = BcPayloadStream { rx: &mut self.rx }
.into_async_read()
.compat();
FramedRead::new(async_read, BcMediaCodex::new())
FramedRead::new(async_read, BcMediaCodex::new(strict))
}
}
+4 -1
View File
@@ -66,10 +66,13 @@ impl BcCamera {
/// The buffer_size represents number of compete messages so 1 would be one complete message
/// which may be a single audio frame or a whole video key frame. If 0 a default of 100 is used
///
/// A value of scrict=true will mean that the stream will error if the underlying stream is not
/// as expected
pub async fn start_video(
&self,
stream: StreamKind,
mut buffer_size: usize,
strict: bool,
) -> Result<StreamData> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
@@ -157,7 +160,7 @@ impl BcCamera {
}
{
let mut media_sub = sub_video.bcmedia_stream();
let mut media_sub = sub_video.bcmedia_stream(strict);
while !abort_handle_thread.load(Ordering::Relaxed) {
if let Some(bc_media) = media_sub.next().await {
+36 -8
View File
@@ -4,14 +4,19 @@
//!
use crate::bcmedia::model::*;
use crate::{Error, Result};
use bytes::BytesMut;
use bytes::{Buf, BytesMut};
use log::*;
use tokio_util::codec::{Decoder, Encoder};
pub struct BcMediaCodex {}
pub struct BcMediaCodex {
/// If true we will not search for the start of the next packet
/// in the event that the stream appears to be corrupted
strict: bool,
}
impl BcMediaCodex {
pub(crate) fn new() -> Self {
Self {}
pub(crate) fn new(strict: bool) -> Self {
Self { strict }
}
}
@@ -32,10 +37,33 @@ impl Decoder for BcMediaCodex {
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
match { BcMedia::deserialize(src) } {
Ok(bc) => Ok(Some(bc)),
Err(Error::NomIncomplete(_)) => Ok(None),
Err(e) => Err(e),
let mut amount_skipped: usize = 0;
loop {
match { BcMedia::deserialize(src) } {
Ok(bc) => {
if amount_skipped > 0 {
trace!("Amount skipped to restore stream: {}", amount_skipped);
}
return Ok(Some(bc));
}
Err(Error::NomIncomplete(_)) => {
if amount_skipped > 0 {
trace!("Amount skipped to restore stream: {}", amount_skipped);
}
return Ok(None);
}
Err(e) => {
if self.strict {
return Err(e);
} else if src.is_empty() {
return Ok(None);
} else {
src.advance(1);
amount_skipped += 1;
continue;
}
}
}
}
}
}
+47 -8
View File
@@ -1,5 +1,5 @@
/// Video streams encapsulate a stream of BcMedia
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum BcMedia {
/// Holds info on the stream
InfoV1(BcMediaInfoV1),
@@ -19,7 +19,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V1: u32 = 0x31303031;
/// The start of a BcMedia stream contains this message
/// which describes the data to follow
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct BcMediaInfoV1 {
// This is the size of the header so it's actually a fixed value
// The other messages have body size here so maybe that's why
@@ -63,7 +63,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V2: u32 = 0x32303031;
/// The start of a BcMedia stream contains this message
/// which describes the data to follow
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct BcMediaInfoV2 {
// This is the size of the header so it's actually a fixed value
// The other messages have body size here so maybe that's why
@@ -108,7 +108,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030;
pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME_LAST: u32 = 0x63643039;
/// Video Types for I/PFrame
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum VideoType {
/// H264 video data
H264,
@@ -117,7 +117,7 @@ pub enum VideoType {
}
/// This is a BcMedia video IFrame.
#[derive(Debug)]
#[derive(Clone)]
pub struct BcMediaIframe {
/// "H264", or "H265"
pub video_type: VideoType,
@@ -134,12 +134,32 @@ pub struct BcMediaIframe {
pub data: Vec<u8>,
}
impl std::fmt::Debug for BcMediaIframe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entry(&"video_type", &self.video_type)
// .entry(&"payload_size", &self.payload_size)
.entry(&"microseconds", &self.microseconds)
.entry(&"time", &self.time)
.entry(
&"data[0..10]",
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
)
.entry(
&"data[-10..-1]",
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
)
.entry(&"data.len()", &self.data.len())
.finish()
}
}
// PFrame magics include the channel number in them
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130;
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME_LAST: u32 = 0x63643139;
/// This is a BcMedia video PFrame.
#[derive(Debug)]
#[derive(Clone)]
pub struct BcMediaPframe {
/// "H264", or "H265"
pub video_type: VideoType,
@@ -153,10 +173,29 @@ pub struct BcMediaPframe {
pub data: Vec<u8>,
}
impl std::fmt::Debug for BcMediaPframe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entry(&"video_type", &self.video_type)
// .entry(&"payload_size", &self.payload_size)
.entry(&"microseconds", &self.microseconds)
.entry(
&"data[0..20]",
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
)
.entry(
&"data[-20..-1]",
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
)
.entry(&"data.len()", &self.data.len())
.finish()
}
}
pub(super) const MAGIC_HEADER_BCMEDIA_AAC: u32 = 0x62773530;
/// This contains BcMedia audio data in AAC format
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct BcMediaAac {
// Size of payload after header in bytes
// pub payload_size: u16,
@@ -171,7 +210,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM: u32 = 0x62773130;
pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM_DATA: u16 = 0x0100;
/// This contains BcMedia audio data in ADPCM format
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct BcMediaAdpcm {
// Size of payload after header in bytes
// pub payload_size: u16,
+8
View File
@@ -95,6 +95,10 @@ pub(crate) struct CameraConfig {
code = "max_encryption"
))]
pub(crate) max_encryption: String,
#[serde(default = "default_strict")]
/// If strict then the media stream will error in the event that the media packets are not as expected
pub(crate) strict: bool,
}
#[derive(Debug, Deserialize, Validate, Clone)]
@@ -207,6 +211,10 @@ fn default_pause_mode() -> String {
"none".to_string()
}
fn default_strict() -> bool {
false
}
fn default_pause() -> PauseConfig {
PauseConfig {
on_motion: default_on_motion(),
+1 -1
View File
@@ -33,7 +33,7 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
.await
.context("Failed to connect to the camera, check credentials and network")?;
let mut stream_data = camera
.start_video(StreamKind::Main, 0)
.start_video(StreamKind::Main, 0, camera_config.strict)
.await
.context("Failed to start video")?;
+1
View File
@@ -129,6 +129,7 @@ impl RtspCamera {
rtsp,
permitted_users,
max_encryption,
strict: config.strict,
};
let mut state: Connected = Default::default();
+1
View File
@@ -26,6 +26,7 @@ pub(crate) struct Shared {
pub(super) permitted_users: HashSet<String>,
pub(super) pause: PauseConfig,
pub(super) max_encryption: MaxEncryption,
pub(super) strict: bool,
}
impl Shared {
+4 -1
View File
@@ -93,8 +93,11 @@ impl CameraState for Streaming {
let output_thread = output.clone();
let stream_thead = *stream;
let strict_thread = shared.strict;
let handle = task::spawn(async move {
let mut stream_data = arc_camera.start_video(stream_thead, 0).await?;
let mut stream_data = arc_camera
.start_video(stream_thead, 0, strict_thread)
.await?;
while arc_abort_handle.is_live() {
let data = stream_data.get_data().await?;
let mut locked_output = output_thread.lock().await;