Merge branch 'h264'

This commit is contained in:
George Hilliard committed 2020-07-02 08:49:10 -05:00
commit 98a0d3cd5d
6 files changed
+114 -23

No files matched your search

+4
View File
@@ -17,10 +17,12 @@ gstreamer = "0.15"
gstreamer-app = "0.15" gstreamer-app = "0.15"
gstreamer-rtsp = "0.15" gstreamer-rtsp = "0.15"
gstreamer-rtsp-server = "0.15" gstreamer-rtsp-server = "0.15"
lazy_static = "1.4"
log = { version = "0.4" } log = { version = "0.4" }
indoc = "0.3" indoc = "0.3"
md5 = "0.7" md5 = "0.7"
nom = "5.1" nom = "5.1"
regex = "1"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
socket2 = "0.3" socket2 = "0.3"
structopt = "0.3" structopt = "0.3"
@@ -28,3 +30,5 @@ toml = "0.5"
yaserde = "0.3.16" yaserde = "0.3.16"
yaserde_derive = "0.3.16" yaserde_derive = "0.3.16"
xml-rs = "0.8" xml-rs = "0.8"
validator = "0.10"
validator_derive = "0.10"
+8 -1
View File
@@ -63,8 +63,15 @@ Copy and modify the `sample_config.toml` to specify the address, username, and p
Each `[[cameras]]` block creates a new camera; the `name` determines the RTSP path you should connect your client to. Each `[[cameras]]` block creates a new camera; the `name` determines the RTSP path you should connect your client to.
Currently Neolink cannot auto-detect cameras like the official clients do; you must specify their IP addresses directly. Currently Neolink cannot auto-detect cameras like the official clients do; you must specify their IP addresses directly.
By default the H265 video format is used. Some cameras, for example E1, provide H264 streams. To use these you must specify `format = "h264"` in the `[[cameras]]` config.
Soon this will be auto-detected, and you will not have to know or care about the format.
By default, the HD stream is available at the RTSP path `/name` or `/name/mainStream`, and the SD stream is available at `/name/subStream`.
You can disable the HD stream by adding `stream = "subStream"` to the `[[cameras]]` config.
You may also need to use `h264` format while using the SD stream.
By default Neolink serves on all IP addresses on port 8554. By default Neolink serves on all IP addresses on port 8554.
You can modify this by changing the `bind` parameter. You can modify this by changing the `bind` and the `bind_port` parameter.
You can change the Neolink log level by setting the `RUST_LOG` environment variable (not in the configuration file) to one of `error`, `warn`, `info`, `debug`, or `trace`: You can change the Neolink log level by setting the `RUST_LOG` environment variable (not in the configuration file) to one of `error`, `warn`, `info`, `debug`, or `trace`:
+2 -2
View File
@@ -242,7 +242,7 @@ impl BcCamera {
Ok(()) Ok(())
} }
pub fn start_video(&self, data_out: &mut dyn Write) -> Result<Never> { pub fn start_video(&self, data_out: &mut dyn Write, stream_name: &str) -> Result<Never> {
let connection = self let connection = self
.connection .connection
.as_ref() .as_ref()
@@ -261,7 +261,7 @@ impl BcCamera {
version: xml_ver(), version: xml_ver(),
channel_id: 0, channel_id: 0,
handle: 0, handle: 0,
stream_type: "mainStream".to_string(), stream_type: stream_name.to_string(),
}), }),
..Default::default() ..Default::default()
}, },
+35 -2
View File
@@ -1,16 +1,29 @@
use serde::Deserialize; use serde::Deserialize;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::time::Duration; use std::time::Duration;
use std::clone::Clone;
use validator::Validate;
use regex::Regex;
#[derive(Debug, Deserialize)] lazy_static! {
static ref RE_STREAM_FORM: Regex = Regex::new(r"^([hH]26[45]|[ \t]*[!].*)$").unwrap();
static ref RE_STREAM_SRC: Regex = Regex::new(r"^(mainStream|subStream|both)$").unwrap();
}
#[derive(Debug, Deserialize, Validate, Clone)]
pub struct Config { pub struct Config {
#[validate]
pub cameras: Vec<CameraConfig>, pub cameras: Vec<CameraConfig>,
#[serde(rename = "bind", default = "default_bind_addr")] #[serde(rename = "bind", default = "default_bind_addr")]
pub bind_addr: String, pub bind_addr: String,
#[validate(range(min = 0, max = 65535, message = "Invalid port", code = "bind_port"))]
#[serde(default = "default_bind_port")]
pub bind_port: u16,
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize, Validate, Clone)]
pub struct CameraConfig { pub struct CameraConfig {
pub name: String, pub name: String,
@@ -21,8 +34,28 @@ pub struct CameraConfig {
pub password: Option<String>, pub password: Option<String>,
pub timeout: Option<Duration>, pub timeout: Option<Duration>,
#[validate(regex(path = "RE_STREAM_FORM", message = "Incorrect stream format", code = "format"))]
#[serde(default = "default_format")]
pub format: String,
#[validate(regex(path = "RE_STREAM_SRC", message = "Incorrect stream source", code = "stream"))]
#[serde(default = "default_stream")]
pub stream: String,
} }
fn default_bind_addr() -> String { fn default_bind_addr() -> String {
"0.0.0.0".to_string() "0.0.0.0".to_string()
} }
fn default_bind_port() -> u16 {
8554
}
fn default_format() -> String {
"h265".to_string()
}
fn default_stream() -> String {
"both".to_string()
}
+21 -8
View File
@@ -18,6 +18,12 @@ pub struct RtspServer {
server: GstRTSPServer, server: GstRTSPServer,
} }
pub enum StreamFormat {
H264,
H265,
Custom(String)
}
impl RtspServer { impl RtspServer {
pub fn new() -> RtspServer { pub fn new() -> RtspServer {
gstreamer::init().expect("Gstreamer should not explode"); gstreamer::init().expect("Gstreamer should not explode");
@@ -26,19 +32,24 @@ impl RtspServer {
} }
} }
pub fn add_stream(&self, name: &str) -> Result<MaybeAppSrc> { pub fn add_stream(&self, names: &[&str], stream_format: &StreamFormat) -> Result<MaybeAppSrc> {
let mounts = self let mounts = self
.server .server
.get_mount_points() .get_mount_points()
.expect("The server should have mountpoints"); .expect("The server should have mountpoints");
let launch_str = match stream_format {
StreamFormat::H264 => "! h264parse ! rtph264pay name=pay0",
StreamFormat::H265 => "! h265parse ! rtph265pay name=pay0",
StreamFormat::Custom(custom_format) => custom_format,
};
let factory = RTSPMediaFactory::new(); let factory = RTSPMediaFactory::new();
//factory.set_protocols(RTSPLowerTrans::TCP); //factory.set_protocols(RTSPLowerTrans::TCP);
factory.set_launch(concat!( factory.set_launch(&format!("{}{}{}{}",
"( ", "( ",
"appsrc name=writesrc is-live=true block=true emit-signals=false max-bytes=0", "appsrc name=writesrc is-live=true block=true emit-signals=false max-bytes=0 do-timestamp=true ",
" ! h265parse", launch_str,
" ! rtph265pay name=pay0",
" )" " )"
)); ));
factory.set_shared(true); factory.set_shared(true);
@@ -66,7 +77,9 @@ impl RtspServer {
let _ = tx.send(app_src); // Receiver may be dropped, don't panic if so let _ = tx.send(app_src); // Receiver may be dropped, don't panic if so
}); });
mounts.add_factory(&format!("/{}", name), &factory); for name in names {
mounts.add_factory(&format!("/{}", name), &factory);
}
Ok(maybe_app_src) Ok(maybe_app_src)
} }
@@ -89,9 +102,9 @@ impl RtspServer {
Ok(()) Ok(())
} }
pub fn run(&self, bind_addr: &str) { pub fn run(&self, bind_addr: &str, bind_port: u16) {
self.server.set_address(bind_addr); self.server.set_address(bind_addr);
self.server.set_service(&format!("{}", bind_port));
// Attach server to default Glib context // Attach server to default Glib context
self.server.attach(None); self.server.attach(None);
+44 -10
View File
@@ -1,13 +1,18 @@
#[macro_use] extern crate validator_derive;
#[macro_use] extern crate lazy_static;
use env_logger::Env; use env_logger::Env;
use err_derive::Error; use err_derive::Error;
use log::*; use log::*;
use neolink::bc_protocol::BcCamera; use neolink::bc_protocol::BcCamera;
use neolink::gst::{MaybeAppSrc, RtspServer}; use neolink::gst::{MaybeAppSrc, RtspServer, StreamFormat};
use neolink::Never; use neolink::Never;
use std::fs; use std::fs;
use std::io::Write; use std::io::Write;
use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use structopt::StructOpt; use structopt::StructOpt;
use validator::Validate;
mod cmdline; mod cmdline;
mod config; mod config;
@@ -23,6 +28,8 @@ pub enum Error {
ProtocolError(#[error(source)] neolink::Error), ProtocolError(#[error(source)] neolink::Error),
#[error(display = "I/O error")] #[error(display = "I/O error")]
IoError(#[error(source)] std::io::Error), IoError(#[error(source)] std::io::Error),
#[error(display = "Validation error")]
ValidationError(#[error(source)] validator::ValidationErrors),
} }
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
@@ -37,18 +44,45 @@ fn main() -> Result<(), Error> {
let opt = Opt::from_args(); let opt = Opt::from_args();
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?; let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
match config.validate() {
Ok(_) => (),
Err(e) => return Err(Error::ValidationError(e)),
};
let rtsp = &RtspServer::new(); let rtsp = &RtspServer::new();
crossbeam::scope(|s| { crossbeam::scope(|s| {
for camera in config.cameras { for camera in config.cameras {
s.spawn(move |_| { let stream_format = match &*camera.format {
// TODO handle these errors "h264"|"H264" => StreamFormat::H264,
let mut output = rtsp.add_stream(&camera.name).unwrap(); "h265"|"H265" => StreamFormat::H265,
camera_loop(&camera, &mut output) custom_format @ _ => StreamFormat::Custom(custom_format.to_string())
}); };
// 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);
// Set up each main and substream according to all the RTSP mount paths we support
if arc_cam.stream == "both" || arc_cam.stream == "mainStream" {
let paths = &[
&arc_cam.name,
&*format!("{}/mainStream", arc_cam.name),
];
let mut output = rtsp.add_stream(paths, &stream_format).unwrap();
let main_camera = arc_cam.clone();
s.spawn(move |_| camera_loop(&*main_camera, &mut output));
}
if arc_cam.stream == "both" || arc_cam.stream == "subStream" {
let paths = &[&*format!("{}/subStream", arc_cam.name)];
let mut output = rtsp.add_stream(paths, &stream_format).unwrap();
let sub_camera = arc_cam.clone();
s.spawn(move |_| camera_loop(&*sub_camera, &mut output));
}
} }
rtsp.run(&config.bind_addr); rtsp.run(&config.bind_addr, config.bind_port);
}) })
.unwrap(); .unwrap();
@@ -112,10 +146,10 @@ fn camera_main(camera_config: &CameraConfig, output: &mut dyn Write) -> Result<N
connected = true; connected = true;
info!( info!(
"{}: Connected to camera, starting video stream", "{}: Connected to camera, starting video stream {}",
camera_config.name camera_config.name, camera_config.stream
); );
camera.start_video(output) camera.start_video(output, &camera_config.stream)
})() })()
.map_err(|err| CameraErr { connected, err }) .map_err(|err| CameraErr { connected, err })
} }