Restucture of rtsp crate into module
This commit is contained in:
12 files changed
+60
-84
No files matched your search
@@ -1,36 +0,0 @@
|
||||
[package]
|
||||
name = "neolink_rtsp"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.4.0"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
neolink_core = { path = "../core", version = "0.4.0" }
|
||||
aes = "0.6"
|
||||
cfb-mode = "0.6"
|
||||
cookie-factory = "0.3"
|
||||
crossbeam = "0.7"
|
||||
err-derive = "0.2"
|
||||
glib = ">=0.10.3"
|
||||
gio = "0.9"
|
||||
gstreamer = "0.16"
|
||||
gstreamer-app = "0.16"
|
||||
gstreamer-rtsp = "0.16"
|
||||
gstreamer-rtsp-server = { version = "0.16", features = ["v1_12", "v1_14"]}
|
||||
lazy_static = "1.4"
|
||||
log = { version = "0.4" }
|
||||
itertools = "0.9"
|
||||
md5 = "0.7"
|
||||
nom = "6.1.2"
|
||||
regex = "1"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
socket2 = "0.3"
|
||||
structopt = "0.3"
|
||||
time = "0.2"
|
||||
toml = "0.5"
|
||||
yaserde = "0.3.16"
|
||||
yaserde_derive = "0.3.16"
|
||||
xml-rs = "0.8"
|
||||
validator = "0.10"
|
||||
validator_derive = "0.10"
|
||||
@@ -1,247 +0,0 @@
|
||||
/*
|
||||
This is a rust implementation of OKI and DVI/IMA ADPCM.
|
||||
*/
|
||||
use super::errors::Error;
|
||||
use log::error;
|
||||
use std::convert::TryInto;
|
||||
|
||||
struct AdpcmSetup {
|
||||
max_step_index: u32,
|
||||
steps: &'static [u32],
|
||||
max_sample_size: i32,
|
||||
changes: &'static [i32],
|
||||
}
|
||||
|
||||
impl AdpcmSetup {
|
||||
// Unused, originally we thought BC might be using OKI but it is actually DVI4
|
||||
#[allow(dead_code)]
|
||||
fn new_oki() -> Self {
|
||||
Self {
|
||||
max_step_index: 48,
|
||||
steps: &[
|
||||
16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97,
|
||||
107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449,
|
||||
494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552,
|
||||
],
|
||||
changes: &[-1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8],
|
||||
max_sample_size: 2048,
|
||||
}
|
||||
}
|
||||
|
||||
// This is IMA format, but it is the same as DVI4 format except in the block header
|
||||
fn new_ima() -> Self {
|
||||
Self {
|
||||
max_step_index: 88,
|
||||
steps: &[
|
||||
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50,
|
||||
55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279,
|
||||
307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282,
|
||||
1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871,
|
||||
5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818,
|
||||
18500, 20350, 22385, 24623, 27086, 29794, 32767,
|
||||
],
|
||||
changes: &[-1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8],
|
||||
max_sample_size: 32768,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Nibble {
|
||||
// A nibble is a 4bit int
|
||||
data: u8, // This is the raw data for the nibble
|
||||
}
|
||||
|
||||
impl Nibble {
|
||||
// Use u/i32 throughout to ensure that we always have enough
|
||||
// Headroom to do the math without needing `as` casting everywhere
|
||||
fn unsigned(&self) -> u32 {
|
||||
(self.data & 0b00001111) as u32 // Mask first 4 bits it just to be sure its in nibble range
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn signed_magnitude(&self) -> u32 {
|
||||
(self.data & 0b00000111) as u32 // Mask of first 3 bits which are the magnitiude bits in signed int
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn signed(&self) -> i32 {
|
||||
match self.data & 0b00001000 {
|
||||
// Sign bit is at the 4th bit
|
||||
0b00001000 => -(self.signed_magnitude() as i32),
|
||||
_ => self.signed_magnitude() as i32,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_byte(byte: &u8) -> [Self; 2] {
|
||||
// Two nibbles per byte
|
||||
[
|
||||
Self {
|
||||
data: (byte & 0b11110000) >> 4,
|
||||
},
|
||||
Self {
|
||||
data: byte & 0b00001111,
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn adpcm_to_pcm(bytes: &[u8]) -> Result<Vec<u8>, Error> {
|
||||
let context = AdpcmSetup::new_ima();
|
||||
|
||||
let mut result: Vec<u8> = vec![]; // Stores the PCM byte array
|
||||
|
||||
// ADPCM is not really a streamable format
|
||||
// Each audio sample requires information on the previous sample
|
||||
// To solve this reolink caches the intermediate variables (step_index and last_output)
|
||||
// Into the block header in the stream. When ever an adpcm packet arrives it starts with
|
||||
// 0x0001 which is the frame time from HISilicon documentation (I think) following by
|
||||
// 0xWW which is half the block size
|
||||
// 0xYY which is the last output
|
||||
// 0xZZ which is the step index of the last output
|
||||
// We must initialise our decoder with this data
|
||||
|
||||
if bytes.len() < 4 {
|
||||
error!("ADPCM data is too short for even the magic.");
|
||||
return Err(Error::AdpcmDecodingError(
|
||||
"ADPCM data is too short for even the magic.",
|
||||
));
|
||||
}
|
||||
|
||||
// Check for valid number of frame type
|
||||
let frame_type_bytes = &bytes[0..2];
|
||||
const FRAME_TYPE_HISILICON: &[u8] = &[0x00, 0x01];
|
||||
if frame_type_bytes != FRAME_TYPE_HISILICON {
|
||||
error!("Unexpected ADPCM frame type: {:x?}", frame_type_bytes);
|
||||
return Err(Error::AdpcmDecodingError("Unexpected ADPCM frame type"));
|
||||
}
|
||||
|
||||
// Check for valid block size
|
||||
let block_size_bytes = &bytes[2..4];
|
||||
let block_size = (u16::from_le_bytes(
|
||||
block_size_bytes
|
||||
.try_into()
|
||||
.expect("slice with incorrect length"),
|
||||
) as u32)
|
||||
* 2; // Block size is stored as 1/2 (don't know why)
|
||||
let full_block_size = block_size + 4; // block_size + magic (2 bytes) + size (2 bytes)
|
||||
if !bytes.len() % full_block_size as usize == 0 {
|
||||
error!("ADPCM Data is not a multiple of the block size");
|
||||
return Err(Error::AdpcmDecodingError(
|
||||
"ADPCM block size does not match data length.",
|
||||
));
|
||||
}
|
||||
|
||||
// Chunk on block size
|
||||
for bytes in bytes.chunks(full_block_size as usize) {
|
||||
// Get predictor state from block header using DVI 4 format.
|
||||
if bytes.len() < 8 {
|
||||
error!("ADPCM Block size is not long enough for header");
|
||||
return Err(Error::AdpcmDecodingError(
|
||||
"ADPCM has insufficent block size",
|
||||
));
|
||||
}
|
||||
let step_output_bytes = &bytes[4..6];
|
||||
let mut last_output = i16::from_le_bytes(
|
||||
step_output_bytes
|
||||
.try_into()
|
||||
.expect("slice with incorrect length"),
|
||||
) as i32;
|
||||
let step_index_bytes = &bytes[6..8];
|
||||
let mut step_index = u16::from_le_bytes(
|
||||
step_index_bytes
|
||||
.try_into()
|
||||
.expect("slice with incorrect length"),
|
||||
) as i32;
|
||||
|
||||
// To avoid casting to u8 <-> u16 <-> u32 and back all the time I just do all maths in u/i32
|
||||
// This gives enough headroom to do all calculations without overflow because adpcm puts artifical
|
||||
// limits on the sample sizes
|
||||
let mut step: u32;
|
||||
|
||||
// The rest is all data to be decoded
|
||||
let data = &bytes[8..];
|
||||
|
||||
for byte in data {
|
||||
let nibbles: [Nibble; 2] = Nibble::from_byte(byte);
|
||||
for nibble in &nibbles {
|
||||
let unibble = nibble.unsigned();
|
||||
|
||||
// Specifications say: Clamp it in max index range 0..context.max_step_index
|
||||
step_index = match step_index {
|
||||
n if n < 0 => 0,
|
||||
n if n > context.max_step_index as i32 => context.max_step_index as i32,
|
||||
n => n,
|
||||
};
|
||||
|
||||
// This is just Eulers approximation with a variable step size
|
||||
// **Adaptive** Differential PCM
|
||||
// Adaptive: because the step size is variable
|
||||
step = context.steps[step_index as usize];
|
||||
|
||||
let raw_sample;
|
||||
/* == Non approxiate version ===
|
||||
// This is the full maths version
|
||||
// We don't use this one as we need to match the way the encoder
|
||||
// works if we want to use the state stored in the header.
|
||||
// I have Left it here as it is easier to understand then the bit shift version below
|
||||
let inibble = nibble.signed();
|
||||
|
||||
// Calculate the delta (which is really what adpcm is all about)
|
||||
// Adaptive **Differential** PCM
|
||||
// Differential: Becuase its all about the difference (gradient)
|
||||
let diff = (step as i32) * (inibble) / 2 + (step as i32) / 8;
|
||||
|
||||
// Eulers approxiation
|
||||
// Sample = Previous_Sample + difference*step_size
|
||||
raw_sample = last_output + diff;
|
||||
*/
|
||||
|
||||
// === Approximate version ==
|
||||
// Approximate form uses bit shift operators.
|
||||
// This is a legacy of the days when mult/divides were expensive
|
||||
// It is also the format used on low end CPUs like cameras
|
||||
let mut diff = step >> 3;
|
||||
if (unibble & 0b0100) == 0b0100 {
|
||||
diff += step;
|
||||
}
|
||||
if (unibble & 0b0010) == 0b0010 {
|
||||
diff += step >> 1;
|
||||
}
|
||||
if (unibble & 0b0001) == 0b0001 {
|
||||
diff += step >> 2;
|
||||
}
|
||||
// Sign test
|
||||
if (unibble & 0b1000) == 0b1000 {
|
||||
raw_sample = last_output - (diff as i32);
|
||||
} else {
|
||||
raw_sample = last_output + (diff as i32);
|
||||
}
|
||||
|
||||
// Specifications say: Clamp it in max sample range -context.max_sample_size..context.max_sample_size
|
||||
let sample = match raw_sample {
|
||||
value if value > context.max_sample_size - 1 => context.max_sample_size - 1,
|
||||
value if value < -context.max_sample_size => -context.max_sample_size,
|
||||
value => value,
|
||||
};
|
||||
|
||||
// PCM is really in i16 range
|
||||
// Some formats e.g. OKI are not in the full PCM range of values
|
||||
// To convert we must scale it to the i16 range
|
||||
// We also cast to i16 at this point ready for the conversion to u8 bytes of the output
|
||||
let scaled_sample = (sample as i32 * (std::i16::MAX as i32)
|
||||
/ (context.max_sample_size - 1) as i32)
|
||||
as i16;
|
||||
|
||||
// Get the results in bytes
|
||||
result.extend(scaled_sample.to_le_bytes().iter());
|
||||
|
||||
// Increment the step index
|
||||
step_index = step_index as i32 + context.changes[unibble as usize];
|
||||
|
||||
// cache the last_output ready for next run
|
||||
last_output = sample;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
use std::path::PathBuf;
|
||||
use structopt::StructOpt;
|
||||
|
||||
/// The command line for the rtsp subcommand
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct Opt {
|
||||
/// The path to the config file
|
||||
#[structopt(short, long, parse(from_os_str))]
|
||||
pub config: PathBuf,
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use std::time::Duration;
|
||||
use validator::{Validate, ValidationError};
|
||||
use validator_derive::Validate;
|
||||
|
||||
lazy_static! {
|
||||
static ref RE_STREAM_SRC: Regex = Regex::new(r"^(mainStream|subStream|both)$").unwrap();
|
||||
static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap();
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct Config {
|
||||
#[validate]
|
||||
pub(crate) cameras: Vec<CameraConfig>,
|
||||
|
||||
#[serde(rename = "bind", default = "default_bind_addr")]
|
||||
pub(crate) bind_addr: String,
|
||||
|
||||
#[validate(range(min = 0, max = 65535, message = "Invalid port", code = "bind_port"))]
|
||||
#[serde(default = "default_bind_port")]
|
||||
pub(crate) bind_port: u16,
|
||||
|
||||
#[serde(default = "default_certificate")]
|
||||
pub(crate) certificate: Option<String>,
|
||||
|
||||
#[validate(regex(
|
||||
path = "RE_TLS_CLIENT_AUTH",
|
||||
message = "Incorrect tls auth",
|
||||
code = "tls_client_auth"
|
||||
))]
|
||||
#[serde(default = "default_tls_client_auth")]
|
||||
pub(crate) tls_client_auth: String,
|
||||
|
||||
#[validate]
|
||||
#[serde(default)]
|
||||
pub(crate) users: Vec<UserConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct CameraConfig {
|
||||
pub(crate) name: String,
|
||||
|
||||
#[serde(rename = "address")]
|
||||
pub(crate) camera_addr: String,
|
||||
|
||||
pub(crate) username: String,
|
||||
pub(crate) password: Option<String>,
|
||||
|
||||
// no longer used, but still here so we can warn users:
|
||||
pub(crate) timeout: Option<Duration>,
|
||||
|
||||
// no longer used, but still here so we can warn users:
|
||||
pub(crate) format: Option<String>,
|
||||
|
||||
#[validate(regex(
|
||||
path = "RE_STREAM_SRC",
|
||||
message = "Incorrect stream source",
|
||||
code = "stream"
|
||||
))]
|
||||
#[serde(default = "default_stream")]
|
||||
pub(crate) stream: String,
|
||||
|
||||
pub(crate) permitted_users: Option<Vec<String>>,
|
||||
|
||||
#[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))]
|
||||
#[serde(default = "default_channel_id")]
|
||||
pub(crate) channel_id: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct UserConfig {
|
||||
#[validate(custom = "validate_username")]
|
||||
#[serde(alias = "username")]
|
||||
pub(crate) name: String,
|
||||
|
||||
#[serde(alias = "password")]
|
||||
pub(crate) pass: String,
|
||||
}
|
||||
|
||||
fn default_bind_addr() -> String {
|
||||
"0.0.0.0".to_string()
|
||||
}
|
||||
|
||||
fn default_bind_port() -> u16 {
|
||||
8554
|
||||
}
|
||||
|
||||
fn default_stream() -> String {
|
||||
"both".to_string()
|
||||
}
|
||||
|
||||
fn default_certificate() -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
fn default_tls_client_auth() -> String {
|
||||
"none".to_string()
|
||||
}
|
||||
|
||||
fn default_channel_id() -> u8 {
|
||||
0
|
||||
}
|
||||
|
||||
pub(crate) static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"];
|
||||
fn validate_username(name: &str) -> Result<(), ValidationError> {
|
||||
if name.trim().is_empty() {
|
||||
return Err(ValidationError::new("username cannot be empty"));
|
||||
}
|
||||
if RESERVED_NAMES.contains(&name) {
|
||||
return Err(ValidationError::new("This is a reserved username"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
use err_derive::Error;
|
||||
|
||||
/// The main error for the rtsp subcommand
|
||||
#[derive(Debug, Error)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum Error {
|
||||
/// Raised when the config file fails to deserlize
|
||||
#[error(display = "Configuration parsing error")]
|
||||
ConfigError(#[error(source)] toml::de::Error),
|
||||
/// Raised when `neolink_core` raises an error
|
||||
#[error(display = "Communication error")]
|
||||
ProtocolError(#[error(source)] neolink_core::Error),
|
||||
/// Raised when there is an IO error such as unable to find
|
||||
/// config file
|
||||
#[error(display = "I/O error")]
|
||||
IoError(#[error(source)] std::io::Error),
|
||||
/// Raised when the config file fails validataion
|
||||
#[error(display = "Validation error")]
|
||||
ValidationError(#[error(source)] validator::ValidationErrors),
|
||||
/// Raised when there is an ADPCM decoding error
|
||||
#[error(display = "ADPCM Decoding Error")]
|
||||
AdpcmDecodingError(&'static str),
|
||||
}
|
||||
@@ -1,351 +0,0 @@
|
||||
//! This module provides an "RtspServer" abstraction that allows consumers of its API to feed it
|
||||
//! data using an ordinary std::io::Write interface.
|
||||
pub(crate) use self::maybe_app_src::MaybeAppSrc;
|
||||
use super::adpcm::adpcm_to_pcm;
|
||||
use super::errors::Error;
|
||||
use gstreamer::prelude::Cast;
|
||||
use gstreamer::{Bin, Structure};
|
||||
use gstreamer_app::AppSrc;
|
||||
//use gstreamer_rtsp::RTSPLowerTrans;
|
||||
use gio::{TlsAuthenticationMode, TlsCertificate};
|
||||
use gstreamer_rtsp::RTSPAuthMethod;
|
||||
use gstreamer_rtsp_server::prelude::*;
|
||||
use gstreamer_rtsp_server::{
|
||||
RTSPAuth, RTSPMediaFactory, RTSPServer as GstRTSPServer, RTSPToken,
|
||||
RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT,
|
||||
RTSP_TOKEN_MEDIA_FACTORY_ROLE,
|
||||
};
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::{StreamFormat, StreamOutput, StreamOutputError};
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
|
||||
type Result<T> = std::result::Result<T, ()>;
|
||||
|
||||
pub(crate) struct RtspServer {
|
||||
server: GstRTSPServer,
|
||||
}
|
||||
|
||||
pub(crate) struct GstOutputs {
|
||||
pub(crate) audsrc: MaybeAppSrc,
|
||||
pub(crate) vidsrc: MaybeAppSrc,
|
||||
video_format: Option<StreamFormat>,
|
||||
audio_format: Option<StreamFormat>,
|
||||
factory: RTSPMediaFactory,
|
||||
}
|
||||
|
||||
impl StreamOutput for GstOutputs {
|
||||
fn write_audio(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError {
|
||||
self.set_format(Some(format));
|
||||
if let StreamFormat::ADPCM = format {
|
||||
let pcm = adpcm_to_pcm(data).map_err(|e| {
|
||||
if let Error::AdpcmDecodingError(msg) = e {
|
||||
neolink_core::Error::OtherString(format!("ADPCM decoding error: {}", msg))
|
||||
} else {
|
||||
neolink_core::Error::Other("Generic error during ADPCM decoding")
|
||||
}
|
||||
})?;
|
||||
self.vidsrc.write_all(&pcm)?;
|
||||
} else {
|
||||
self.vidsrc.write_all(data)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn write_video(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError {
|
||||
self.set_format(Some(format));
|
||||
self.vidsrc.write_all(data)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl GstOutputs {
|
||||
pub(crate) fn from_appsrcs(vidsrc: MaybeAppSrc, audsrc: MaybeAppSrc) -> GstOutputs {
|
||||
let result = GstOutputs {
|
||||
vidsrc,
|
||||
audsrc,
|
||||
video_format: None,
|
||||
audio_format: None,
|
||||
factory: RTSPMediaFactory::new(),
|
||||
};
|
||||
result.apply_format();
|
||||
result
|
||||
}
|
||||
|
||||
fn set_format(&mut self, format: Option<StreamFormat>) {
|
||||
match format {
|
||||
Some(StreamFormat::H264) | Some(StreamFormat::H265) => {
|
||||
if format != self.video_format {
|
||||
self.video_format = format;
|
||||
self.apply_format();
|
||||
}
|
||||
}
|
||||
Some(StreamFormat::AAC) | Some(StreamFormat::ADPCM) => {
|
||||
if format != self.audio_format {
|
||||
self.audio_format = format;
|
||||
self.apply_format();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_format(&self) {
|
||||
let launch_vid = match self.video_format {
|
||||
Some(StreamFormat::H264) => {
|
||||
"! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! h264parse ! rtph264pay name=pay0"
|
||||
}
|
||||
Some(StreamFormat::H265) => {
|
||||
"! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! h265parse ! rtph265pay name=pay0"
|
||||
}
|
||||
_ => "! fakesink",
|
||||
};
|
||||
|
||||
let launch_aud = match self.audio_format {
|
||||
Some(StreamFormat::ADPCM) => "! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! rawaudioparse format=pcm pcm-format=s16le sample-rate=8000 num-channels=1 interleaved=true ! audioconvert ! rtpL16pay name=pay1", // DVI4 is converted to pcm in the appsrc
|
||||
Some(StreamFormat::AAC) => "! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! aacparse ! decodebin ! audioconvert ! rtpL16pay name=pay1 name=pay1",
|
||||
_ => "! fakesink",
|
||||
};
|
||||
|
||||
self.factory.set_launch(
|
||||
&vec![
|
||||
"( ",
|
||||
"appsrc name=vidsrc is-live=true block=true emit-signals=false max-bytes=52428800 do-timestamp=true format=GST_FORMAT_TIME", // 50MB max size so that it won't grow to infinite if the queue blocks
|
||||
launch_vid,
|
||||
"appsrc name=audsrc is-live=true block=true emit-signals=false max-bytes=52428800 do-timestamp=true format=GST_FORMAT_TIME", // 50MB max size so that it won't grow to infinite if the queue blocks
|
||||
launch_aud,
|
||||
")"
|
||||
]
|
||||
.join(" "),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RtspServer {
|
||||
fn default() -> RtspServer {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl RtspServer {
|
||||
pub(crate) fn new() -> RtspServer {
|
||||
gstreamer::init().expect("Gstreamer should not explode");
|
||||
RtspServer {
|
||||
server: GstRTSPServer::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn add_stream(
|
||||
&self,
|
||||
paths: &[&str],
|
||||
permitted_users: &HashSet<&str>,
|
||||
) -> Result<GstOutputs> {
|
||||
let mounts = self
|
||||
.server
|
||||
.get_mount_points()
|
||||
.expect("The server should have mountpoints");
|
||||
|
||||
// Create a MaybeAppSrc: Write which we will give the caller. When the backing AppSrc is
|
||||
// created by the factory, fish it out and give it to the waiting MaybeAppSrc via the
|
||||
// channel it provided. This callback may be called more than once by Gstreamer if it is
|
||||
// unhappy with the pipeline, so keep updating the MaybeAppSrc.
|
||||
let (maybe_app_src, tx) = MaybeAppSrc::new_with_tx();
|
||||
let (maybe_app_src_aud, tx_aud) = MaybeAppSrc::new_with_tx();
|
||||
|
||||
let outputs = GstOutputs::from_appsrcs(maybe_app_src, maybe_app_src_aud);
|
||||
|
||||
let factory = &outputs.factory;
|
||||
|
||||
debug!(
|
||||
"Permitting {} to access {}",
|
||||
// This is hashmap or (iter) equivalent of join, it requres itertools
|
||||
itertools::Itertools::intersperse(permitted_users.iter().cloned(), ", ")
|
||||
.collect::<String>(),
|
||||
paths.join(", ")
|
||||
);
|
||||
self.add_permitted_roles(factory, permitted_users);
|
||||
|
||||
factory.set_shared(true);
|
||||
|
||||
factory.connect_media_configure(move |_factory, media| {
|
||||
debug!("RTSP: media was configured");
|
||||
let bin = media
|
||||
.get_element()
|
||||
.expect("Media should have an element")
|
||||
.dynamic_cast::<Bin>()
|
||||
.expect("Media source's element should be a bin");
|
||||
let app_src = bin
|
||||
.get_by_name_recurse_up("vidsrc")
|
||||
.expect("write_src must be present in created bin")
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.expect("Source element is expected to be an appsrc!");
|
||||
let _ = tx.send(app_src); // Receiver may be dropped, don't panic if so
|
||||
|
||||
let app_src_aud = bin
|
||||
.get_by_name_recurse_up("audsrc")
|
||||
.expect("write_src must be present in created bin")
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.expect("Source element is expected to be an appsrc!");
|
||||
let _ = tx_aud.send(app_src_aud); // Receiver may be dropped, don't panic if so
|
||||
});
|
||||
|
||||
for path in paths {
|
||||
mounts.add_factory(path, factory);
|
||||
}
|
||||
|
||||
Ok(outputs)
|
||||
}
|
||||
|
||||
pub(crate) fn add_permitted_roles(
|
||||
&self,
|
||||
factory: &RTSPMediaFactory,
|
||||
permitted_roles: &HashSet<&str>,
|
||||
) {
|
||||
for permitted_role in permitted_roles {
|
||||
factory.add_role_from_structure(&Structure::new(
|
||||
permitted_role,
|
||||
&[
|
||||
(*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true),
|
||||
(*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true),
|
||||
],
|
||||
));
|
||||
}
|
||||
// During auth, first it binds anonymously. At this point it checks
|
||||
// RTSP_PERM_MEDIA_FACTORY_ACCESS to see if anyone can connect
|
||||
// This is done before the auth token is loaded, possibliy an upstream bug there
|
||||
// After checking RTSP_PERM_MEDIA_FACTORY_ACCESS anonymously
|
||||
// It loads the auth token of the user and checks that users
|
||||
// RTSP_PERM_MEDIA_FACTORY_CONSTRUCT allowing them to play
|
||||
// As a result of this we must ensure that if anonymous is not granted RTSP_PERM_MEDIA_FACTORY_ACCESS
|
||||
// As a part of permitted users then we must allow it to access
|
||||
// at least RTSP_PERM_MEDIA_FACTORY_ACCESS but not RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
|
||||
// Watching Actually happens during RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
|
||||
// So this should be OK to do.
|
||||
// FYI: If no RTSP_PERM_MEDIA_FACTORY_ACCESS then server returns 404 not found
|
||||
// If yes RTSP_PERM_MEDIA_FACTORY_ACCESS but no RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
|
||||
// server returns 401 not authourised
|
||||
if !permitted_roles.contains(&"anonymous") {
|
||||
factory.add_role_from_structure(&Structure::new(
|
||||
"anonymous",
|
||||
&[(*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true)],
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_credentials(&self, credentials: &[(&str, &str)]) -> Result<()> {
|
||||
let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new);
|
||||
auth.set_supported_methods(RTSPAuthMethod::Basic);
|
||||
|
||||
let mut un_authtoken = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"anonymous")]);
|
||||
auth.set_default_token(Some(&mut un_authtoken));
|
||||
|
||||
for credential in credentials {
|
||||
let (user, pass) = credential;
|
||||
trace!("Setting credentials for user {}", user);
|
||||
let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]);
|
||||
let basic = RTSPAuth::make_basic(user, pass);
|
||||
auth.add_basic(basic.as_str(), &token);
|
||||
}
|
||||
|
||||
self.server.set_auth(Some(&auth));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn set_tls(
|
||||
&self,
|
||||
cert_file: &str,
|
||||
client_auth: TlsAuthenticationMode,
|
||||
) -> Result<()> {
|
||||
debug!("Setting up TLS using {}", cert_file);
|
||||
let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new);
|
||||
|
||||
// We seperate reading the file and changing to a PEM so that we get different error messages.
|
||||
let cert_contents = fs::read_to_string(cert_file).expect("TLS file not found");
|
||||
let cert = TlsCertificate::from_pem(&cert_contents).expect("Not a valid TLS certificate");
|
||||
auth.set_tls_certificate(Some(&cert));
|
||||
auth.set_tls_authentication_mode(client_auth);
|
||||
|
||||
self.server.set_auth(Some(&auth));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn run(&self, bind_addr: &str, bind_port: u16) {
|
||||
self.server.set_address(bind_addr);
|
||||
self.server.set_service(&format!("{}", bind_port));
|
||||
// Attach server to default Glib context
|
||||
self.server.attach(None);
|
||||
|
||||
// Run the Glib main loop.
|
||||
let main_loop = glib::MainLoop::new(None, false);
|
||||
main_loop.run();
|
||||
}
|
||||
}
|
||||
|
||||
mod maybe_app_src {
|
||||
use super::*;
|
||||
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
|
||||
|
||||
/// A Write implementation around AppSrc that also allows delaying the creation of the AppSrc
|
||||
/// until later, discarding written data until the AppSrc is provided.
|
||||
pub(crate) struct MaybeAppSrc {
|
||||
rx: Receiver<AppSrc>,
|
||||
app_src: Option<AppSrc>,
|
||||
}
|
||||
|
||||
impl MaybeAppSrc {
|
||||
/// Creates a MaybeAppSrc. Also returns a Sender that you must use to provide an AppSrc as
|
||||
/// soon as one is available. When it is received, the MaybeAppSrc will start pushing data
|
||||
/// into the AppSrc when write() is called.
|
||||
pub(crate) fn new_with_tx() -> (Self, SyncSender<AppSrc>) {
|
||||
let (tx, rx) = sync_channel(3); // The sender should not send very often
|
||||
(MaybeAppSrc { rx, app_src: None }, tx)
|
||||
}
|
||||
|
||||
/// Flushes data to Gstreamer on a problem communicating with the underlying video source.
|
||||
pub(crate) fn on_stream_error(&mut self) {
|
||||
if let Some(src) = self.try_get_src() {
|
||||
// Ignore "errors" from Gstreamer such as FLUSHING, which are not really errors.
|
||||
let _ = src.end_of_stream();
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to retrieve the AppSrc that should be passed in by the caller of new_with_tx
|
||||
/// at some point after this struct has been created. At that point, we swap over to
|
||||
/// owning the AppSrc directly. This function handles either case and returns the AppSrc,
|
||||
/// or None if the caller has not yet sent one.
|
||||
fn try_get_src(&mut self) -> Option<&AppSrc> {
|
||||
while let Some(src) = self.rx.try_recv().ok() {
|
||||
self.app_src = Some(src);
|
||||
}
|
||||
self.app_src.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for MaybeAppSrc {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
// If we have no AppSrc yet, throw away the data and claim that it was written
|
||||
let app_src = match self.try_get_src() {
|
||||
Some(src) => src,
|
||||
None => return Ok(buf.len()),
|
||||
};
|
||||
|
||||
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf);
|
||||
}
|
||||
|
||||
let res = app_src.push_buffer(gst_buf); //.map_err(|e| io::Error::new(io::ErrorKind::Other, Box::new(e)))?;
|
||||
if res.is_err() {
|
||||
self.app_src = None;
|
||||
}
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,271 +0,0 @@
|
||||
#![warn(missing_docs)]
|
||||
//!
|
||||
//! # Neolink RTSP
|
||||
//!
|
||||
//! This crate serves as the rtsp source for the
|
||||
//! `neolink rtsp` subcommand
|
||||
//!
|
||||
use gio::TlsAuthenticationMode;
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::BcCamera;
|
||||
use neolink_core::Never;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use validator::Validate;
|
||||
|
||||
mod adpcm;
|
||||
/// The command line parameters for this subcommand
|
||||
pub mod cmdline;
|
||||
mod config;
|
||||
/// The errors this subcommand can raise
|
||||
pub mod errors;
|
||||
mod gst;
|
||||
|
||||
use cmdline::Opt;
|
||||
use config::{CameraConfig, Config, UserConfig};
|
||||
use errors::Error;
|
||||
use gst::{GstOutputs, RtspServer};
|
||||
|
||||
/// Entry point for the rtsp subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
|
||||
|
||||
config.validate()?;
|
||||
|
||||
let rtsp = &RtspServer::new();
|
||||
|
||||
set_up_tls(&config, rtsp);
|
||||
|
||||
set_up_users(&config.users, rtsp);
|
||||
|
||||
if config.certificate == None && !config.users.is_empty() {
|
||||
warn!(
|
||||
"Without a server certificate, usernames and passwords will be exchanged in plaintext!"
|
||||
)
|
||||
}
|
||||
|
||||
crossbeam::scope(|s| {
|
||||
for camera in config.cameras {
|
||||
if camera.format.is_some() {
|
||||
warn!("The format config option of the camera has been removed in favour of auto detection.")
|
||||
}
|
||||
// Let subthreads share the camera object; in principle I think they could share
|
||||
// the object as it sits in the config.cameras block, but I have not figured out the
|
||||
// syntax for that.
|
||||
let arc_cam = Arc::new(camera);
|
||||
|
||||
let permitted_users =
|
||||
get_permitted_users(config.users.as_slice(), &arc_cam.permitted_users);
|
||||
|
||||
// Set up each main and substream according to all the RTSP mount paths we support
|
||||
if ["both", "mainStream"].iter().any(|&e| e == arc_cam.stream) {
|
||||
let paths = &[
|
||||
&*format!("/{}", arc_cam.name),
|
||||
&*format!("/{}/mainStream", arc_cam.name),
|
||||
];
|
||||
let mut outputs = rtsp
|
||||
.add_stream(paths, &permitted_users)
|
||||
.unwrap();
|
||||
let main_camera = arc_cam.clone();
|
||||
s.spawn(move |_| camera_loop(&*main_camera, "mainStream", &mut outputs, true));
|
||||
}
|
||||
if ["both", "subStream"].iter().any(|&e| e == arc_cam.stream) {
|
||||
let paths = &[&*format!("/{}/subStream", arc_cam.name)];
|
||||
let mut outputs = rtsp
|
||||
.add_stream(paths, &permitted_users)
|
||||
.unwrap();
|
||||
let sub_camera = arc_cam.clone();
|
||||
let manage = arc_cam.stream == "subStream";
|
||||
s.spawn(move |_| camera_loop(&*sub_camera, "subStream", &mut outputs, manage));
|
||||
}
|
||||
}
|
||||
|
||||
rtsp.run(&config.bind_addr, config.bind_port);
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn camera_loop(
|
||||
camera_config: &CameraConfig,
|
||||
stream_name: &str,
|
||||
outputs: &mut GstOutputs,
|
||||
manage: bool,
|
||||
) -> Result<Never, Error> {
|
||||
let min_backoff = Duration::from_secs(1);
|
||||
let max_backoff = Duration::from_secs(15);
|
||||
let mut current_backoff = min_backoff;
|
||||
|
||||
loop {
|
||||
let cam_err = camera_main(camera_config, stream_name, outputs, manage).unwrap_err();
|
||||
outputs.vidsrc.on_stream_error();
|
||||
outputs.audsrc.on_stream_error();
|
||||
// Authentication failures are permanent; we retry everything else
|
||||
if cam_err.connected {
|
||||
current_backoff = min_backoff;
|
||||
}
|
||||
match cam_err.err {
|
||||
neolink_core::Error::AuthFailed => {
|
||||
error!(
|
||||
"Authentication failed to camera {}, not retrying",
|
||||
camera_config.name
|
||||
);
|
||||
return Err(cam_err.err.into());
|
||||
}
|
||||
_ => error!(
|
||||
"Error streaming from camera {}, will retry in {}s: {}",
|
||||
camera_config.name,
|
||||
current_backoff.as_secs(),
|
||||
cam_err.err
|
||||
),
|
||||
}
|
||||
|
||||
std::thread::sleep(current_backoff);
|
||||
current_backoff = std::cmp::min(max_backoff, current_backoff * 2);
|
||||
}
|
||||
}
|
||||
|
||||
struct CameraErr {
|
||||
connected: bool,
|
||||
err: neolink_core::Error,
|
||||
}
|
||||
|
||||
fn set_up_tls(config: &Config, rtsp: &RtspServer) {
|
||||
let tls_client_auth = match &config.tls_client_auth as &str {
|
||||
"request" => TlsAuthenticationMode::Requested,
|
||||
"require" => TlsAuthenticationMode::Required,
|
||||
"none" => TlsAuthenticationMode::None,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if let Some(cert_path) = &config.certificate {
|
||||
rtsp.set_tls(cert_path, tls_client_auth)
|
||||
.expect("Failed to set up TLS");
|
||||
}
|
||||
}
|
||||
|
||||
fn set_up_users(users: &[UserConfig], rtsp: &RtspServer) {
|
||||
// Setting up users
|
||||
let credentials: Vec<_> = users
|
||||
.iter()
|
||||
.map(|user| (&*user.name, &*user.pass))
|
||||
.collect();
|
||||
rtsp.set_credentials(&credentials)
|
||||
.expect("Failed to set up users");
|
||||
}
|
||||
|
||||
fn get_permitted_users<'a>(
|
||||
users: &'a [UserConfig],
|
||||
// not idiomatic as a function argument, but this fn translates the config struct directly:
|
||||
permitted_users: &'a Option<Vec<String>>,
|
||||
) -> HashSet<&'a str> {
|
||||
// Helper to build hashset of all users in `users`:
|
||||
let all_users_hash = || users.iter().map(|u| u.name.as_str()).collect();
|
||||
|
||||
match permitted_users {
|
||||
// If in the camera config there is the user "anyone", or if none is specified but users
|
||||
// are defined at all, then we add all users to the camera's allowed list.
|
||||
Some(p) if p.iter().any(|u| u == "anyone") => all_users_hash(),
|
||||
None if !users.is_empty() => all_users_hash(),
|
||||
|
||||
// The user specified permitted_users
|
||||
Some(p) => p.iter().map(String::as_str).collect(),
|
||||
|
||||
// The user didn't specify permitted_users, and there are none defined anyway
|
||||
None => ["anonymous"].iter().cloned().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn camera_main(
|
||||
camera_config: &CameraConfig,
|
||||
stream_name: &str,
|
||||
outputs: &mut GstOutputs,
|
||||
manage: bool,
|
||||
) -> Result<Never, CameraErr> {
|
||||
let mut connected = false;
|
||||
(|| {
|
||||
let mut camera = BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
|
||||
if camera_config.timeout.is_some() {
|
||||
warn!("The undocumented `timeout` config option has been removed and is no longer needed.");
|
||||
warn!("Please update your config file.");
|
||||
}
|
||||
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_config.camera_addr
|
||||
);
|
||||
|
||||
camera.login(&camera_config.username, camera_config.password.as_deref())?;
|
||||
|
||||
connected = true;
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
if manage {
|
||||
do_camera_management(&mut camera, camera_config)?;
|
||||
}
|
||||
|
||||
info!(
|
||||
"{}: Starting video stream {}",
|
||||
camera_config.name, stream_name
|
||||
);
|
||||
camera.start_video(outputs, stream_name)
|
||||
})()
|
||||
.map_err(|err| CameraErr { connected, err })
|
||||
}
|
||||
|
||||
fn do_camera_management(
|
||||
camera: &mut BcCamera,
|
||||
camera_config: &CameraConfig,
|
||||
) -> Result<(), neolink_core::Error> {
|
||||
let cam_time = camera.get_time()?;
|
||||
if let Some(time) = cam_time {
|
||||
info!(
|
||||
"{}: Camera time is already set: {}",
|
||||
camera_config.name, time
|
||||
);
|
||||
} else {
|
||||
use time::OffsetDateTime;
|
||||
// We'd like now_local() but it's deprecated - try to get the local time, but if no
|
||||
// time zone, fall back to UTC.
|
||||
let new_time =
|
||||
OffsetDateTime::try_now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());
|
||||
|
||||
warn!(
|
||||
"{}: Camera has no time set, setting to {}",
|
||||
camera_config.name, new_time
|
||||
);
|
||||
camera.set_time(new_time)?;
|
||||
let cam_time = camera.get_time()?;
|
||||
if let Some(time) = cam_time {
|
||||
info!("{}: Camera time is now set: {}", camera_config.name, time);
|
||||
} else {
|
||||
error!(
|
||||
"{}: Camera did not accept new time (is {} an admin?)",
|
||||
camera_config.name, camera_config.username
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
use neolink_core::bc::xml::VersionInfo;
|
||||
if let Ok(VersionInfo {
|
||||
firmwareVersion: firmware_version,
|
||||
..
|
||||
}) = camera.version()
|
||||
{
|
||||
info!(
|
||||
"{}: Camera reports firmware version {}",
|
||||
camera_config.name, firmware_version
|
||||
);
|
||||
} else {
|
||||
info!(
|
||||
"{}: Could not fetch version information",
|
||||
camera_config.name
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user