Use reactor for rtsp

This commit is contained in:
QuantumEntangledAndy committed 2023-09-03 09:57:19 +07:00
1 parent 1da4472ca8
commit 71e9830643
17 files changed
+846 -657

No files matched your search

Generated
+1 -46
View File
@@ -109,17 +109,6 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9"
[[package]]
name = "async-channel"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35"
dependencies = [
"concurrent-queue",
"event-listener",
"futures-core",
]
[[package]]
name = "async-trait"
version = "0.1.72"
@@ -349,15 +338,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
[[package]]
name = "concurrent-queue"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62ec6771ecfa0762d24683ee5a32ad78487a3d3afdc0fb8cae19d2c5deb50b7c"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "console-api"
version = "0.5.0"
@@ -565,12 +545,6 @@ dependencies = [
"libc",
]
[[package]]
name = "event-listener"
version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]]
name = "fastrand"
version = "2.0.0"
@@ -1264,12 +1238,6 @@ dependencies = [
"windows-sys",
]
[[package]]
name = "is_sorted"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357376465c37db3372ef6a00585d336ed3d0f11d4345eef77ebcb05865392b21"
[[package]]
name = "itertools"
version = "0.10.5"
@@ -1279,15 +1247,6 @@ dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.9"
@@ -1454,7 +1413,6 @@ name = "neolink"
version = "0.5.18"
dependencies = [
"anyhow",
"async-channel",
"base64 0.21.2",
"byte-slice-cast",
"clap",
@@ -1467,8 +1425,6 @@ dependencies = [
"gstreamer-rtsp",
"gstreamer-rtsp-server",
"heck",
"is_sorted",
"itertools 0.11.0",
"lazy_static",
"log",
"neolink_core",
@@ -1476,7 +1432,6 @@ dependencies = [
"rumqttc",
"serde",
"serde_json",
"time",
"tokio",
"tokio-stream",
"tokio-util",
@@ -1767,7 +1722,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4"
dependencies = [
"anyhow",
"itertools 0.10.5",
"itertools",
"proc-macro2",
"quote",
"syn 1.0.109",
-4
View File
@@ -13,7 +13,6 @@ members = [
[dependencies]
anyhow = "1.0.70"
async-channel = "1.9.0"
base64 = "0.21.2"
byte-slice-cast = "1.2.2"
clap = { version = "4.2.2", features = ["derive", "cargo"] }
@@ -26,8 +25,6 @@ gstreamer-app = "0.20.0"
gstreamer-rtsp = "0.20.0"
gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] }
heck = "0.4.1"
is_sorted = "0.1.1"
itertools = "0.11.0"
lazy_static = "1.4.0"
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
neolink_core = { path = "crates/core", version = "0.5.18" }
@@ -35,7 +32,6 @@ regex = "1.7.3"
rumqttc = "0.22.0"
serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"
time = "0.3.20"
tokio = { version = "1.27.0", features = ["rt-multi-thread", "macros", "io-util", "tracing"] }
tokio-stream = "0.1.12"
tokio-util = { version = "0.7.7", features = ["full", "tracing"] }
+2
View File
@@ -259,6 +259,7 @@ impl BcCamera {
}, if allow_remote => Ok(v),
Ok(v) = async {
let uid_map = uid.clone();
tokio::time::sleep(tokio::time::Duration::from_millis(250)).await;
info!("{}: Trying map discovery", options.name);
let result = discovery.map(&reg_result).await;
match result {
@@ -276,6 +277,7 @@ impl BcCamera {
}, if allow_map => Ok(v),
Ok(v) = async {
let uid_relay = uid.clone();
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
info!("{}: Trying relay discovery", options.name);
let result = discovery.relay(&reg_result).await;
match result {
@@ -59,6 +59,7 @@ impl BcConnection {
let thread_cancel = cancel.clone();
let handle = tokio::task::spawn_blocking(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let result = runtime.block_on(async move {
@@ -26,7 +26,7 @@ use tokio::{
net::UdpSocket,
sync::{
mpsc::{channel, Receiver, Sender},
RwLock,
RwLock, Semaphore,
},
task::JoinSet,
time::{interval, timeout, Duration},
@@ -83,14 +83,18 @@ lazy_static! {
];
/// Maximum wait for a reply
static ref MAXIMUM_WAIT: Duration = Duration::from_secs(15);
/// Wait for tcp connections
static ref TCP_WAIT: Duration = Duration::from_secs(4);
/// How long to wait before resending
static ref RESEND_WAIT: Duration = Duration::from_millis(500);
}
type Subscriber = Arc<RwLock<BTreeMap<u32, Sender<Result<(UdpDiscovery, SocketAddr)>>>>>;
type Handlers = Arc<RwLock<Vec<Sender<Result<(UdpDiscovery, SocketAddr)>>>>>;
type ArcFramedSocket = UdpFramed<BcUdpCodex, Arc<UdpSocket>>;
pub(crate) struct Discoverer {
semaphore: Arc<Semaphore>,
socket: Arc<UdpSocket>,
handle: RwLock<JoinSet<()>>,
writer: Sender<Result<(BcUdp, SocketAddr)>>,
@@ -172,6 +176,7 @@ impl Discoverer {
});
Ok(Discoverer {
semaphore: Arc::new(Semaphore::new(1)),
socket,
handle: RwLock::new(set),
writer: sinker,
@@ -619,6 +624,12 @@ impl Discoverer {
},
};
let permit = self
.semaphore
.clone()
.acquire_owned()
.await
.map_err(|_| Error::Other("Discovery already complete"))?;
// Send and await confirm
self.retry_send(msg, addr, |bc, _| {
trace!("msg: {:?}", &bc);
@@ -675,6 +686,8 @@ impl Discoverer {
self.keep_alive_device(local_tid, &result).await;
self.semaphore.close();
drop(permit);
Ok(result)
}
@@ -736,6 +749,12 @@ impl Discoverer {
},
};
let permit = self
.semaphore
.clone()
.acquire_owned()
.await
.map_err(|_| Error::Other("Discovery already complete"))?;
// Send and await confirm
self.retry_send(msg, addr, |bc, _| {
trace!("msg: {:?}", &bc);
@@ -792,6 +811,8 @@ impl Discoverer {
self.keep_alive_device(local_tid, &result).await;
self.semaphore.close();
drop(permit);
Ok(result)
}
@@ -838,6 +859,12 @@ impl Discoverer {
camera_id: local_did,
};
let permit = self
.semaphore
.clone()
.acquire_owned()
.await
.map_err(|_| Error::Other("Discovery already complete"))?;
// Confirm local to register
let msg = UdpDiscovery {
tid: 0,
@@ -857,6 +884,8 @@ impl Discoverer {
self.keep_alive_device(tid, &result).await;
self.semaphore.close();
drop(permit);
Ok(result)
}
@@ -880,6 +909,12 @@ impl Discoverer {
},
};
let permit = self
.semaphore
.clone()
.acquire_owned()
.await
.map_err(|_| Error::Other("Discovery already complete"))?;
let (final_addr, local_did) = self
.retry_send(msg, relay_addr, |bc, addr| match bc {
UdpDiscovery {
@@ -933,6 +968,8 @@ impl Discoverer {
self.keep_alive_device(tid, &result).await;
// self.keep_alive_relay(tid, &result).await;
self.semaphore.close();
drop(permit);
Ok(result)
}
@@ -1048,11 +1085,8 @@ impl Discovery {
pub(crate) async fn check_tcp(&self, addr: SocketAddr, channel_id: u8) -> Result<()> {
let username = "admin";
let password = Some("123456");
let mut tcp_source = timeout(
*MAXIMUM_WAIT,
TcpSource::new(addr, username, password, false),
)
.await??;
let mut tcp_source =
timeout(*TCP_WAIT, TcpSource::new(addr, username, password, false)).await??;
let md5_username = md5_string(username, Md5Trunc::ZeroLast);
let md5_password = password
@@ -1076,7 +1110,7 @@ impl Discovery {
})
.await?;
let _bc: Bc = timeout(*MAXIMUM_WAIT, tcp_source.next())
let _bc: Bc = timeout(*TCP_WAIT, tcp_source.next())
.await?
.ok_or(Error::CannotInitCamera)??; // Successful recv should mean a Bc packet if not then deser will fail
Ok(())
@@ -322,6 +322,7 @@ impl UdpPayloadInner {
let thread_camera_addr = camera_addr;
tokio::task::spawn_blocking(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async move {
@@ -350,6 +351,7 @@ impl UdpPayloadInner {
let mut ack_socket_in_tx = PollSender::new(socket_in_tx.clone());
tokio::task::spawn_blocking(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async move {
@@ -388,6 +390,7 @@ impl UdpPayloadInner {
let mut socket_out_tx = PollSender::new(socket_out_tx);
tokio::task::spawn_blocking(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
@@ -591,6 +594,7 @@ impl UdpPayloadSource {
let thread_cancel_token = cancel_token.clone();
let handle = tokio::task::spawn_blocking(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
+5 -6
View File
@@ -22,14 +22,13 @@ pub enum StreamKind {
Extern,
}
impl StreamKind {
pub fn to_string(&self) -> String {
impl std::fmt::Display for StreamKind {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
StreamKind::Main => "mainStream",
StreamKind::Sub => "subStream",
StreamKind::Extern => "externStream",
StreamKind::Main => write!(f, "mainStream"),
StreamKind::Sub => write!(f, "subStream"),
StreamKind::Extern => write!(f, "externStream"),
}
.to_string()
}
}
@@ -0,0 +1,50 @@
use super::{BcCamera, Error, Result};
use crate::bc::{model::*, xml::*};
impl BcCamera {
/// Get the [StreamInfoList] xml which contains the supported camera streams
pub async fn get_stream_info(&self) -> Result<StreamInfoList> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection
.subscribe(MSG_ID_STREAM_INFO_LIST, msg_num)
.await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_STREAM_INFO_LIST,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: None,
payload: None,
}),
};
sub_get.send(get).await?;
let msg = sub_get.recv().await?;
if msg.meta.response_code != 200 {
return Err(Error::CameraServiceUnavaliable);
}
if let BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
stream_info_list: Some(data),
..
})),
..
}) = msg.body
{
Ok(data)
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected StreamInfoList xml but it was not recieved",
})
}
}
}
+3
View File
@@ -130,6 +130,7 @@ impl NeoInstance {
Ok(instance_rx.await?)
}
#[allow(dead_code)]
pub(crate) async fn low_stream(&self) -> Result<Option<StreamInstance>> {
let (instance_tx, instance_rx) = oneshot();
self.camera_control
@@ -138,6 +139,7 @@ impl NeoInstance {
Ok(instance_rx.await?)
}
#[allow(dead_code)]
pub(crate) async fn high_stream(&self) -> Result<Option<StreamInstance>> {
let (instance_tx, instance_rx) = oneshot();
self.camera_control
@@ -146,6 +148,7 @@ impl NeoInstance {
Ok(instance_rx.await?)
}
#[allow(dead_code)]
pub(crate) async fn streams(&self) -> Result<Vec<StreamInstance>> {
let (instance_tx, instance_rx) = oneshot();
self.camera_control
+2 -1
View File
@@ -11,13 +11,14 @@ use tokio::sync::{
oneshot::{channel as oneshot, Sender as OneshotSender},
watch::{channel as watch, Receiver as WatchReceiver, Sender as WatchSender},
};
use tokio_stream::wrappers::{BroadcastStream, ReceiverStream};
use tokio_stream::wrappers::ReceiverStream;
use tokio_util::sync::CancellationToken;
use super::{NeoCamStreamThread, NeoCamThread, NeoInstance, StreamInstance, StreamRequest};
use crate::{config::CameraConfig, AnyResult, Result};
use neolink_core::bc_protocol::{BcCamera, StreamKind};
#[allow(dead_code)]
pub(crate) enum NeoCamCommand {
HangUp,
Instance(OneshotSender<Result<NeoInstance>>),
+3 -2
View File
@@ -161,10 +161,10 @@ impl NeoCamStreamThread {
sender
} => {
let config = self.instance.config().await?.borrow_and_update().clone();
let streams = config.stream.to_stream_kinds();
let streams = config.stream.as_stream_kinds();
for stream in streams.iter().copied() {
if let Entry::Vacant(vac) = self.streams.entry(stream) {
let (tx, rx) = broadcast(1000);
let (tx, _) = broadcast(1000);
vac.insert(
StreamData::new(tx, stream, self.instance.subscribe().await?, config.strict)
.await?,
@@ -207,6 +207,7 @@ impl Drop for NeoCamStreamThread {
/// The kind of stream we want a async broadcast of
pub(crate) enum StreamRequest {
#[allow(dead_code)]
/// Get a currently loaded stream
Get {
name: StreamKind,
+1 -8
View File
@@ -91,7 +91,7 @@ pub(crate) enum StreamConfig {
}
impl StreamConfig {
pub(crate) fn to_stream_kinds(&self) -> Vec<StreamKind> {
pub(crate) fn as_stream_kinds(&self) -> Vec<StreamKind> {
match self {
StreamConfig::All => {
vec![StreamKind::Main, StreamKind::Extern, StreamKind::Sub]
@@ -176,13 +176,6 @@ pub(crate) struct CameraConfig {
#[serde(default = "default_buffer_size", alias = "size", alias = "buffer")]
pub(crate) buffer_size: usize,
#[serde(
default = "default_smoothing",
alias = "smoothing",
alias = "stretching"
)]
pub(crate) use_smoothing: bool,
#[serde(default = "default_true", alias = "splash")]
pub(crate) use_splash: bool,
+3 -2
View File
@@ -39,7 +39,7 @@ pub(crate) async fn main(opt: Opt, config: Config, reactor: NeoReactor) -> Resul
let camera = reactor.get_or_insert(config.clone()).await?;
if opt.use_stream {
let mut stream_data = camera
let stream_data = camera
.stream(StreamKind::Main)
.await
.context("Failed to start video")?;
@@ -47,7 +47,8 @@ pub(crate) async fn main(opt: Opt, config: Config, reactor: NeoReactor) -> Resul
// Get one iframe at the start while also getting the the video type
let buf;
let vid_type;
let mut stream = BroadcastStream::new(stream_data.stream.resubscribe());
let mut stream = BroadcastStream::new(stream_data.stream.resubscribe())
.filter(|f| futures::future::ready(f.is_ok())); // Filter to ignore lagged
loop {
if let Some(Ok(BcMedia::Iframe(frame))) = stream.next().await {
vid_type = frame.video_type;
+4 -65
View File
@@ -4,19 +4,13 @@
//! expect issues
use super::AnyResult;
use crate::common::{AudFormat, NeoReactor, StreamInstance, VidFormat};
use anyhow::{anyhow, Context};
use async_channel::{Receiver as AsyncReceiver, Sender as AsyncSender};
use futures::stream::StreamExt;
use gstreamer::glib::object_subclass;
use gstreamer::glib::subclass::types::ObjectSubclass;
use gstreamer::Element;
use gstreamer::{
glib::{self, Object},
prelude::*,
ClockTime, Structure,
Structure,
};
use gstreamer::{Bin, Caps, Element, ElementFactory};
use gstreamer_app::{AppSrc, AppSrcCallbacks, AppStreamType};
use gstreamer_rtsp::RTSPUrl;
use gstreamer_rtsp_server::prelude::*;
use gstreamer_rtsp_server::subclass::prelude::*;
@@ -24,21 +18,9 @@ use gstreamer_rtsp_server::RTSPMediaFactory;
use gstreamer_rtsp_server::{RTSPSuspendMode, RTSPTransportMode};
use gstreamer_rtsp_server::{RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT};
use log::*;
use neolink_core::{bc_protocol::StreamKind, bcmedia::model::*};
use std::collections::HashSet;
use std::convert::TryInto;
use std::sync::Arc;
use tokio::{
sync::{
mpsc::{channel as mpsc, Sender as MpscSender},
oneshot::{channel as oneshot, Receiver as OneshotReceiver, Sender as OneshotSender},
Mutex, RwLock,
},
task::JoinSet,
time::Duration,
};
use tokio_stream::wrappers::ReceiverStream;
use tokio_util::sync::CancellationToken;
use tokio::sync::Mutex;
glib::wrapper! {
/// The wrapped RTSPMediaFactory
@@ -112,6 +94,7 @@ unsafe impl Send for NeoMediaFactory {}
unsafe impl Sync for NeoMediaFactory {}
pub(crate) struct NeoMediaFactoryImpl {
#[allow(clippy::type_complexity)]
call_back: Arc<Mutex<Option<Arc<dyn Fn(Element) -> AnyResult<Option<Element>> + Send + Sync>>>>,
}
@@ -154,47 +137,3 @@ impl ObjectSubclass for NeoMediaFactoryImpl {
type Type = super::NeoMediaFactory;
type ParentType = RTSPMediaFactory;
}
// Convenice funcion to make an element or provide a message
// about what plugin is missing
fn make_element(kind: &str, name: &str) -> AnyResult<Element> {
ElementFactory::make_with_name(kind, Some(name)).with_context(|| {
let plugin = match kind {
"appsrc" => "app (gst-plugins-base)",
"audioconvert" => "audioconvert (gst-plugins-base)",
"adpcmdec" => "Required for audio",
"h264parse" => "videoparsersbad (gst-plugins-bad)",
"h265parse" => "videoparsersbad (gst-plugins-bad)",
"rtph264pay" => "rtp (gst-plugins-good)",
"rtph265pay" => "rtp (gst-plugins-good)",
"aacparse" => "audioparsers (gst-plugins-good)",
"rtpL16pay" => "rtp (gst-plugins-good)",
"x264enc" => "x264 (gst-plugins-ugly)",
"x265enc" => "x265 (gst-plugins-bad)",
"avdec_h264" => "libav (gst-libav)",
"avdec_h265" => "libav (gst-libav)",
"videotestsrc" => "videotestsrc (gst-plugins-base)",
"imagefreeze" => "imagefreeze (gst-plugins-good)",
"audiotestsrc" => "audiotestsrc (gst-plugins-base)",
"decodebin" => "playback (gst-plugins-good)",
_ => "Unknown",
};
format!(
"Missing required gstreamer plugin `{}` for `{}` element",
plugin, kind
)
})
}
fn make_queue(name: &str) -> AnyResult<Element> {
let queue = make_element("queue", name)?;
queue.set_property_from_str("leaky", "downstream");
queue.set_property("max-size-bytes", 0u32);
queue.set_property("max-size-buffers", 0u32);
queue.set_property(
"max-size-time",
std::convert::TryInto::<u64>::try_into(tokio::time::Duration::from_secs(5).as_nanos())
.unwrap_or(0),
);
Ok(queue)
}
+5 -37
View File
@@ -3,26 +3,22 @@
//! We are now messing with gstreamer glib objects
//! expect issues
use super::{factory::*, AnyResult};
use super::AnyResult;
use crate::config::*;
use anyhow::{anyhow, Context};
use anyhow::Context;
use gstreamer::glib::{self, object_subclass, subclass::types::ObjectSubclass, MainLoop, Object};
use gstreamer_rtsp::RTSPAuthMethod;
use gstreamer_rtsp_server::{
gio::{TlsAuthenticationMode, TlsCertificate},
prelude::*,
subclass::prelude::*,
RTSPAuth, RTSPFilterResult, RTSPServer, RTSPToken, RTSP_TOKEN_MEDIA_FACTORY_ROLE,
RTSPAuth, RTSPServer, RTSPToken, RTSP_TOKEN_MEDIA_FACTORY_ROLE,
};
use log::*;
use std::{
collections::{hash_map::Entry, HashMap, HashSet},
fs,
sync::Arc,
};
use std::{fs, sync::Arc};
use tokio::{
sync::{mpsc::Sender, RwLock},
sync::RwLock,
task::JoinSet,
time::{timeout, Duration},
};
@@ -45,14 +41,6 @@ impl NeoRtspServer {
Ok(factory)
}
pub(crate) async fn add_permitted_roles<T: Into<String>, U: AsRef<str>>(
&self,
tag: T,
permitted_users: &HashSet<U>,
) -> AnyResult<()> {
self.imp().add_permitted_roles(tag, permitted_users).await
}
pub(crate) async fn run(&self, bind_addr: &str, bind_port: u16) -> AnyResult<()> {
let server = self;
server.set_address(bind_addr);
@@ -104,14 +92,8 @@ impl NeoRtspServer {
unsafe impl Send for NeoRtspServer {}
unsafe impl Sync for NeoRtspServer {}
struct FactoryData {
factory: NeoMediaFactory,
paths: HashSet<String>,
}
#[derive(Default)]
pub(crate) struct NeoRtspServerImpl {
medias: RwLock<HashMap<String, FactoryData>>,
threads: RwLock<JoinSet<AnyResult<()>>>,
main_loop: RwLock<Option<Arc<MainLoop>>>,
}
@@ -127,20 +109,6 @@ impl ObjectSubclass for NeoRtspServerImpl {
}
impl NeoRtspServerImpl {
pub(crate) async fn add_permitted_roles<T: Into<String>, U: AsRef<str>>(
&self,
tag: T,
permitted_users: &HashSet<U>,
) -> AnyResult<()> {
let tag: String = tag.into();
if let Some(media) = self.medias.write().await.get_mut(&tag) {
media.factory.add_permitted_roles(permitted_users);
Ok(())
} else {
Err(anyhow!("No media with tag {} to add users to", &tag))
}
}
pub(crate) fn set_credentials(&self, credentials: &[(&str, &str)]) -> AnyResult<()> {
let auth = self.obj().auth().unwrap_or_else(RTSPAuth::new);
auth.set_supported_methods(RTSPAuthMethod::Basic);
+721 -374
View File
File diff suppressed because it is too large. Load diff
-105
View File
@@ -1,105 +0,0 @@
//! A critically damped spring
use tokio::time::Instant;
#[derive(Debug)]
pub(crate) struct Spring {
last_update: Instant,
target: f64,
value: f64,
velocity: f64,
halflife: f64,
}
impl Spring {
pub(crate) fn new(value: f64, target: f64, halflife: f64) -> Self {
Self {
value,
target,
halflife,
last_update: Instant::now(),
velocity: 0.0f64,
}
}
pub(crate) async fn update(&mut self) {
let now = Instant::now();
let dt = now - self.last_update;
self.last_update = now;
spring_update(
&mut self.value,
self.target,
&mut self.velocity,
self.halflife,
dt.as_secs_f64(),
);
}
// pub(crate) fn value(&self) -> f64 {
// self.value
// }
// pub(crate) fn value_u32(&self) -> u32 {
// self.value.max(std::u32::MIN as f64).floor().min(std::u32::MAX as f64) as u32
// }
pub(crate) fn value_i64(&self) -> i64 {
self.value
.max(std::i64::MIN as f64)
.floor()
.min(std::i64::MAX as f64) as i64
}
pub(crate) fn value_u64(&self) -> u64 {
self.value
.max(std::u64::MIN as f64)
.floor()
.min(std::u64::MAX as f64) as u64
}
#[allow(dead_code)]
pub(crate) fn set_target(&mut self, target: f64) {
self.target = target;
}
#[allow(dead_code)] // Used in debug print
pub(crate) fn get_target(&self) -> f64 {
self.target
}
#[allow(dead_code)]
pub(crate) fn mod_value(&mut self, delta: f64) {
self.target += delta;
self.value += delta;
}
pub(crate) fn reset_to(&mut self, target: f64) {
self.target = target;
self.value = target;
self.velocity = 0.0;
}
}
const EPS: f64 = 1e-5;
fn halflife_to_damping(halflife: f64) -> f64 {
(4.0 * std::f64::consts::LN_2) / (halflife + EPS)
}
// fn damping_to_halflife(damping: f32) -> f32 {
// (4.0f32 * std::f32::consts::LN_2) / (damping + EPS)
// }
fn fast_negexp(x: f64) -> f64 {
1.0 / (1.0 + x + 0.48 * x * x + 0.235 * x * x * x)
}
fn spring_update(value: &mut f64, target: f64, velocity: &mut f64, halflife: f64, dt: f64) {
if halflife.abs() < 1e-3 {
*value = target;
*velocity = 0.0;
} else {
let y = halflife_to_damping(halflife) / 2.0;
let j0 = *value - target;
let j1 = *velocity + j0 * y;
let eydt = fast_negexp(y * dt);
*value = eydt * (j0 + j1 * dt) + target;
*velocity = eydt * (*velocity - j1 * y * dt);
}
}