From 98ad773bfe72e6810e2695fd122edb0ef70ada1a Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Tue, 28 Apr 2020 13:36:02 -0500 Subject: [PATCH] Implement rudimentary RTSP server --- Cargo.toml | 2 ++ sample_config.toml | 4 +-- src/bc/de.rs | 3 +- src/config.rs | 33 ++++------------------ src/gst.rs | 68 ++++++++++++++++++++++++++-------------------- src/main.rs | 22 +++++++-------- 6 files changed, 61 insertions(+), 71 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3970b79..6911125 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,9 +11,11 @@ cookie-factory = "0.3.1" crossbeam-utils = "0.7" env_logger = "*" err-derive = "0.2.4" +glib = "*" gstreamer = "0.15" gstreamer-app = "0.15" gstreamer-player = "0.15" +gstreamer-rtsp = "0.15" gstreamer-rtsp-server = "0.15" log = { version = "0.4.8", features = ["release_max_level_warn"] } indoc = "0.3.5" diff --git a/sample_config.toml b/sample_config.toml index 611f559..a67d47e 100644 --- a/sample_config.toml +++ b/sample_config.toml @@ -1,13 +1,13 @@ +bind = "0.0.0.0" + [[cameras]] name = "driveway" username = "admin" password = "12345678" address = "192.168.1.187:9000" -serve = { port = 9900 } [[cameras]] name = "storage shed" username = "admin" password = "987654321" address = "192.168.1.245:9000" -serve = { port = 9901 } diff --git a/src/bc/de.rs b/src/bc/de.rs index 89c4f47..4a9ee3b 100644 --- a/src/bc/de.rs +++ b/src/bc/de.rs @@ -134,7 +134,8 @@ fn bc_modern_msg<'a, 'b, 'c>(context: &mut BcContext, header: &'a BcHeader, buf: .map_err(|_| Err::Error(make_error(buf, ErrorKind::MapRes)))?; // If this is the first message containing binary, the Extension message puts the message - // ID into binary mode, then the first binary is sent after the XML. + // ID into binary mode, then the first binary is sent after the XML. All remaining + // messages for that ID are pure binary. match parsed { AllTopXmls::BcXml(x) => { xml = Some(x); } AllTopXmls::Extension(Extension { binary_data: _ }) => { diff --git a/src/config.rs b/src/config.rs index 8264e06..428ffa2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,11 +1,12 @@ use serde::Deserialize; -use std::fmt; use std::net::SocketAddr; -use std::net::ToSocketAddrs; #[derive(Debug, Deserialize)] pub struct Config { pub cameras: Vec, + + #[serde(rename="bind", default="default_bind_addr")] + pub bind_addr: String, } #[derive(Debug, Deserialize)] @@ -15,34 +16,10 @@ pub struct CameraConfig { #[serde(rename="address")] pub camera_addr: SocketAddr, - #[serde(rename="serve")] - pub bind_addr: BindAddr, - - pub stream: Option, pub username: String, pub password: Option, } -#[derive(Debug, PartialEq, Eq, Deserialize)] -pub struct BindAddr { - host: Option, - port: u16, -} - -impl fmt::Display for BindAddr { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(ref host) = self.host { - write!(f, "{}:{}", host, self.port) - } else { - write!(f, "port {}", self.port) - } - } -} - -impl ToSocketAddrs for BindAddr { - type Iter = <(&'static str, u16) as ToSocketAddrs>::Iter; - fn to_socket_addrs(&self) -> std::io::Result { - let host = self.host.as_deref().unwrap_or("0.0.0.0"); - (host, self.port).to_socket_addrs() - } +fn default_bind_addr() -> String { + "0.0.0.0".to_string() } diff --git a/src/gst.rs b/src/gst.rs index 6ae6d45..d2f0724 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -1,10 +1,14 @@ +//! This module provides an "RtspServer" abstraction that allows consumers of its API to feed it +//! data using an ordinary std::io::Write interface. +pub use self::maybe_app_src::MaybeAppSrc; + use gstreamer::Bin; use gstreamer::prelude::Cast; use gstreamer_app::AppSrc; +//use gstreamer_rtsp::RTSPLowerTrans; use gstreamer_rtsp_server::{RTSPServer as GstRTSPServer, RTSPAuth, RTSPMediaFactory}; use gstreamer_rtsp_server::prelude::*; use log::debug; -use self::maybe_app_src::MaybeAppSrc; use std::io; use std::io::Write; @@ -16,27 +20,31 @@ pub struct RtspServer { impl RtspServer { pub fn new() -> RtspServer { + gstreamer::init().expect("Gstreamer should not explode"); RtspServer { server: GstRTSPServer::new(), } } - pub fn add_stream(&mut self, name: &str) -> Result { + pub fn add_stream(&self, name: &str) -> Result { let mounts = self.server.get_mount_points().expect("The server should have mountpoints"); let factory = RTSPMediaFactory::new(); - // TODO data from the camera may already be payloaded; in that case I am not sure what to - // create as pay0 (maybe depay/pay is an option) - factory.set_launch("( appsrc name=writesrc ! rtph265pay name=pay0 )"); + //factory.set_protocols(RTSPLowerTrans::TCP); + factory.set_launch(concat!("( ", + "appsrc name=writesrc is-live=true block=true emit-signals=false max-bytes=0", + " ! h265parse", + " ! rtph265pay name=pay0", + " )")); factory.set_shared(true); - factory.set_stop_on_disconnect(false); // I think appsrc must be allowed to continue producing - // TODO maybe set video format, either via caps or via + // TODO maybe set video format via // https://gitlab.freedesktop.org/gstreamer/gstreamer-rs/-/blob/master/examples/src/bin/appsrc.rs#L66 // 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. + // 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(); factory.connect_media_configure(move |_factory, media| { debug!("RTSP: media was configured"); @@ -48,7 +56,7 @@ impl RtspServer { .expect("write_src must be present in created bin") .dynamic_cast::() .expect("Source element is expected to be an appsrc!"); - tx.send(app_src).expect("No trouble expected sending the appsrc"); + let _ = tx.send(app_src); // Receiver may be dropped, don't panic if so }); mounts.add_factory(&format!("/{}", name), &factory); @@ -74,23 +82,27 @@ impl RtspServer { Ok(()) } - pub fn run(&mut self, bind_addr: &str) { + pub fn run(&self, bind_addr: &str) { self.server.set_address(bind_addr); // 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 std::sync::mpsc::{sync_channel, Receiver, SyncSender}; use super::*; - use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; /// 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 enum MaybeAppSrc { - Receiver(Receiver), - AppSrc(AppSrc), + pub struct MaybeAppSrc { + rx: Receiver, + app_src: Option, } impl MaybeAppSrc { @@ -98,23 +110,19 @@ mod maybe_app_src { /// soon as one is available. When it is received, the MaybeAppSrc will start pushing data /// into the AppSrc when write() is called. pub fn new_with_tx() -> (Self, SyncSender) { - let (tx, rx) = sync_channel(1); - (MaybeAppSrc::Receiver(rx), tx) + let (tx, rx) = sync_channel(3); // The sender should not send very often + (MaybeAppSrc { rx, app_src: None, }, tx) } /// 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 and drop the channel. This function handles either case and - /// returns the AppSrc, or None if the caller has not yet sent one. + /// 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> { - use MaybeAppSrc::*; - match self { - AppSrc(ref src) => Some(src), - Receiver(rx) => if let Some(src) = rx.try_recv().ok() { - *self = AppSrc(src); - self.try_get_src() - } else { None } + while let Some(src) = self.rx.try_recv().ok() { + self.app_src = Some(src); } + self.app_src.as_ref() } } @@ -127,12 +135,14 @@ mod maybe_app_src { }; let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap(); { - let mut gst_buf_data = gst_buf.get_mut().unwrap() - .map_writable().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); } - app_src.push_buffer(gst_buf) - .map_err(|e| io::Error::new(io::ErrorKind::Other, Box::new(e)))?; + 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()) } diff --git a/src/main.rs b/src/main.rs index 2331f22..c9f7a65 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,8 +11,9 @@ use config::{Config, CameraConfig}; use cmdline::Opt; use crossbeam_utils::thread; use err_derive::Error; +use gst::RtspServer; use std::fs; -use std::net::TcpListener; +use std::io::Write; use structopt::StructOpt; #[derive(Debug, Error)] @@ -29,19 +30,24 @@ fn main() -> Result<(), Error> { let opt = Opt::from_args(); let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?; + let rtsp = &RtspServer::new(); + thread::scope(|s| { for camera in config.cameras { s.spawn(move |_| { // TODO handle these errors - camera_main(&camera) + let mut output = rtsp.add_stream(&camera.name).unwrap(); // TODO + camera_main(&camera, &mut output) }); } + + rtsp.run(&config.bind_addr); }).unwrap(); Ok(()) } -fn camera_main(camera_config: &CameraConfig) -> Result<(), Error> { +fn camera_main(camera_config: &CameraConfig, output: &mut dyn Write) -> Result<(), Error> { let mut camera = BcCamera::new_with_addr(camera_config.camera_addr)?; println!("{}: Connecting to camera at {}", camera_config.name, camera_config.camera_addr); @@ -49,15 +55,9 @@ fn camera_main(camera_config: &CameraConfig) -> Result<(), Error> { camera.connect()?; camera.login(&camera_config.username, camera_config.password.as_deref())?; - let bind_addr = &camera_config.bind_addr; - println!("{}: Logged in to camera; awaiting connection on {}", camera_config.name, bind_addr); + println!("{}: Connected to camera, starting video stream", camera_config.name); - let listener = TcpListener::bind(bind_addr)?; - let (mut out_socket, remote_addr) = listener.accept()?; - - println!("{}: Connected to {}, starting video stream", camera_config.name, remote_addr); - - camera.start_video(&mut out_socket)?; + camera.start_video(output)?; Ok(()) }