Handle stream vid/aud seperation globally
This commit is contained in:
6 files changed
+725
-463
No files matched your search
@@ -29,6 +29,8 @@ impl NeoCamThread {
|
||||
async fn run_camera(&mut self, config: &CameraConfig) -> Result<()> {
|
||||
let camera = Arc::new(connect_and_login(config).await?);
|
||||
|
||||
update_camera_time(&camera, &config.name, config.update_time).await?;
|
||||
|
||||
self.camera_watch.send_replace(Arc::downgrade(&camera));
|
||||
|
||||
let cancel_check = self.cancel.clone();
|
||||
@@ -142,3 +144,39 @@ impl Drop for NeoCamThread {
|
||||
self.cancel.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
async fn update_camera_time(camera: &BcCamera, name: &str, update_time: bool) -> Result<()> {
|
||||
let cam_time = camera.get_time().await?;
|
||||
let mut update = false;
|
||||
if let Some(time) = cam_time {
|
||||
log::info!("{}: Camera time is already set: {}", name, time);
|
||||
if update_time {
|
||||
update = true;
|
||||
}
|
||||
} else {
|
||||
update = true;
|
||||
log::warn!("{}: Camera has no time set, Updating", name);
|
||||
}
|
||||
if update {
|
||||
use std::time::SystemTime;
|
||||
let new_time = SystemTime::now();
|
||||
|
||||
log::info!("{}: Setting time to {:?}", name, new_time);
|
||||
match camera.set_time(new_time.into()).await {
|
||||
Ok(_) => {
|
||||
let cam_time = camera.get_time().await?;
|
||||
if let Some(time) = cam_time {
|
||||
log::info!("{}: Camera time is now set: {}", name, time);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"{}: Camera did not accept new time (is user an admin?): Error: {:?}",
|
||||
name,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+320
-198
@@ -13,20 +13,18 @@ use tokio::{
|
||||
broadcast::{
|
||||
channel as broadcast, Receiver as BroadcastReceiver, Sender as BroadcastSender,
|
||||
},
|
||||
mpsc::Receiver as MpscReceiver,
|
||||
mpsc::{channel as mpsc, Receiver as MpscReceiver, Sender as MpscSender},
|
||||
oneshot::Sender as OneshotSender,
|
||||
watch::{channel as watch, Receiver as WatchReceiver, Sender as WatchSender},
|
||||
},
|
||||
task::JoinHandle,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::NeoInstance;
|
||||
use crate::Result;
|
||||
use neolink_core::{
|
||||
bc_protocol::StreamKind,
|
||||
bcmedia::model::{BcMedia, VideoType},
|
||||
};
|
||||
use crate::{AnyResult, Result};
|
||||
use neolink_core::{bc_protocol::StreamKind, bcmedia::model::*};
|
||||
|
||||
pub(crate) struct NeoCamStreamThread {
|
||||
streams: HashMap<StreamKind, StreamData>,
|
||||
@@ -51,23 +49,21 @@ impl NeoCamStreamThread {
|
||||
pub(crate) async fn run(&mut self) -> Result<()> {
|
||||
let thread_cancel = self.cancel.clone();
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => Ok(()),
|
||||
_ = thread_cancel.cancelled() => {
|
||||
for (_, mut data) in self.streams.drain() {
|
||||
let _ = data.shutdown().await;
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
v = async {
|
||||
while let Some(request) = self.stream_request_rx.recv().await {
|
||||
match request {
|
||||
StreamRequest::Get {
|
||||
name, sender
|
||||
} => {
|
||||
if let Entry::Occupied(mut occ) = self.streams.entry(name) {
|
||||
let sub = occ.get().sender.subscribe();
|
||||
occ.get_mut().ensure_running().await?;
|
||||
|
||||
let _ = sender.send(Some(
|
||||
StreamInstance {
|
||||
name,
|
||||
stream: sub,
|
||||
config: occ.get().config.subscribe(),
|
||||
}));
|
||||
if let Entry::Occupied(occ) = self.streams.entry(name) {
|
||||
let _ = sender.send(Some(
|
||||
StreamInstance::new(occ.get()).await?));
|
||||
} else {
|
||||
let _ = sender.send(None);
|
||||
}
|
||||
@@ -76,34 +72,26 @@ impl NeoCamStreamThread {
|
||||
name, sender, strict
|
||||
} => {
|
||||
match self.streams.entry(name) {
|
||||
Entry::Occupied(mut occ) => {
|
||||
let sub = occ.get().sender.subscribe();
|
||||
occ.get_mut().ensure_running().await?;
|
||||
Entry::Occupied(occ) => {
|
||||
let _ = sender
|
||||
.send(StreamInstance {
|
||||
name,
|
||||
stream: sub,
|
||||
config: occ.get().config.subscribe(),
|
||||
});
|
||||
.send(StreamInstance::new(occ.get()).await?);
|
||||
}
|
||||
Entry::Vacant(vac) => {
|
||||
// Make a new streaming instance
|
||||
|
||||
let (sender_tx, stream_rx) = broadcast(1000);
|
||||
let mut data = StreamData::new(
|
||||
sender_tx,
|
||||
let data = StreamData::new(
|
||||
name,
|
||||
self.instance.subscribe().await?,
|
||||
strict,
|
||||
).await?;
|
||||
data.ensure_running().await?;
|
||||
let config = data.config.subscribe();
|
||||
vac.insert(data);
|
||||
let _ = sender.send(StreamInstance {
|
||||
name,
|
||||
stream: stream_rx,
|
||||
config,
|
||||
});
|
||||
let vid = data.vid.subscribe();
|
||||
let aud = data.aud.subscribe();
|
||||
let in_use = data.users.activated().await?;
|
||||
|
||||
let data = vac.insert(data);
|
||||
|
||||
let _ = sender.send(StreamInstance::new(data).await?);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -117,16 +105,9 @@ impl NeoCamStreamThread {
|
||||
StreamKind::Sub,
|
||||
];
|
||||
for name in streams.drain(..) {
|
||||
if let Entry::Occupied(mut occ) = self.streams.entry(name) {
|
||||
let sub = occ.get().sender.subscribe();
|
||||
occ.get_mut().ensure_running().await?;
|
||||
|
||||
if let Entry::Occupied(occ) = self.streams.entry(name) {
|
||||
result = Some(
|
||||
StreamInstance {
|
||||
name,
|
||||
stream: sub,
|
||||
config: occ.get().config.subscribe(),
|
||||
});
|
||||
StreamInstance::new(occ.get()).await?);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -142,15 +123,14 @@ impl NeoCamStreamThread {
|
||||
StreamKind::Main,
|
||||
];
|
||||
for name in streams.drain(..) {
|
||||
if let Entry::Occupied(mut occ) = self.streams.entry(name) {
|
||||
let sub = occ.get().sender.subscribe();
|
||||
occ.get_mut().ensure_running().await?;
|
||||
|
||||
if let Entry::Occupied(occ) = self.streams.entry(name) {
|
||||
result = Some(
|
||||
StreamInstance {
|
||||
name,
|
||||
stream: sub,
|
||||
vid: occ.get().vid.subscribe(),
|
||||
aud: occ.get().aud.subscribe(),
|
||||
config: occ.get().config.subscribe(),
|
||||
in_use: occ.get().users.activated().await?,
|
||||
});
|
||||
break;
|
||||
}
|
||||
@@ -164,23 +144,17 @@ impl NeoCamStreamThread {
|
||||
let streams = config.stream.as_stream_kinds();
|
||||
for stream in streams.iter().copied() {
|
||||
if let Entry::Vacant(vac) = self.streams.entry(stream) {
|
||||
let (tx, _) = broadcast(1000);
|
||||
vac.insert(
|
||||
StreamData::new(tx, stream, self.instance.subscribe().await?, config.strict)
|
||||
StreamData::new(stream, self.instance.subscribe().await?, config.strict)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut streams = self.streams.iter_mut().filter_map(|(name, stream)| if streams.contains(name) {
|
||||
Some(async move {
|
||||
let sub = stream.sender.subscribe();
|
||||
stream.ensure_running().await?;
|
||||
Result::<_, anyhow::Error>::Ok(
|
||||
StreamInstance {
|
||||
name: *name,
|
||||
stream: sub,
|
||||
config: stream.config.subscribe(),
|
||||
})
|
||||
StreamInstance::new(&stream).await?
|
||||
)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
@@ -235,15 +209,129 @@ pub(crate) enum StreamRequest {
|
||||
},
|
||||
}
|
||||
|
||||
/// Counts the active users of the stream
|
||||
pub(crate) struct UseCounter {
|
||||
value: WatchReceiver<u32>,
|
||||
notifier_tx: MpscSender<bool>,
|
||||
cancel: CancellationToken,
|
||||
}
|
||||
|
||||
impl UseCounter {
|
||||
async fn new() -> Self {
|
||||
let (notifier_tx, mut notifier) = mpsc(100);
|
||||
let (value_tx, value) = watch(0);
|
||||
let cancel = CancellationToken::new();
|
||||
|
||||
let thread_cancel = cancel.clone();
|
||||
tokio::task::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => {
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
v = async {
|
||||
while let Some(noti) = notifier.recv().await {
|
||||
value_tx.send_modify(|value| {
|
||||
if noti {
|
||||
*value += 1;
|
||||
} else {
|
||||
*value -= 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
} => v,
|
||||
}
|
||||
});
|
||||
Self {
|
||||
value,
|
||||
notifier_tx,
|
||||
cancel,
|
||||
}
|
||||
}
|
||||
|
||||
async fn activated(&self) -> Result<CountUses> {
|
||||
let mut res = CountUses::new(self);
|
||||
res.activate().await?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
async fn deactivated(&self) -> Result<CountUses> {
|
||||
Ok(CountUses::new(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for UseCounter {
|
||||
fn drop(&mut self) {
|
||||
self.cancel.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CountUses {
|
||||
is_active: bool,
|
||||
value: WatchReceiver<u32>,
|
||||
notifier: MpscSender<bool>,
|
||||
}
|
||||
|
||||
impl CountUses {
|
||||
fn new(source: &UseCounter) -> Self {
|
||||
Self {
|
||||
is_active: false,
|
||||
value: source.value.clone(),
|
||||
notifier: source.notifier_tx.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn activate(&mut self) -> Result<()> {
|
||||
if !self.is_active {
|
||||
self.is_active = true;
|
||||
self.notifier.send(self.is_active).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn deactivate(&mut self) -> Result<()> {
|
||||
if self.is_active {
|
||||
self.is_active = false;
|
||||
self.notifier.send(self.is_active).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn aquired_users(&self) -> Result<()> {
|
||||
self.value.clone().wait_for(|curr| *curr > 0).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn dropped_users(&self) -> Result<()> {
|
||||
self.value.clone().wait_for(|curr| *curr == 0).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CountUses {
|
||||
fn drop(&mut self) {
|
||||
if self.is_active {
|
||||
self.is_active = false;
|
||||
tokio::task::block_in_place(move || {
|
||||
tokio::runtime::Handle::current().block_on(async move {
|
||||
let _ = self.notifier.send(self.is_active).await;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The data of a running stream
|
||||
pub(crate) struct StreamData {
|
||||
sender: BroadcastSender<BcMedia>,
|
||||
vid: BroadcastSender<StampedData>,
|
||||
aud: BroadcastSender<StampedData>,
|
||||
config: Arc<WatchSender<StreamConfig>>,
|
||||
name: StreamKind,
|
||||
instance: NeoInstance,
|
||||
cancel: CancellationToken,
|
||||
handle: Option<JoinHandle<Result<()>>>,
|
||||
strict: bool,
|
||||
users: UseCounter,
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Clone)]
|
||||
@@ -266,19 +354,42 @@ pub(crate) struct StreamConfig {
|
||||
pub(crate) aud_format: AudFormat,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct StampedData {
|
||||
pub(crate) data: Vec<u8>,
|
||||
pub(crate) ts: Duration,
|
||||
}
|
||||
|
||||
pub(crate) struct StreamInstance {
|
||||
pub(crate) name: StreamKind,
|
||||
pub(crate) stream: BroadcastReceiver<BcMedia>,
|
||||
pub(crate) vid: BroadcastReceiver<StampedData>,
|
||||
pub(crate) aud: BroadcastReceiver<StampedData>,
|
||||
pub(crate) config: WatchReceiver<StreamConfig>,
|
||||
in_use: CountUses,
|
||||
}
|
||||
|
||||
impl StreamInstance {
|
||||
pub async fn new(data: &StreamData) -> Result<Self> {
|
||||
Ok(Self {
|
||||
name: data.name,
|
||||
vid: data.vid.subscribe(),
|
||||
aud: data.aud.subscribe(),
|
||||
config: data.config.subscribe(),
|
||||
in_use: data.users.activated().await?,
|
||||
})
|
||||
}
|
||||
pub(crate) async fn activate(&mut self) -> Result<()> {
|
||||
self.in_use.activate().await
|
||||
}
|
||||
pub(crate) async fn deactivate(&mut self) -> Result<()> {
|
||||
self.in_use.activate().await
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamData {
|
||||
async fn new(
|
||||
sender: BroadcastSender<BcMedia>,
|
||||
name: StreamKind,
|
||||
instance: NeoInstance,
|
||||
strict: bool,
|
||||
) -> Result<Self> {
|
||||
async fn new(name: StreamKind, instance: NeoInstance, strict: bool) -> Result<Self> {
|
||||
let (vid, _) = broadcast::<StampedData>(100);
|
||||
let (aud, _) = broadcast::<StampedData>(100);
|
||||
let resolution = instance
|
||||
.run_task(|cam| {
|
||||
Box::pin(async move {
|
||||
@@ -304,164 +415,175 @@ impl StreamData {
|
||||
vid_format: VidFormat::None,
|
||||
aud_format: AudFormat::None,
|
||||
});
|
||||
let me = Self {
|
||||
let mut me = Self {
|
||||
name,
|
||||
cancel: CancellationToken::new(),
|
||||
config: Arc::new(config_tx),
|
||||
sender,
|
||||
vid,
|
||||
aud,
|
||||
instance,
|
||||
handle: None,
|
||||
strict,
|
||||
users: UseCounter::new().await,
|
||||
};
|
||||
Ok(me)
|
||||
}
|
||||
|
||||
async fn ensure_running(&mut self) -> Result<()> {
|
||||
if self.cancel.is_cancelled()
|
||||
|| self
|
||||
.handle
|
||||
.as_ref()
|
||||
.map(|handle| handle.is_finished())
|
||||
.unwrap_or(true)
|
||||
{
|
||||
log::debug!("Restart stream");
|
||||
self.restart().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let cancel = me.cancel.clone();
|
||||
let vid = me.vid.clone();
|
||||
let aud = me.aud.clone();
|
||||
let instance = me.instance.subscribe().await?;
|
||||
let name = me.name;
|
||||
let strict = me.strict;
|
||||
let config = me.config.clone();
|
||||
let thread_inuse = me.users.deactivated().await?;
|
||||
|
||||
async fn restart(&mut self) -> Result<()> {
|
||||
self.shutdown().await?;
|
||||
self.cancel = CancellationToken::new();
|
||||
|
||||
let cancel = self.cancel.clone();
|
||||
let sender = self.sender.clone();
|
||||
let instance = self.instance.subscribe().await?;
|
||||
let name = self.name;
|
||||
let strict = self.strict;
|
||||
let config = self.config.clone();
|
||||
self.handle = Some(tokio::task::spawn(async move {
|
||||
me.handle = Some(tokio::task::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => {
|
||||
Result::<(), anyhow::Error>::Ok(())
|
||||
},
|
||||
v = async {
|
||||
loop {
|
||||
let result = instance.run_task(|camera| {
|
||||
let stream_tx = sender.clone();
|
||||
let stream_config = config.clone();
|
||||
Box::pin(async move {
|
||||
let res = async {
|
||||
let mut stream_data = camera.start_video(name, 0, strict).await?;
|
||||
loop {
|
||||
let data = stream_data.get_data().await??;
|
||||
tokio::select! {
|
||||
v = thread_inuse.dropped_users() => {
|
||||
// Handles the stop and restart when no active users
|
||||
v?;
|
||||
thread_inuse.aquired_users().await?; // Wait for new users of the stream
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
result = instance.run_task(|camera| {
|
||||
let vid_tx = vid.clone();
|
||||
let aud_tx = aud.clone();
|
||||
let stream_config = config.clone();
|
||||
Box::pin(async move {
|
||||
let res = async {
|
||||
let mut prev_ts = Duration::ZERO;
|
||||
let mut stream_data = camera.start_video(name, 0, strict).await?;
|
||||
loop {
|
||||
let data = stream_data.get_data().await??;
|
||||
|
||||
// Update the stream config with any information
|
||||
match &data {
|
||||
BcMedia::InfoV1(info) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
if state.resolution[0] != info.video_width || state.resolution[1] != info.video_height {
|
||||
state.resolution[0] = info.video_width;
|
||||
state.resolution[1] = info.video_height;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
// Update the stream config with any information
|
||||
match &data {
|
||||
BcMedia::InfoV1(info) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
if state.resolution[0] != info.video_width || state.resolution[1] != info.video_height {
|
||||
state.resolution[0] = info.video_width;
|
||||
state.resolution[1] = info.video_height;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
},
|
||||
BcMedia::InfoV2(info) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
if state.resolution[0] != info.video_width || state.resolution[1] != info.video_height {
|
||||
state.resolution[0] = info.video_width;
|
||||
state.resolution[1] = info.video_height;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
},
|
||||
BcMedia::Iframe(frame) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
let expected = match frame.video_type {
|
||||
VideoType::H264 => VidFormat::H264,
|
||||
VideoType::H265 => VidFormat::H265,
|
||||
};
|
||||
if state.vid_format != expected {
|
||||
state.vid_format = expected;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
BcMedia::InfoV2(info) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
if state.resolution[0] != info.video_width || state.resolution[1] != info.video_height {
|
||||
state.resolution[0] = info.video_width;
|
||||
state.resolution[1] = info.video_height;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
BcMedia::Pframe(frame) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
let expected = match frame.video_type {
|
||||
VideoType::H264 => VidFormat::H264,
|
||||
VideoType::H265 => VidFormat::H265,
|
||||
};
|
||||
if state.vid_format != expected {
|
||||
state.vid_format = expected;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
},
|
||||
BcMedia::Aac(_) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
if state.aud_format != AudFormat::Aac {
|
||||
state.aud_format = AudFormat::Aac;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
BcMedia::Iframe(frame) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
let expected = match frame.video_type {
|
||||
VideoType::H264 => VidFormat::H264,
|
||||
VideoType::H265 => VidFormat::H265,
|
||||
};
|
||||
if state.vid_format != expected {
|
||||
state.vid_format = expected;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
BcMedia::Adpcm(aud) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
let expected = AudFormat::Adpcm(aud.data.len() as u32 - 4);
|
||||
if state.aud_format != expected {
|
||||
state.aud_format = expected;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
BcMedia::Pframe(frame) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
let expected = match frame.video_type {
|
||||
VideoType::H264 => VidFormat::H264,
|
||||
VideoType::H265 => VidFormat::H265,
|
||||
};
|
||||
if state.vid_format != expected {
|
||||
state.vid_format = expected;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
},
|
||||
BcMedia::Aac(_) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
if state.aud_format != AudFormat::Aac {
|
||||
state.aud_format = AudFormat::Aac;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
BcMedia::Adpcm(aud) => {
|
||||
stream_config.send_if_modified(|state| {
|
||||
let expected = AudFormat::Adpcm(aud.data.len() as u32 - 4);
|
||||
if state.aud_format != expected {
|
||||
state.aud_format = expected;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Send the stream data onwards
|
||||
if stream_tx.send(data).is_err() {
|
||||
// If noone is listening for the stream we error and stop here
|
||||
break;
|
||||
};
|
||||
}
|
||||
Result::<(),anyhow::Error>::Ok(())
|
||||
}.await;
|
||||
Ok(res)
|
||||
})
|
||||
}).await;
|
||||
match result {
|
||||
Ok(Ok(())) => {
|
||||
log::debug!("Video Stream Stopped due to no listeners");
|
||||
break;
|
||||
match data {
|
||||
BcMedia::Iframe(BcMediaIframe{data, microseconds, ..}) | BcMedia::Pframe(BcMediaPframe{data, microseconds,..}) => {
|
||||
prev_ts = Duration::from_micros(microseconds as u64);
|
||||
let _ = vid_tx.send(
|
||||
StampedData{
|
||||
data,
|
||||
ts: prev_ts
|
||||
});
|
||||
log::trace!("Sent Vid Frame");
|
||||
}
|
||||
BcMedia::Aac(BcMediaAac{data, ..}) | BcMedia::Adpcm(BcMediaAdpcm{data,..}) => {
|
||||
let _ = aud_tx.send(
|
||||
StampedData{
|
||||
data,
|
||||
ts: prev_ts,
|
||||
})?;
|
||||
log::trace!("Sent Aud Frame");
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
Result::<(),anyhow::Error>::Ok(())
|
||||
}.await;
|
||||
Ok(res)
|
||||
})
|
||||
}) => {
|
||||
match result {
|
||||
Ok(Ok(())) => {
|
||||
log::debug!("Video Stream Stopped due to no listeners");
|
||||
break Ok(());
|
||||
},
|
||||
Ok(Err(e)) => {
|
||||
log::debug!("Video Stream Restarting Due to Error: {:?}", e);
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
Err(e) => {
|
||||
log::debug!("Video Stream Stopped Due to Instance Error: {:?}", e);
|
||||
break Err(e);
|
||||
},
|
||||
}
|
||||
},
|
||||
Ok(Err(e)) => {
|
||||
log::debug!("Video Stream Restarting Due to Error: {:?}", e);
|
||||
},
|
||||
Err(e) => {
|
||||
log::debug!("Video Stream Stopped Due to Instance Error: {:?}", e);
|
||||
break;
|
||||
},
|
||||
}
|
||||
}?;
|
||||
}
|
||||
Ok(())
|
||||
} => v,
|
||||
}
|
||||
}));
|
||||
|
||||
Ok(())
|
||||
Ok(me)
|
||||
}
|
||||
|
||||
async fn shutdown(&mut self) -> Result<()> {
|
||||
|
||||
@@ -163,9 +163,6 @@ pub(crate) struct CameraConfig {
|
||||
#[serde(default = "default_buffer_size", alias = "size", alias = "buffer")]
|
||||
pub(crate) buffer_size: usize,
|
||||
|
||||
#[serde(default = "default_true", alias = "splash")]
|
||||
pub(crate) use_splash: bool,
|
||||
|
||||
#[serde(default = "default_true", alias = "enable")]
|
||||
pub(crate) enabled: bool,
|
||||
|
||||
@@ -344,10 +341,6 @@ fn default_pause() -> PauseConfig {
|
||||
}
|
||||
}
|
||||
|
||||
fn default_smoothing() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_buffer_size() -> usize {
|
||||
25
|
||||
}
|
||||
|
||||
+7
-4
@@ -12,6 +12,8 @@ use tokio::{
|
||||
task::{self, JoinSet},
|
||||
};
|
||||
|
||||
use crate::common::VidFormat;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum GstControl {
|
||||
Data(Vec<u8>),
|
||||
@@ -56,7 +58,7 @@ impl GstSender {
|
||||
}
|
||||
|
||||
pub(super) async fn from_input<T: AsRef<Path>>(
|
||||
format: VideoType,
|
||||
format: VidFormat,
|
||||
out_file: T,
|
||||
) -> Result<GstSender> {
|
||||
let pipeline = create_pipeline(format, out_file.as_ref())?;
|
||||
@@ -144,13 +146,13 @@ fn get_source(pipeline: &Pipeline) -> Result<AppSrc> {
|
||||
.map_err(|_| anyhow!("Cannot find appsource in gstreamer, check your gstreamer plugins"))
|
||||
}
|
||||
|
||||
fn create_pipeline(format: VideoType, file_path: &Path) -> Result<Pipeline> {
|
||||
fn create_pipeline(format: VidFormat, file_path: &Path) -> Result<Pipeline> {
|
||||
gstreamer::init()
|
||||
.context("Unable to start gstreamer ensure it and all plugins are installed")?;
|
||||
let file_path = file_path.with_extension("jpeg");
|
||||
|
||||
let launch_str = match format {
|
||||
VideoType::H264 => {
|
||||
VidFormat::H264 => {
|
||||
format!(
|
||||
"appsrc name=thesource \
|
||||
! h264parse \
|
||||
@@ -160,7 +162,7 @@ fn create_pipeline(format: VideoType, file_path: &Path) -> Result<Pipeline> {
|
||||
file_path.display()
|
||||
)
|
||||
}
|
||||
VideoType::H265 => {
|
||||
VidFormat::H265 => {
|
||||
format!(
|
||||
"appsrc name=thesource \
|
||||
! h265parse \
|
||||
@@ -170,6 +172,7 @@ fn create_pipeline(format: VideoType, file_path: &Path) -> Result<Pipeline> {
|
||||
file_path.display()
|
||||
)
|
||||
}
|
||||
VidFormat::None => unreachable!(),
|
||||
};
|
||||
|
||||
log::info!("{}", launch_str);
|
||||
|
||||
+13
-12
@@ -27,7 +27,7 @@ use tokio_stream::wrappers::BroadcastStream;
|
||||
mod cmdline;
|
||||
mod gst;
|
||||
|
||||
use crate::common::NeoReactor;
|
||||
use crate::common::{NeoReactor, StampedData, VidFormat};
|
||||
pub(crate) use cmdline::Opt;
|
||||
|
||||
/// Entry point for the image subcommand
|
||||
@@ -43,17 +43,19 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
.context("Failed to start video")?;
|
||||
|
||||
// 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_config = stream_data.config.clone();
|
||||
let vid_type = stream_config
|
||||
.wait_for(|config| config.vid_format != VidFormat::None)
|
||||
.await?
|
||||
.vid_format
|
||||
.clone();
|
||||
let mut stream = BroadcastStream::new(stream_data.vid.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;
|
||||
buf = frame.data;
|
||||
break;
|
||||
let buf = loop {
|
||||
if let Some(Ok(StampedData { data, ts: _ })) = stream.next().await {
|
||||
break data;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut sender = gst::from_input(vid_type, &opt.file_path).await?;
|
||||
sender.send(buf).await?; // Send first iframe
|
||||
@@ -61,8 +63,7 @@ pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
// Keep sending both IFrame or PFrame until finished
|
||||
while sender.is_finished().await.is_none() {
|
||||
let buf = match stream.next().await {
|
||||
Some(Ok(BcMedia::Iframe(frame))) => frame.data,
|
||||
Some(Ok(BcMedia::Pframe(frame))) => frame.data,
|
||||
Some(Ok(StampedData { data, .. })) => data,
|
||||
_ => {
|
||||
continue;
|
||||
}
|
||||
|
||||
+347
-242
@@ -62,8 +62,8 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use tokio::{
|
||||
sync::{
|
||||
broadcast::channel as broadcast,
|
||||
mpsc::{channel as mpsc, Sender as MpscSender},
|
||||
broadcast::{channel as broadcast, Receiver as BroadcastReceiver},
|
||||
mpsc::{channel as mpsc, Receiver as MpscReceiver, Sender as MpscSender},
|
||||
},
|
||||
task::JoinSet,
|
||||
time::{sleep, Duration},
|
||||
@@ -74,8 +74,9 @@ use tokio_util::sync::CancellationToken;
|
||||
mod cmdline;
|
||||
mod gst;
|
||||
|
||||
use crate::common::StampedData;
|
||||
use crate::{
|
||||
common::{AudFormat, NeoInstance, NeoReactor, StreamInstance, VidFormat},
|
||||
common::{AudFormat, NeoInstance, NeoReactor, StreamConfig, StreamInstance, VidFormat},
|
||||
rtsp::gst::NeoMediaFactory,
|
||||
};
|
||||
|
||||
@@ -154,14 +155,15 @@ pub(crate) async fn main(_opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
}).await.with_context(|| "Camera Config Watcher")?;
|
||||
config_names = thread_config.borrow().clone().cameras.iter().filter(|a| a.enabled).map(|cam_config| cam_config.name.clone()).collect::<HashSet<_>>();
|
||||
|
||||
for name in config_names.iter().cloned() {
|
||||
for name in config_names.iter() {
|
||||
log::info!("{name}: Rtsp Staring");
|
||||
if ! cameras.contains_key(&name) {
|
||||
if ! cameras.contains_key(name) {
|
||||
let local_cancel = CancellationToken::new();
|
||||
cameras.insert(name.clone(),local_cancel.clone() );
|
||||
let thread_global_cancel = thread_cancel2.clone();
|
||||
let thread_rtsp2 = thread_rtsp.clone();
|
||||
let thread_reactor2 = thread_reactor.clone();
|
||||
let name = name.clone();
|
||||
set.spawn_blocking(|| {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
@@ -179,7 +181,7 @@ pub(crate) async fn main(_opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
v = camera_main(camera, &thread_rtsp2) => v,
|
||||
)
|
||||
})
|
||||
});
|
||||
}) ;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,6 +229,7 @@ pub(crate) async fn main(_opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// This keeps the users in rtsp and the config in sync
|
||||
async fn apply_users(rtsp: &NeoRtspServer, config: &Config) -> AnyResult<()> {
|
||||
// Add those missing
|
||||
for user in config.users.iter() {
|
||||
@@ -247,6 +250,9 @@ async fn apply_users(rtsp: &NeoRtspServer, config: &Config) -> AnyResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Top level camera entry point
|
||||
///
|
||||
/// It checks which streams are supported and then starts them
|
||||
async fn camera_main(camera: NeoInstance, rtsp: &NeoRtspServer) -> Result<()> {
|
||||
let stream_info = camera
|
||||
.run_task(|cam| Box::pin(async move { Ok(cam.get_stream_info().await?) }))
|
||||
@@ -290,6 +296,8 @@ async fn camera_main(camera: NeoInstance, rtsp: &NeoRtspServer) -> Result<()> {
|
||||
},
|
||||
v = async {
|
||||
// This select handles enabling the right stream
|
||||
|
||||
// and setting up the users
|
||||
let all_users = rtsp.get_users().await?.iter().filter(|a| *a != "anyone" && *a != "anonymous").cloned().collect::<HashSet<_>>();
|
||||
let permitted_users: HashSet<String> = match &prev_stream_users {
|
||||
// If in the camera config there is the user "anyone", or if none is specified but users
|
||||
@@ -307,15 +315,54 @@ async fn camera_main(camera: NeoInstance, rtsp: &NeoRtspServer) -> Result<()> {
|
||||
tokio::select! {
|
||||
v = async {
|
||||
let name = camera.config().await?.borrow().name.clone();
|
||||
stream_main(name, camera.stream(StreamKind::Main).await?, rtsp, &permitted_users).await
|
||||
let mut paths = vec![
|
||||
format!("/{name}/main"),
|
||||
format!("/{name}/Main"),
|
||||
format!("/{name}/mainStream"),
|
||||
format!("/{name}/MainStream"),
|
||||
format!("/{name}/Mainstream"),
|
||||
format!("/{name}/mainstream"),
|
||||
];
|
||||
if camera.high_stream().await?.map(|s| s.name == StreamKind::Main).unwrap_or(false) {
|
||||
paths.push(
|
||||
format!("/{name}")
|
||||
);
|
||||
}
|
||||
stream_main(camera.stream(StreamKind::Main).await?, camera.clone(), rtsp, &permitted_users, &paths).await
|
||||
}, if active_streams.contains(&StreamKind::Main) && supported_streams.contains(&StreamKind::Main) => v,
|
||||
v = async {
|
||||
let name = camera.config().await?.borrow().name.clone();
|
||||
stream_main(name, camera.stream(StreamKind::Sub).await?, rtsp, &permitted_users).await
|
||||
let mut paths = vec![
|
||||
format!("/{name}/sub"),
|
||||
format!("/{name}/Sub"),
|
||||
format!("/{name}/subStream"),
|
||||
format!("/{name}/SubStream"),
|
||||
format!("/{name}/Substream"),
|
||||
format!("/{name}/substream"),
|
||||
];
|
||||
if camera.high_stream().await?.map(|s| s.name == StreamKind::Sub).unwrap_or(false) {
|
||||
paths.push(
|
||||
format!("/{name}")
|
||||
);
|
||||
}
|
||||
stream_main(camera.stream(StreamKind::Sub).await?,camera.clone(), rtsp, &permitted_users, &paths).await
|
||||
}, if active_streams.contains(&StreamKind::Sub) && supported_streams.contains(&StreamKind::Sub) => v,
|
||||
v = async {
|
||||
let name = camera.config().await?.borrow().name.clone();
|
||||
stream_main(name, camera.stream(StreamKind::Extern).await?, rtsp, &permitted_users).await
|
||||
let mut paths = vec![
|
||||
format!("/{name}/extern"),
|
||||
format!("/{name}/Extern"),
|
||||
format!("/{name}/externStream"),
|
||||
format!("/{name}/ExternStream"),
|
||||
format!("/{name}/Externstream"),
|
||||
format!("/{name}/externstream"),
|
||||
];
|
||||
if camera.high_stream().await?.map(|s| s.name == StreamKind::Extern).unwrap_or(false) {
|
||||
paths.push(
|
||||
format!("/{name}")
|
||||
);
|
||||
}
|
||||
stream_main(camera.stream(StreamKind::Extern).await?,camera.clone(), rtsp, &permitted_users, &paths).await
|
||||
}, if active_streams.contains(&StreamKind::Extern) && supported_streams.contains(&StreamKind::Extern) => v,
|
||||
else => {
|
||||
// all disabled just wait here until config is changed
|
||||
@@ -330,17 +377,29 @@ async fn camera_main(camera: NeoInstance, rtsp: &NeoRtspServer) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Clone, Debug)]
|
||||
enum StreamData {
|
||||
Media { data: Vec<u8>, ts: Duration },
|
||||
Seek { ts: Duration, reply: MpscSender<()> },
|
||||
}
|
||||
|
||||
struct ClientSourceData {
|
||||
app: AppSrc,
|
||||
msg: MpscReceiver<StreamData>,
|
||||
}
|
||||
|
||||
struct ClientData {
|
||||
vid: Option<ClientSourceData>,
|
||||
aud: Option<ClientSourceData>,
|
||||
}
|
||||
|
||||
/// This handles the stream itself by creating the factory and pushing messages into it
|
||||
async fn stream_main(
|
||||
name: String,
|
||||
mut stream_instance: StreamInstance,
|
||||
camera: NeoInstance,
|
||||
rtsp: &NeoRtspServer,
|
||||
users: &HashSet<String>,
|
||||
paths: &[String],
|
||||
) -> Result<()> {
|
||||
loop {
|
||||
// Wait for a valid stream format to be detected
|
||||
@@ -352,260 +411,306 @@ async fn stream_main(
|
||||
&& config.resolution[1] > 0
|
||||
})
|
||||
.await?;
|
||||
let stream = stream_instance.stream.resubscribe();
|
||||
let stream_name = match stream_instance.name {
|
||||
StreamKind::Main => "main",
|
||||
StreamKind::Sub => "sub",
|
||||
StreamKind::Extern => "extern",
|
||||
}
|
||||
.to_string();
|
||||
|
||||
let vid = stream_instance.vid.resubscribe();
|
||||
let aud = stream_instance.aud.resubscribe();
|
||||
let thread_stream_config = stream_instance.config.clone();
|
||||
// This select ensures is for the streams config
|
||||
// This select is for the streams config updates
|
||||
break tokio::select! {
|
||||
_ = stream_instance.config.changed() => {
|
||||
// If stream config changes we reload the stream
|
||||
continue;
|
||||
},
|
||||
v = async {
|
||||
// Finally ready to create the factory and connect the stream
|
||||
let mounts = rtsp
|
||||
.mount_points()
|
||||
.ok_or(anyhow!("RTSP server lacks mount point"))?;
|
||||
let path = format!("/{}/{}", name, stream_name);
|
||||
log::debug!("Path: {}", path);
|
||||
let stream_config = thread_stream_config.clone();
|
||||
// Create the factory
|
||||
let (client_tx, mut client_rx) = mpsc(100);
|
||||
let factory = {
|
||||
NeoMediaFactory::new_with_callback(move |element| {
|
||||
clear_bin(&element)?;
|
||||
let config = stream_config.borrow().clone();
|
||||
let (vid_seek_tx, vid_seek_rx) = mpsc(10);
|
||||
let (aud_seek_tx, aud_seek_rx) = mpsc(10);
|
||||
let vid = match config.vid_format {
|
||||
VidFormat::None => {
|
||||
build_unknown(&element)?;
|
||||
AnyResult::Ok(None)
|
||||
},
|
||||
VidFormat::H264 => {
|
||||
let app = build_h264(&element)?;
|
||||
app.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.seek_data(move |_, seek_pos| {
|
||||
log::info!("seek_pos: {seek_pos:?}");
|
||||
let (reply_tx, mut reply_rx) = mpsc(1);
|
||||
vid_seek_tx.blocking_send(
|
||||
StreamData::Seek{
|
||||
ts: Duration::from_micros(seek_pos),
|
||||
reply: reply_tx,
|
||||
}).is_ok() && reply_rx.blocking_recv().is_some()
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
AnyResult::Ok(Some(app))
|
||||
},
|
||||
VidFormat::H265 => {
|
||||
let app = build_h265(&element)?;
|
||||
app.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.seek_data(move |_, seek_pos| {
|
||||
log::info!("seek_pos: {seek_pos:?}");
|
||||
let (reply_tx, mut reply_rx) = mpsc(1);
|
||||
vid_seek_tx.blocking_send(
|
||||
StreamData::Seek{
|
||||
ts: Duration::from_micros(seek_pos),
|
||||
reply: reply_tx,
|
||||
}).is_ok() && reply_rx.blocking_recv().is_some()
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
AnyResult::Ok(Some(app))
|
||||
},
|
||||
}?;
|
||||
let aud = if matches!(config.vid_format, VidFormat::None) {
|
||||
None
|
||||
} else {
|
||||
match config.aud_format {
|
||||
AudFormat::None => {
|
||||
AnyResult::Ok(None)
|
||||
},
|
||||
AudFormat::Aac => {
|
||||
let app = build_aac(&element)?;
|
||||
app.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.seek_data(move |_, seek_pos| {
|
||||
log::info!("seek_pos: {seek_pos:?}");
|
||||
let (reply_tx, mut reply_rx) = mpsc(1);
|
||||
aud_seek_tx.blocking_send(
|
||||
StreamData::Seek{
|
||||
ts: Duration::from_micros(seek_pos),
|
||||
reply: reply_tx,
|
||||
}).is_ok() && reply_rx.blocking_recv().is_some()
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
AnyResult::Ok(Some(app))
|
||||
},
|
||||
AudFormat::Adpcm(block_size) => {
|
||||
let app = build_adpcm(&element, block_size)?;
|
||||
app.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.seek_data(move |_, seek_pos| {
|
||||
log::info!("seek_pos: {seek_pos:?}");
|
||||
let (reply_tx, mut reply_rx) = mpsc(1);
|
||||
aud_seek_tx.blocking_send(
|
||||
StreamData::Seek{
|
||||
ts: Duration::from_micros(seek_pos),
|
||||
reply: reply_tx,
|
||||
}).is_ok() && reply_rx.blocking_recv().is_some()
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
AnyResult::Ok(Some(app))
|
||||
},
|
||||
}?
|
||||
};
|
||||
v = stream_run(vid, aud, rtsp, thread_stream_config.borrow().clone(), users, paths) => v,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
client_tx.blocking_send((vid, aud, vid_seek_rx, aud_seek_rx))?;
|
||||
Ok(Some(element))
|
||||
}).await
|
||||
}?;
|
||||
async fn stream_run(
|
||||
vidstream: BroadcastReceiver<StampedData>,
|
||||
audstream: BroadcastReceiver<StampedData>,
|
||||
rtsp: &NeoRtspServer,
|
||||
stream_config: StreamConfig,
|
||||
users: &HashSet<String>,
|
||||
paths: &[String],
|
||||
) -> AnyResult<()> {
|
||||
// Finally ready to create the factory and connect the stream
|
||||
let mounts = rtsp
|
||||
.mount_points()
|
||||
.ok_or(anyhow!("RTSP server lacks mount point"))?;
|
||||
// Create the factory
|
||||
let (factory, mut client_rx) = make_factory(&stream_config).await?;
|
||||
|
||||
factory.add_permitted_roles(users);
|
||||
mounts.add_factory(&path, factory);
|
||||
factory.add_permitted_roles(users);
|
||||
|
||||
// Done now sit on the receiver and push through the vid to the app sources
|
||||
let stream_cancel = CancellationToken::new();
|
||||
let mut set = JoinSet::new();
|
||||
while let Some((vid, aud, mut vid_seek, mut aud_seek)) = client_rx.recv().await {
|
||||
log::trace!("New media");
|
||||
// New media created
|
||||
for path in paths.iter() {
|
||||
log::debug!("Path: {}", path);
|
||||
mounts.add_factory(path, factory.clone());
|
||||
}
|
||||
|
||||
// This thread handles splitting the data into two streams
|
||||
let mut thread_stream = BroadcastStream::new(stream.resubscribe()).filter(|f| f.is_ok()); // Filter to ignore lagged
|
||||
// Use broadcast because of its overflow protection
|
||||
let (vid_data_tx, vid_data_rx) = broadcast(100);
|
||||
let (aud_data_tx, aud_data_rx) = broadcast(100);
|
||||
let thread_stream_cancel = stream_cancel.clone();
|
||||
let thread_vid = vid.clone();
|
||||
let thread_aud = aud.clone();
|
||||
let thread_vid_data_tx = vid_data_tx.clone();
|
||||
let thread_aud_data_tx = aud_data_tx.clone();
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_stream_cancel.cancelled() => {
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
v = async {
|
||||
let mut prev_vid_ms: u32 = 0;
|
||||
// let prev_aud_ms: u32 = 0;
|
||||
let mut vid_time: u64 = 0;
|
||||
// let aud_time: u64 = 0;
|
||||
while let Some(Ok(data)) = thread_stream.next().await {
|
||||
log::trace!("Media Frame Recieved");
|
||||
match data {
|
||||
BcMedia::Iframe(BcMediaIframe{data, microseconds, ..}) | BcMedia::Pframe(BcMediaPframe{data, microseconds,..}) => {
|
||||
if let Some(app) = thread_vid.as_ref() {
|
||||
check_live(app)?; // Stop if appsrc is dropped
|
||||
let delta = if prev_vid_ms > microseconds {
|
||||
0
|
||||
} else {
|
||||
microseconds - prev_vid_ms
|
||||
};
|
||||
prev_vid_ms = microseconds;
|
||||
vid_time = vid_time.wrapping_add(delta as u64);
|
||||
thread_vid_data_tx.send(
|
||||
StreamData::Media{
|
||||
data,
|
||||
ts: Duration::from_micros(vid_time)
|
||||
})?;
|
||||
log::trace!("Sent Vid Frame");
|
||||
}
|
||||
}
|
||||
BcMedia::Aac(BcMediaAac{data, ..}) | BcMedia::Adpcm(BcMediaAdpcm{data,..}) => {
|
||||
if let Some(app) = thread_aud.as_ref() {
|
||||
check_live(app)?; // Stop if appsrc is dropped
|
||||
thread_aud_data_tx.send(
|
||||
StreamData::Media{
|
||||
data,
|
||||
ts: Duration::from_micros(vid_time)
|
||||
})?;
|
||||
log::trace!("Sent Aud Frame");
|
||||
}
|
||||
}
|
||||
_ => {},
|
||||
}
|
||||
// Done now sit on the receiver and push through the vid to the app sources
|
||||
let stream_cancel = CancellationToken::new();
|
||||
let mut set = JoinSet::new();
|
||||
while let Some(mut client_data) = client_rx.recv().await {
|
||||
log::trace!("New media");
|
||||
// New media created
|
||||
let (vid, mut vid_seek) = client_data
|
||||
.vid
|
||||
.take()
|
||||
.map_or((None, None), |data| (Some(data.app), Some(data.msg)));
|
||||
let (aud, mut aud_seek) = client_data
|
||||
.aud
|
||||
.take()
|
||||
.map_or((None, None), |data| (Some(data.app), Some(data.msg)));
|
||||
|
||||
// This is the data that gets sent to gstreamer thread
|
||||
// It represents the combination of the camera stream and the appsrc seek messages
|
||||
let (aud_data_tx, aud_data_rx) = broadcast(100);
|
||||
let (vid_data_tx, vid_data_rx) = broadcast(100);
|
||||
|
||||
// This thread takes the video data from the cam and passed it into the stream
|
||||
let mut vidstream = BroadcastStream::new(vidstream.resubscribe());
|
||||
let thread_vid_data_tx = vid_data_tx.clone();
|
||||
let thread_stream_cancel = stream_cancel.clone();
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_stream_cancel.cancelled() => AnyResult::Ok(()),
|
||||
v = async {
|
||||
while let Some(data) = vidstream.next().await {
|
||||
if let Ok(data) = data {
|
||||
thread_vid_data_tx.send(
|
||||
StreamData::Media {
|
||||
data: data.data,
|
||||
ts: data.ts
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
} => v,
|
||||
};
|
||||
log::trace!("Stream Thread End: {:?}", r);
|
||||
if let Some(app) = thread_vid.as_ref() {
|
||||
let _ = app.end_of_stream();
|
||||
)?;
|
||||
}
|
||||
if let Some(app) = thread_aud.as_ref() {
|
||||
let _ = app.end_of_stream();
|
||||
// Ignore broadcast lag errors
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
} => v
|
||||
};
|
||||
log::trace!("Stream Vid Media End {r:?}");
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
|
||||
// This thread takes the audio data from the cam and passed it into the stream
|
||||
let mut audstream = BroadcastStream::new(audstream.resubscribe());
|
||||
let thread_stream_cancel = stream_cancel.clone();
|
||||
let thread_aud_data_tx = aud_data_tx.clone();
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_stream_cancel.cancelled() => AnyResult::Ok(()),
|
||||
v = async {
|
||||
while let Some(data) = audstream.next().await {
|
||||
if let Ok(data) = data {
|
||||
thread_aud_data_tx.send(
|
||||
StreamData::Media {
|
||||
data: data.data,
|
||||
ts: data.ts
|
||||
}
|
||||
)?;
|
||||
}
|
||||
r
|
||||
});
|
||||
// Ignore broadcast lag errors
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
} => v,
|
||||
};
|
||||
log::trace!("Stream Aud Media End: {r:?}");
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
|
||||
|
||||
// Handles the seek commands
|
||||
set.spawn(async move {
|
||||
// This thread takes the seek data for the vid and passed it into the stream
|
||||
let thread_stream_cancel = stream_cancel.clone();
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_stream_cancel.cancelled() => AnyResult::Ok(()),
|
||||
v = async {
|
||||
if let Some(vid_seek) = vid_seek.as_mut() {
|
||||
while let Some(data) = vid_seek.recv().await {
|
||||
vid_data_tx.send(data)?;
|
||||
}
|
||||
log::trace!("Stream Vid Seek End");
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
set.spawn(async move {
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
} => v,
|
||||
};
|
||||
log::trace!("Stream Vid Seek End: {r:?}");
|
||||
r
|
||||
});
|
||||
|
||||
// This thread takes the seek data for the aud and passed it into the stream
|
||||
let thread_stream_cancel = stream_cancel.clone();
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_stream_cancel.cancelled() => AnyResult::Ok(()),
|
||||
v = async {
|
||||
if let Some(aud_seek) = aud_seek.as_mut() {
|
||||
while let Some(data) = aud_seek.recv().await {
|
||||
aud_data_tx.send(data)?;
|
||||
}
|
||||
log::trace!("Stream Aud Seek End");
|
||||
AnyResult::Ok(())
|
||||
});
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
} => v
|
||||
};
|
||||
log::trace!("Stream Aud Seek End: {r:?}");
|
||||
r
|
||||
});
|
||||
|
||||
// Handles the sending the video data into gstreamer
|
||||
let thread_stream_cancel = stream_cancel.clone();
|
||||
let vid_data_rx = BroadcastStream::new(vid_data_rx).filter(|f| f.is_ok()); // Filter to ignore lagged
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_stream_cancel.cancelled() => {
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
v = handle_data(vid.as_ref(), vid_data_rx) => v,
|
||||
};
|
||||
log::trace!("Vid Thread End: {:?}", r);
|
||||
r
|
||||
});
|
||||
// Handles sending the video data into gstreamer
|
||||
let thread_stream_cancel = stream_cancel.clone();
|
||||
let vid_data_rx = BroadcastStream::new(vid_data_rx).filter(|f| f.is_ok()); // Filter to ignore lagged
|
||||
let thread_vid = vid.clone();
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_stream_cancel.cancelled() => {
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
v = handle_data(thread_vid.as_ref(), vid_data_rx) => v,
|
||||
};
|
||||
log::trace!("Vid Thread End: {:?}", r);
|
||||
r
|
||||
});
|
||||
|
||||
// Handles the audio data
|
||||
let thread_stream_cancel = stream_cancel.clone();
|
||||
let aud_data_rx = BroadcastStream::new(aud_data_rx).filter(|f| f.is_ok()); // Filter to ignore lagged
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_stream_cancel.cancelled() => {
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
v = handle_data(aud.as_ref(), aud_data_rx) => v,
|
||||
};
|
||||
log::trace!("Aud Thread End: {:?}", r);
|
||||
r
|
||||
});
|
||||
}
|
||||
// At this point the factory has been destroyed
|
||||
// Cancel any remaining threads that are trying to send data
|
||||
// Although it should be finished already when the appsrcs are dropped
|
||||
stream_cancel.cancel();
|
||||
while set.join_next().await.is_some() {
|
||||
|
||||
}
|
||||
log::trace!("Stream done");
|
||||
AnyResult::Ok(())
|
||||
} => v,
|
||||
};
|
||||
// Handles the audio data into gstreamer
|
||||
let thread_stream_cancel = stream_cancel.clone();
|
||||
let aud_data_rx = BroadcastStream::new(aud_data_rx).filter(|f| f.is_ok()); // Filter to ignore lagged
|
||||
let thread_aud = aud.clone();
|
||||
set.spawn(async move {
|
||||
let r = tokio::select! {
|
||||
_ = thread_stream_cancel.cancelled() => {
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
v = handle_data(thread_aud.as_ref(), aud_data_rx) => v,
|
||||
};
|
||||
log::trace!("Aud Thread End: {:?}", r);
|
||||
r
|
||||
});
|
||||
}
|
||||
// At this point the factory has been destroyed
|
||||
// Cancel any remaining threads that are trying to send data
|
||||
// Although it should be finished already when the appsrcs are dropped
|
||||
stream_cancel.cancel();
|
||||
while set.join_next().await.is_some() {}
|
||||
log::trace!("Stream done");
|
||||
AnyResult::Ok(())
|
||||
}
|
||||
|
||||
async fn make_factory(
|
||||
stream_config: &StreamConfig,
|
||||
) -> AnyResult<(NeoMediaFactory, MpscReceiver<ClientData>)> {
|
||||
let (client_tx, client_rx) = mpsc(100);
|
||||
let factory = {
|
||||
let stream_config = stream_config.clone();
|
||||
NeoMediaFactory::new_with_callback(move |element| {
|
||||
clear_bin(&element)?;
|
||||
let (vid_seek_tx, vid_seek_rx) = mpsc(10);
|
||||
let (aud_seek_tx, aud_seek_rx) = mpsc(10);
|
||||
let vid = match stream_config.vid_format {
|
||||
VidFormat::None => {
|
||||
build_unknown(&element)?;
|
||||
AnyResult::Ok(None)
|
||||
}
|
||||
VidFormat::H264 => {
|
||||
let app = build_h264(&element)?;
|
||||
app.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.seek_data(move |_, seek_pos| {
|
||||
log::info!("seek_pos: {seek_pos:?}");
|
||||
let (reply_tx, mut reply_rx) = mpsc(1);
|
||||
vid_seek_tx
|
||||
.blocking_send(StreamData::Seek {
|
||||
ts: Duration::from_micros(seek_pos),
|
||||
reply: reply_tx,
|
||||
})
|
||||
.is_ok()
|
||||
&& reply_rx.blocking_recv().is_some()
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
AnyResult::Ok(Some(app))
|
||||
}
|
||||
VidFormat::H265 => {
|
||||
let app = build_h265(&element)?;
|
||||
app.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.seek_data(move |_, seek_pos| {
|
||||
log::info!("seek_pos: {seek_pos:?}");
|
||||
let (reply_tx, mut reply_rx) = mpsc(1);
|
||||
vid_seek_tx
|
||||
.blocking_send(StreamData::Seek {
|
||||
ts: Duration::from_micros(seek_pos),
|
||||
reply: reply_tx,
|
||||
})
|
||||
.is_ok()
|
||||
&& reply_rx.blocking_recv().is_some()
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
AnyResult::Ok(Some(app))
|
||||
}
|
||||
}?;
|
||||
let aud = if matches!(stream_config.vid_format, VidFormat::None) {
|
||||
None
|
||||
} else {
|
||||
match stream_config.aud_format {
|
||||
AudFormat::None => AnyResult::Ok(None),
|
||||
AudFormat::Aac => {
|
||||
let app = build_aac(&element)?;
|
||||
app.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.seek_data(move |_, seek_pos| {
|
||||
log::info!("seek_pos: {seek_pos:?}");
|
||||
let (reply_tx, mut reply_rx) = mpsc(1);
|
||||
aud_seek_tx
|
||||
.blocking_send(StreamData::Seek {
|
||||
ts: Duration::from_micros(seek_pos),
|
||||
reply: reply_tx,
|
||||
})
|
||||
.is_ok()
|
||||
&& reply_rx.blocking_recv().is_some()
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
AnyResult::Ok(Some(app))
|
||||
}
|
||||
AudFormat::Adpcm(block_size) => {
|
||||
let app = build_adpcm(&element, block_size)?;
|
||||
app.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.seek_data(move |_, seek_pos| {
|
||||
log::info!("seek_pos: {seek_pos:?}");
|
||||
let (reply_tx, mut reply_rx) = mpsc(1);
|
||||
aud_seek_tx
|
||||
.blocking_send(StreamData::Seek {
|
||||
ts: Duration::from_micros(seek_pos),
|
||||
reply: reply_tx,
|
||||
})
|
||||
.is_ok()
|
||||
&& reply_rx.blocking_recv().is_some()
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
AnyResult::Ok(Some(app))
|
||||
}
|
||||
}?
|
||||
};
|
||||
|
||||
client_tx.blocking_send(ClientData {
|
||||
vid: match (vid, vid_seek_rx) {
|
||||
(Some(app), msg) => Some(ClientSourceData { app, msg }),
|
||||
_ => None,
|
||||
},
|
||||
aud: match (aud, aud_seek_rx) {
|
||||
(Some(app), msg) => Some(ClientSourceData { app, msg }),
|
||||
_ => None,
|
||||
},
|
||||
})?;
|
||||
Ok(Some(element))
|
||||
})
|
||||
.await
|
||||
}?;
|
||||
|
||||
Ok((factory, client_rx))
|
||||
}
|
||||
|
||||
async fn handle_data<T: Stream<Item = Result<StreamData, E>> + Unpin, E>(
|
||||
|
||||
Reference in new issue
Block a user