Further CPU optiations

This commit is contained in:
QuantumEntangledAndy committed 2023-10-27 16:13:11 +07:00
1 parent a6c8665a98
commit 7f047efaef
4 files changed
+68 -57

No files matched your search

@@ -79,14 +79,14 @@ impl<'a> BcSubscription<'a> {
pub fn payload_stream(&'_ mut self) -> impl Stream<Item = IoResult<Vec<u8>>> + '_ {
(&mut self.rx).filter_map(|x| match x {
Ok(Bc {
meta: BcMeta { msg_id, .. },
body:
BcBody::ModernMsg(ModernMsg {
payload: Some(BcPayloads::Binary(data)),
..
}),
..
}) => {
// log::debug!("PayloadStream: Data");
log::debug!("PayloadStream got binary data: {msg_id}");
Some(Ok(data))
}
Ok(_) => None,
@@ -95,7 +95,17 @@ impl<'a> BcSubscription<'a> {
}
pub fn bcmedia_stream(&'_ mut self, strict: bool) -> impl Stream<Item = Result<BcMedia>> + '_ {
let async_read = self.payload_stream().into_async_read().compat();
FramedRead::new(async_read, BcMediaCodex::new(strict))
let async_read = self
.payload_stream()
.map(|frame| {
log::debug!("- BcMedia Payloader got packet");
frame
})
.into_async_read()
.compat();
FramedRead::new(async_read, BcMediaCodex::new(strict)).map(|frame| {
log::debug!(" - BcMedia Payloader decoded packet");
frame
})
}
}
@@ -19,7 +19,10 @@ use std::task::{Context, Poll};
use tokio::{
net::UdpSocket,
sync::mpsc::channel,
sync::{
mpsc::channel,
watch::{channel as watch, Sender as WatchSender},
},
task::JoinSet,
time::{interval, sleep, Duration, Instant, Interval},
};
@@ -287,7 +290,7 @@ impl Drop for UdpPayloadSource {
struct UdpPayloadInner {
camera_addr: SocketAddr,
ack_tx: PollSender<UdpAck>,
ack_tx: WatchSender<UdpAck>,
socket_in: PollSender<BcUdp>,
socket_out: ReceiverStream<(BcUdp, SocketAddr)>,
thread_stream: PollSender<IoResult<Vec<u8>>>,
@@ -410,8 +413,7 @@ impl UdpPayloadInner {
let ack_cancel = cancel.clone();
let mut ack_interval = interval(Duration::from_millis(10)); // Offical Client does ack every 10ms
ack_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let (ack_tx, mut ack_rx) = channel(100);
let thread_camera_id = camera_id;
let (ack_tx, ack_rx) = watch(UdpAck::empty(camera_id));
let ack_socket_in_tx = socket_in_tx.clone();
set.spawn(async move {
tokio::select! {
@@ -419,26 +421,12 @@ impl UdpPayloadInner {
Result::Ok(())
},
v = async {
let mut ack_packet = UdpAck::empty(thread_camera_id);
loop {
tokio::select! {
v = ack_rx.recv() => {
// Update the ACK packet
if let Some(v) = v {
ack_packet = v;
Ok(())
} else {
log::trace!("ack_rx.recv() Error::DroppedConnection");
Err(Error::DroppedConnection)
}
},
_ = ack_interval.tick() => {
// Send an ack packet
log::trace!("send ack");
ack_socket_in_tx.send(BcUdp::Ack(ack_packet.clone())).await?;
Ok(())
}
}?;
ack_interval.tick().await;
// Send an ack packet
log::trace!("send ack");
let ack_packet = BcUdp::Ack(ack_rx.borrow().clone());
ack_socket_in_tx.send(ack_packet).await?;
}
} => v,
}
@@ -479,7 +467,7 @@ impl UdpPayloadInner {
Self {
camera_addr,
ack_tx: PollSender::new(ack_tx),
ack_tx,
socket_in: PollSender::new(socket_in_tx),
socket_out: ReceiverStream::new(socket_out_rx),
thread_stream,
@@ -504,7 +492,7 @@ impl UdpPayloadInner {
for (_, resend) in self.sent.iter() {
self.socket_in.feed(BcUdp::Data(resend.clone())).await?;
}
self.ack_tx.feed(self.build_send_ack()).await?; // Ensure we update the ack packet sometimes too
self.ack_tx.send_replace(self.build_send_ack()); // Ensure we update the ack packet sometimes too
Result::Ok(())
},
v = self.thread_sink.next() => {
@@ -550,7 +538,7 @@ impl UdpPayloadInner {
if packet_id >= self.packets_want {
// error!("packets_want: {}", this.packets_want);
self.recieved.insert(packet_id, data.payload);
self.ack_tx.feed(self.build_send_ack()).await?;
self.ack_tx.send_replace(self.build_send_ack());
}
}
},
@@ -569,7 +557,6 @@ impl UdpPayloadInner {
log::trace!("Flush");
self.socket_in.flush().await?;
self.thread_stream.flush().await?;
self.ack_tx.flush().await?;
log::trace!("Flushed");
Ok(())
}
+1 -1
View File
@@ -228,7 +228,7 @@ local function hexencode(str)
end
local gcrypt = require("luagcrypt")
local function aes_decrypt(data)
local raw_key = _G.nonce .. "-" .. bc_protocol.prefs.key
local raw_key = (_G.nonce or "") .. "-" .. bc_protocol.prefs.key
local iv = "0123456789abcdef"
local hasher = gcrypt.Hash(gcrypt.MD_MD5)
hasher:write(raw_key)
+39 -25
View File
@@ -14,7 +14,7 @@ use tokio::{
channel as broadcast, Receiver as BroadcastReceiver, Sender as BroadcastSender,
},
mpsc::{channel as mpsc, Receiver as MpscReceiver},
oneshot::Sender as OneshotSender,
oneshot::{channel as oneshot, Sender as OneshotSender},
watch::{channel as watch, Receiver as WatchReceiver, Sender as WatchSender},
},
task::JoinHandle,
@@ -402,6 +402,36 @@ impl StreamData {
v = async {
loop {
let (watchdog_tx, mut watchdog_rx) = mpsc(1);
let (watchdog_eat_tx, watchdog_eat_rx) = oneshot();
// Give the watchdog his own thread to play in
//
// This should stop one branch of the select from waking the other
// too often
let watchdog_print_name = print_name.clone();
tokio::task::spawn(async move {
let mut check_timeout = timeout(Duration::from_secs(15), watchdog_rx.recv()).await; // Wait longer for the first feed
loop {
match check_timeout {
Err(_) => {
// Timeout
// Break with Ok to trigger the restart
log::debug!("{watchdog_print_name}: Watchdog kicking the stream");
break;
},
Ok(None) => {
log::debug!("{watchdog_print_name}: Watchdog dropped the stream");
break;
}
Ok(_) => {
// log::debug!("{print_name}: Good Doggo");
check_timeout = timeout(Duration::from_secs(10), watchdog_rx.recv()).await;
}
}
}
// Watch dog is hungry send the kill to the stream thread
let _ = watchdog_eat_tx.send(());
}) ;
tokio::select! {
v = thread_inuse.dropped_users() => {
// Handles the stop and restart when no active users
@@ -413,29 +443,10 @@ impl StreamData {
log::debug!("{print_name}: Streaming START");
AnyResult::Ok(())
},
v = async {
let mut check_timeout = timeout(Duration::from_secs(15), watchdog_rx.recv()).await; // Wait longer for the first feed
loop {
match check_timeout {
Err(_) => {
// Timeout
// Break with Ok to trigger the restart
log::debug!("{print_name}: Watchdog kicking the stream");
sleep(Duration::from_secs(1)).await;
break AnyResult::Ok(());
},
Ok(None) => {
log::debug!("{print_name}: Watchdog dropped the stream");
sleep(Duration::from_secs(1)).await;
break AnyResult::Ok(());
}
Ok(_) => {
// log::debug!("{print_name}: Good Doggo");
check_timeout = timeout(Duration::from_secs(4), watchdog_rx.recv()).await;
}
}
}
} => v,
_ = watchdog_eat_rx => {
sleep(Duration::from_secs(1)).await;
AnyResult::Ok(())
},
result = instance.run_passive_task(|camera| {
let vid_tx = vid.clone();
let aud_tx = aud.clone();
@@ -444,6 +455,7 @@ impl StreamData {
let aud_history = aud_history.clone();
let watchdog_tx = watchdog_tx.clone();
let fps_table = fps_table.clone();
let print_name = print_name.clone();
log::debug!("{print_name}: Running Stream Instance Task");
Box::pin(async move {
@@ -456,9 +468,11 @@ impl StreamData {
let mut prev_ts = Duration::ZERO;
let mut stream_data = camera.start_video(name, 0, strict).await?;
loop {
watchdog_tx.send(()).await?; // Feed the watchdog
log::debug!("{print_name}: Waiting for frame");
let data = stream_data.get_data().await??;
log::debug!("{print_name}: Waiting for Watchdog");
watchdog_tx.send(()).await?; // Feed the watchdog
log::debug!("{print_name}: Got frame");
// Update the stream config with any information
match &data {