2020-03-02 01:53:41 -05:00
|
|
|
// This file is part of Moonfire NVR, a security camera network video recorder.
|
2020-03-20 00:35:42 -04:00
|
|
|
// Copyright (C) 2016-2020 The Moonfire NVR Authors
|
2016-11-25 17:34:00 -05:00
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// In addition, as a special exception, the copyright holders give
|
|
|
|
// permission to link the code of portions of this program with the
|
|
|
|
// OpenSSL library under certain conditions as described in each
|
|
|
|
// individual source file, and distribute linked combinations including
|
|
|
|
// the two.
|
|
|
|
//
|
|
|
|
// You must obey the GNU General Public License in all respects for all
|
|
|
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
|
|
|
// exception, you may extend this exception to your version of the
|
|
|
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
|
|
|
// so, delete this exception statement from your version. If you delete
|
|
|
|
// this exception statement from all source files in the program, then
|
|
|
|
// also delete it here.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
|
|
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2018-12-28 13:21:49 -05:00
|
|
|
use crate::h264;
|
2018-12-28 22:53:29 -05:00
|
|
|
use crate::stream;
|
2021-02-17 01:15:54 -05:00
|
|
|
use base::clock::{Clocks, TimerGuard};
|
|
|
|
use db::{dir, recording, writer, Camera, Database, Stream};
|
|
|
|
use failure::{bail, format_err, Error};
|
2018-12-28 22:53:29 -05:00
|
|
|
use log::{debug, info, trace, warn};
|
2016-11-25 17:34:00 -05:00
|
|
|
use std::result::Result;
|
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use std::sync::Arc;
|
|
|
|
use time;
|
2019-07-01 00:54:52 -04:00
|
|
|
use url::Url;
|
2016-11-25 17:34:00 -05:00
|
|
|
|
|
|
|
pub static ROTATE_INTERVAL_SEC: i64 = 60;
|
|
|
|
|
2016-12-06 21:41:44 -05:00
|
|
|
/// Common state that can be used by multiple `Streamer` instances.
|
2021-02-17 01:15:54 -05:00
|
|
|
pub struct Environment<'a, 'b, C, S>
|
|
|
|
where
|
|
|
|
C: Clocks + Clone,
|
|
|
|
S: 'a + stream::Stream,
|
|
|
|
{
|
2019-06-14 11:47:11 -04:00
|
|
|
pub opener: &'a dyn stream::Opener<S>,
|
2018-03-23 16:31:23 -04:00
|
|
|
pub db: &'b Arc<Database<C>>,
|
2016-12-06 21:41:44 -05:00
|
|
|
pub shutdown: &'b Arc<AtomicBool>,
|
|
|
|
}
|
|
|
|
|
2021-02-17 01:15:54 -05:00
|
|
|
pub struct Streamer<'a, C, S>
|
|
|
|
where
|
|
|
|
C: Clocks + Clone,
|
|
|
|
S: 'a + stream::Stream,
|
|
|
|
{
|
2016-11-25 17:34:00 -05:00
|
|
|
shutdown: Arc<AtomicBool>,
|
|
|
|
|
|
|
|
// State below is only used by the thread in Run.
|
|
|
|
rotate_offset_sec: i64,
|
2016-12-06 21:41:44 -05:00
|
|
|
rotate_interval_sec: i64,
|
2018-03-23 16:31:23 -04:00
|
|
|
db: Arc<Database<C>>,
|
2016-11-25 17:34:00 -05:00
|
|
|
dir: Arc<dir::SampleFileDir>,
|
2018-03-04 15:24:24 -05:00
|
|
|
syncer_channel: writer::SyncerChannel<::std::fs::File>,
|
2019-06-14 11:47:11 -04:00
|
|
|
opener: &'a dyn stream::Opener<S>,
|
2018-01-23 14:05:07 -05:00
|
|
|
stream_id: i32,
|
2016-11-25 17:34:00 -05:00
|
|
|
short_name: String,
|
2019-07-01 00:54:52 -04:00
|
|
|
url: Url,
|
|
|
|
redacted_url: Url,
|
2020-04-14 02:03:49 -04:00
|
|
|
detector: Option<Arc<crate::analytics::ObjectDetector>>,
|
2016-11-25 17:34:00 -05:00
|
|
|
}
|
|
|
|
|
2021-02-17 01:15:54 -05:00
|
|
|
impl<'a, C, S> Streamer<'a, C, S>
|
|
|
|
where
|
|
|
|
C: 'a + Clocks + Clone,
|
|
|
|
S: 'a + stream::Stream,
|
|
|
|
{
|
|
|
|
pub fn new<'b>(
|
|
|
|
env: &Environment<'a, 'b, C, S>,
|
|
|
|
dir: Arc<dir::SampleFileDir>,
|
|
|
|
syncer_channel: writer::SyncerChannel<::std::fs::File>,
|
|
|
|
stream_id: i32,
|
|
|
|
c: &Camera,
|
|
|
|
s: &Stream,
|
|
|
|
rotate_offset_sec: i64,
|
|
|
|
rotate_interval_sec: i64,
|
|
|
|
detector: Option<Arc<crate::analytics::ObjectDetector>>,
|
|
|
|
) -> Result<Self, Error> {
|
2019-07-01 00:54:52 -04:00
|
|
|
let mut url = Url::parse(&s.rtsp_url)?;
|
|
|
|
let mut redacted_url = url.clone();
|
|
|
|
if !c.username.is_empty() {
|
2021-02-17 01:15:54 -05:00
|
|
|
url.set_username(&c.username)
|
|
|
|
.map_err(|_| format_err!("can't set username"))?;
|
2019-07-01 01:06:22 -04:00
|
|
|
redacted_url.set_username(&c.username).unwrap();
|
|
|
|
url.set_password(Some(&c.password)).unwrap();
|
|
|
|
redacted_url.set_password(Some("redacted")).unwrap();
|
2019-07-01 00:54:52 -04:00
|
|
|
}
|
|
|
|
Ok(Streamer {
|
2016-12-06 21:41:44 -05:00
|
|
|
shutdown: env.shutdown.clone(),
|
2020-04-14 02:03:49 -04:00
|
|
|
rotate_offset_sec,
|
|
|
|
rotate_interval_sec,
|
2016-12-06 21:41:44 -05:00
|
|
|
db: env.db.clone(),
|
2018-02-12 01:45:51 -05:00
|
|
|
dir,
|
2020-04-14 02:03:49 -04:00
|
|
|
syncer_channel,
|
2016-12-06 21:41:44 -05:00
|
|
|
opener: env.opener,
|
2020-04-14 02:03:49 -04:00
|
|
|
stream_id,
|
2018-01-23 14:05:07 -05:00
|
|
|
short_name: format!("{}-{}", c.short_name, s.type_.as_str()),
|
2019-07-01 00:54:52 -04:00
|
|
|
url,
|
|
|
|
redacted_url,
|
2020-04-14 02:03:49 -04:00
|
|
|
detector,
|
2019-07-01 00:54:52 -04:00
|
|
|
})
|
2016-11-25 17:34:00 -05:00
|
|
|
}
|
|
|
|
|
2021-02-17 01:15:54 -05:00
|
|
|
pub fn short_name(&self) -> &str {
|
|
|
|
&self.short_name
|
|
|
|
}
|
2016-11-25 17:34:00 -05:00
|
|
|
|
|
|
|
pub fn run(&mut self) {
|
|
|
|
while !self.shutdown.load(Ordering::SeqCst) {
|
|
|
|
if let Err(e) = self.run_once() {
|
2016-12-06 21:41:44 -05:00
|
|
|
let sleep_time = time::Duration::seconds(1);
|
2021-02-17 01:15:54 -05:00
|
|
|
warn!(
|
|
|
|
"{}: sleeping for {:?} after error: {}",
|
|
|
|
self.short_name,
|
|
|
|
sleep_time,
|
|
|
|
base::prettify_failure(&e)
|
|
|
|
);
|
2018-03-23 16:31:23 -04:00
|
|
|
self.db.clocks().sleep(sleep_time);
|
2016-11-25 17:34:00 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
info!("{}: shutting down", self.short_name);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn run_once(&mut self) -> Result<(), Error> {
|
|
|
|
info!("{}: Opening input: {}", self.short_name, self.redacted_url);
|
2018-03-23 16:31:23 -04:00
|
|
|
let clocks = self.db.clocks();
|
2016-11-25 17:34:00 -05:00
|
|
|
|
2018-01-31 17:20:30 -05:00
|
|
|
let mut stream = {
|
2018-03-23 16:31:23 -04:00
|
|
|
let _t = TimerGuard::new(&clocks, || format!("opening {}", self.redacted_url));
|
2019-02-14 01:34:19 -05:00
|
|
|
self.opener.open(stream::Source::Rtsp {
|
2019-07-01 00:54:52 -04:00
|
|
|
url: self.url.as_str(),
|
|
|
|
redacted_url: self.redacted_url.as_str(),
|
2019-02-14 01:34:19 -05:00
|
|
|
})?
|
2018-01-31 17:20:30 -05:00
|
|
|
};
|
2018-03-23 16:31:23 -04:00
|
|
|
let realtime_offset = self.db.clocks().realtime() - clocks.monotonic();
|
2016-11-25 17:34:00 -05:00
|
|
|
// TODO: verify width/height.
|
2020-04-14 02:03:49 -04:00
|
|
|
let mut detector_stream = match self.detector.as_ref() {
|
|
|
|
None => None,
|
|
|
|
Some(od) => Some(crate::analytics::ObjectDetectorStream::new(
|
2021-02-17 01:15:54 -05:00
|
|
|
stream.get_video_codecpar(),
|
|
|
|
&od,
|
|
|
|
)?),
|
2020-04-14 02:03:49 -04:00
|
|
|
};
|
2016-11-25 17:34:00 -05:00
|
|
|
let extra_data = stream.get_extra_data()?;
|
2018-01-31 17:20:30 -05:00
|
|
|
let video_sample_entry_id = {
|
2018-03-23 16:31:23 -04:00
|
|
|
let _t = TimerGuard::new(&clocks, || "inserting video sample entry");
|
2020-03-20 00:35:42 -04:00
|
|
|
self.db.lock().insert_video_sample_entry(extra_data.entry)?
|
2018-01-31 17:20:30 -05:00
|
|
|
};
|
2021-02-17 01:15:54 -05:00
|
|
|
debug!(
|
|
|
|
"{}: video_sample_entry_id={}",
|
|
|
|
self.short_name, video_sample_entry_id
|
|
|
|
);
|
2016-11-25 17:34:00 -05:00
|
|
|
let mut seen_key_frame = false;
|
2018-02-28 15:32:52 -05:00
|
|
|
|
|
|
|
// Seconds since epoch at which to next rotate.
|
|
|
|
let mut rotate: Option<i64> = None;
|
2016-11-25 17:34:00 -05:00
|
|
|
let mut transformed = Vec::new();
|
2021-02-17 01:15:54 -05:00
|
|
|
let mut w = writer::Writer::new(
|
|
|
|
&self.dir,
|
|
|
|
&self.db,
|
|
|
|
&self.syncer_channel,
|
|
|
|
self.stream_id,
|
|
|
|
video_sample_entry_id,
|
|
|
|
);
|
2016-11-25 17:34:00 -05:00
|
|
|
while !self.shutdown.load(Ordering::SeqCst) {
|
2018-01-31 17:20:30 -05:00
|
|
|
let pkt = {
|
2018-03-23 16:31:23 -04:00
|
|
|
let _t = TimerGuard::new(&clocks, || "getting next packet");
|
2018-01-31 17:20:30 -05:00
|
|
|
stream.get_next()?
|
|
|
|
};
|
2018-02-21 01:46:14 -05:00
|
|
|
let pts = pkt.pts().ok_or_else(|| format_err!("packet with no pts"))?;
|
2016-11-25 17:34:00 -05:00
|
|
|
if !seen_key_frame && !pkt.is_key() {
|
|
|
|
continue;
|
|
|
|
} else if !seen_key_frame {
|
|
|
|
debug!("{}: have first key frame", self.short_name);
|
|
|
|
seen_key_frame = true;
|
|
|
|
}
|
2020-04-14 02:03:49 -04:00
|
|
|
if let (Some(a_s), Some(a)) = (detector_stream.as_mut(), self.detector.as_ref()) {
|
|
|
|
a_s.process_frame(&pkt, &a)?;
|
|
|
|
}
|
2018-03-23 16:31:23 -04:00
|
|
|
let frame_realtime = clocks.monotonic() + realtime_offset;
|
2016-12-28 23:56:08 -05:00
|
|
|
let local_time = recording::Time::new(frame_realtime);
|
2018-02-28 15:32:52 -05:00
|
|
|
rotate = if let Some(r) = rotate {
|
|
|
|
if frame_realtime.sec > r && pkt.is_key() {
|
2016-12-06 21:41:44 -05:00
|
|
|
trace!("{}: write on normal rotation", self.short_name);
|
2018-03-23 16:31:23 -04:00
|
|
|
let _t = TimerGuard::new(&clocks, || "closing writer");
|
make Writer enforce maximum recording duration
My installation recently somehow ended up with a recording with a
duration of 503793844 90,000ths of a second, way over the maximum of 5
minutes. (Looks like the machine was pretty unresponsive at the time
and/or having network problems.)
When this happens, the system really spirals. Every flush afterward (12
per minute with my installation) fails with a CHECK constraint failure
on the recording table. It never gives up on that recording. /var/log
fills pretty quickly as this failure is extremely verbose (a stack
trace, and a line for each byte of video_index). Eventually the sample
file dirs fill up too as it continues writing video samples while GC is
stuck. The video samples are useless anyway; given that they're not
referenced in the database, they'll be deleted on next startup.
This ensures the offending recording is never added to the database, so
we don't get the same persistent problem. Instead, writing to the
recording will fail. The stream will drop and be retried. If the
underlying condition that caused a too-long recording (many
non-key-frames, or the camera returning a crazy duration, or the
monotonic clock jumping forward extremely, or something) has gone away,
the system should recover.
2019-01-29 11:26:36 -05:00
|
|
|
w.close(Some(pts))?;
|
2016-12-28 23:56:08 -05:00
|
|
|
None
|
|
|
|
} else {
|
2018-02-28 15:32:52 -05:00
|
|
|
Some(r)
|
2016-11-25 17:34:00 -05:00
|
|
|
}
|
2021-02-17 01:15:54 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2018-02-28 15:32:52 -05:00
|
|
|
let r = match rotate {
|
|
|
|
Some(r) => r,
|
2016-11-25 17:34:00 -05:00
|
|
|
None => {
|
2016-12-28 23:56:08 -05:00
|
|
|
let sec = frame_realtime.sec;
|
|
|
|
let r = sec - (sec % self.rotate_interval_sec) + self.rotate_offset_sec;
|
2021-02-17 01:15:54 -05:00
|
|
|
let r = r + if r <= sec {
|
|
|
|
self.rotate_interval_sec
|
|
|
|
} else {
|
|
|
|
0
|
|
|
|
};
|
2016-12-30 09:39:09 -05:00
|
|
|
|
|
|
|
// On the first recording, set rotate time to not the next rotate offset, but
|
|
|
|
// the one after, so that it's longer than usual rather than shorter than
|
|
|
|
// usual. This ensures there's plenty of frame times to use when calculating
|
|
|
|
// the start time.
|
2021-02-17 01:15:54 -05:00
|
|
|
let r = r + if w.previously_opened()? {
|
|
|
|
0
|
|
|
|
} else {
|
|
|
|
self.rotate_interval_sec
|
|
|
|
};
|
2018-03-23 16:31:23 -04:00
|
|
|
let _t = TimerGuard::new(&clocks, || "creating writer");
|
2018-02-28 15:32:52 -05:00
|
|
|
r
|
2021-02-17 01:15:54 -05:00
|
|
|
}
|
2016-11-25 17:34:00 -05:00
|
|
|
};
|
|
|
|
let orig_data = match pkt.data() {
|
|
|
|
Some(d) => d,
|
2018-02-21 01:46:14 -05:00
|
|
|
None => bail!("packet has no data"),
|
2016-11-25 17:34:00 -05:00
|
|
|
};
|
|
|
|
let transformed_data = if extra_data.need_transform {
|
|
|
|
h264::transform_sample_data(orig_data, &mut transformed)?;
|
|
|
|
transformed.as_slice()
|
|
|
|
} else {
|
|
|
|
orig_data
|
|
|
|
};
|
2021-02-17 01:15:54 -05:00
|
|
|
let _t = TimerGuard::new(&clocks, || {
|
|
|
|
format!("writing {} bytes", transformed_data.len())
|
|
|
|
});
|
2018-02-28 15:32:52 -05:00
|
|
|
w.write(transformed_data, local_time, pts, pkt.is_key())?;
|
|
|
|
rotate = Some(r);
|
2016-11-25 17:34:00 -05:00
|
|
|
}
|
2018-02-28 15:32:52 -05:00
|
|
|
if rotate.is_some() {
|
2018-03-23 16:31:23 -04:00
|
|
|
let _t = TimerGuard::new(&clocks, || "closing writer");
|
make Writer enforce maximum recording duration
My installation recently somehow ended up with a recording with a
duration of 503793844 90,000ths of a second, way over the maximum of 5
minutes. (Looks like the machine was pretty unresponsive at the time
and/or having network problems.)
When this happens, the system really spirals. Every flush afterward (12
per minute with my installation) fails with a CHECK constraint failure
on the recording table. It never gives up on that recording. /var/log
fills pretty quickly as this failure is extremely verbose (a stack
trace, and a line for each byte of video_index). Eventually the sample
file dirs fill up too as it continues writing video samples while GC is
stuck. The video samples are useless anyway; given that they're not
referenced in the database, they'll be deleted on next startup.
This ensures the offending recording is never added to the database, so
we don't get the same persistent problem. Instead, writing to the
recording will fail. The stream will drop and be retried. If the
underlying condition that caused a too-long recording (many
non-key-frames, or the camera returning a crazy duration, or the
monotonic clock jumping forward extremely, or something) has gone away,
the system should recover.
2019-01-29 11:26:36 -05:00
|
|
|
w.close(None)?;
|
2016-11-25 17:34:00 -05:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
2016-12-06 21:41:44 -05:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2018-12-28 13:21:49 -05:00
|
|
|
use crate::h264;
|
2018-12-28 22:53:29 -05:00
|
|
|
use crate::stream::{self, Opener, Stream};
|
2021-02-17 01:15:54 -05:00
|
|
|
use base::clock::{self, Clocks};
|
|
|
|
use db::{recording, testutil, CompositeId};
|
|
|
|
use failure::{bail, Error};
|
2018-12-28 22:53:29 -05:00
|
|
|
use log::trace;
|
2018-02-22 19:35:34 -05:00
|
|
|
use parking_lot::Mutex;
|
2016-12-29 20:14:36 -05:00
|
|
|
use std::cmp;
|
2020-08-06 08:16:38 -04:00
|
|
|
use std::convert::TryFrom;
|
2016-12-06 21:41:44 -05:00
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
2021-02-17 01:15:54 -05:00
|
|
|
use std::sync::Arc;
|
2016-12-06 21:41:44 -05:00
|
|
|
use time;
|
|
|
|
|
|
|
|
struct ProxyingStream<'a> {
|
2016-12-30 00:05:57 -05:00
|
|
|
clocks: &'a clock::SimulatedClocks,
|
2016-12-06 21:41:44 -05:00
|
|
|
inner: stream::FfmpegStream,
|
2016-12-29 20:14:36 -05:00
|
|
|
buffered: time::Duration,
|
|
|
|
slept: time::Duration,
|
2016-12-06 21:41:44 -05:00
|
|
|
ts_offset: i64,
|
|
|
|
ts_offset_pkts_left: u32,
|
|
|
|
pkts_left: u32,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> ProxyingStream<'a> {
|
2021-02-17 01:15:54 -05:00
|
|
|
fn new(
|
|
|
|
clocks: &'a clock::SimulatedClocks,
|
|
|
|
buffered: time::Duration,
|
|
|
|
inner: stream::FfmpegStream,
|
|
|
|
) -> ProxyingStream {
|
2016-12-30 00:05:57 -05:00
|
|
|
clocks.sleep(buffered);
|
2016-12-06 21:41:44 -05:00
|
|
|
ProxyingStream {
|
2016-12-30 00:05:57 -05:00
|
|
|
clocks: clocks,
|
2016-12-06 21:41:44 -05:00
|
|
|
inner: inner,
|
2016-12-29 20:14:36 -05:00
|
|
|
buffered: buffered,
|
|
|
|
slept: time::Duration::seconds(0),
|
2016-12-06 21:41:44 -05:00
|
|
|
ts_offset: 0,
|
|
|
|
ts_offset_pkts_left: 0,
|
|
|
|
pkts_left: 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Stream for ProxyingStream<'a> {
|
2020-03-28 03:59:25 -04:00
|
|
|
fn get_next(&mut self) -> Result<ffmpeg::avcodec::Packet, ffmpeg::Error> {
|
2016-12-06 21:41:44 -05:00
|
|
|
if self.pkts_left == 0 {
|
2018-12-28 22:53:29 -05:00
|
|
|
return Err(ffmpeg::Error::eof());
|
2016-12-06 21:41:44 -05:00
|
|
|
}
|
|
|
|
self.pkts_left -= 1;
|
|
|
|
|
|
|
|
let mut pkt = self.inner.get_next()?;
|
|
|
|
|
2020-08-06 08:16:38 -04:00
|
|
|
// Emulate the behavior of real cameras that send some pre-buffered frames immediately
|
|
|
|
// on connect. After that, advance clock to the end of this frame.
|
2016-12-29 20:14:36 -05:00
|
|
|
// Avoid accumulating conversion error by tracking the total amount to sleep and how
|
|
|
|
// much we've already slept, rather than considering each frame in isolation.
|
|
|
|
{
|
2017-09-21 00:06:06 -04:00
|
|
|
let goal = pkt.pts().unwrap() + pkt.duration() as i64;
|
2016-12-29 20:14:36 -05:00
|
|
|
let goal = time::Duration::nanoseconds(
|
2021-02-17 01:15:54 -05:00
|
|
|
goal * 1_000_000_000 / recording::TIME_UNITS_PER_SEC,
|
|
|
|
);
|
2016-12-29 20:14:36 -05:00
|
|
|
let duration = goal - self.slept;
|
|
|
|
let buf_part = cmp::min(self.buffered, duration);
|
|
|
|
self.buffered = self.buffered - buf_part;
|
2016-12-30 00:05:57 -05:00
|
|
|
self.clocks.sleep(duration - buf_part);
|
2016-12-29 20:14:36 -05:00
|
|
|
self.slept = goal;
|
|
|
|
}
|
2016-12-06 21:41:44 -05:00
|
|
|
|
|
|
|
if self.ts_offset_pkts_left > 0 {
|
|
|
|
self.ts_offset_pkts_left -= 1;
|
|
|
|
let old_pts = pkt.pts().unwrap();
|
|
|
|
let old_dts = pkt.dts();
|
2017-09-21 00:06:06 -04:00
|
|
|
pkt.set_pts(Some(old_pts + self.ts_offset));
|
|
|
|
pkt.set_dts(old_dts + self.ts_offset);
|
2016-12-06 21:41:44 -05:00
|
|
|
|
2017-09-21 00:06:06 -04:00
|
|
|
// In a real rtsp stream, the duration of a packet is not known until the
|
2020-08-06 08:16:38 -04:00
|
|
|
// next packet. ffmpeg's duration is an unreliable estimate. Set it to something
|
|
|
|
// ridiculous.
|
|
|
|
pkt.set_duration(i32::try_from(3600 * recording::TIME_UNITS_PER_SEC).unwrap());
|
2016-12-06 21:41:44 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(pkt)
|
|
|
|
}
|
|
|
|
|
2020-04-14 02:03:49 -04:00
|
|
|
fn get_video_codecpar(&self) -> ffmpeg::avcodec::InputCodecParameters<'_> {
|
|
|
|
self.inner.get_video_codecpar()
|
|
|
|
}
|
|
|
|
|
2021-02-17 01:15:54 -05:00
|
|
|
fn get_extra_data(&self) -> Result<h264::ExtraData, Error> {
|
|
|
|
self.inner.get_extra_data()
|
|
|
|
}
|
2016-12-06 21:41:44 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
struct MockOpener<'a> {
|
|
|
|
expected_url: String,
|
|
|
|
streams: Mutex<Vec<ProxyingStream<'a>>>,
|
|
|
|
shutdown: Arc<AtomicBool>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> stream::Opener<ProxyingStream<'a>> for MockOpener<'a> {
|
|
|
|
fn open(&self, src: stream::Source) -> Result<ProxyingStream<'a>, Error> {
|
|
|
|
match src {
|
2021-02-17 01:15:54 -05:00
|
|
|
stream::Source::Rtsp { url, .. } => assert_eq!(url, &self.expected_url),
|
2016-12-06 21:41:44 -05:00
|
|
|
stream::Source::File(_) => panic!("expected rtsp url"),
|
|
|
|
};
|
2018-02-22 19:35:34 -05:00
|
|
|
let mut l = self.streams.lock();
|
2016-12-06 21:41:44 -05:00
|
|
|
match l.pop() {
|
|
|
|
Some(stream) => {
|
|
|
|
trace!("MockOpener returning next stream");
|
|
|
|
Ok(stream)
|
2021-02-17 01:15:54 -05:00
|
|
|
}
|
2016-12-06 21:41:44 -05:00
|
|
|
None => {
|
|
|
|
trace!("MockOpener shutting down");
|
|
|
|
self.shutdown.store(true, Ordering::SeqCst);
|
2018-02-21 01:46:14 -05:00
|
|
|
bail!("done")
|
2021-02-17 01:15:54 -05:00
|
|
|
}
|
2016-12-06 21:41:44 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Eq, PartialEq)]
|
|
|
|
struct Frame {
|
|
|
|
start_90k: i32,
|
|
|
|
duration_90k: i32,
|
|
|
|
is_key: bool,
|
|
|
|
}
|
|
|
|
|
2018-02-20 13:11:10 -05:00
|
|
|
fn get_frames(db: &db::LockedDatabase, id: CompositeId) -> Vec<Frame> {
|
2018-08-24 01:34:40 -04:00
|
|
|
db.with_recording_playback(id, &mut |rec| {
|
2017-03-01 02:28:25 -05:00
|
|
|
let mut it = recording::SampleIndexIterator::new();
|
|
|
|
let mut frames = Vec::new();
|
|
|
|
while it.next(&rec.video_index).unwrap() {
|
2021-02-17 01:15:54 -05:00
|
|
|
frames.push(Frame {
|
2017-03-01 02:28:25 -05:00
|
|
|
start_90k: it.start_90k,
|
|
|
|
duration_90k: it.duration_90k,
|
|
|
|
is_key: it.is_key(),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
Ok(frames)
|
2021-02-17 01:15:54 -05:00
|
|
|
})
|
|
|
|
.unwrap()
|
2016-12-06 21:41:44 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn basic() {
|
|
|
|
testutil::init();
|
2016-12-30 00:05:57 -05:00
|
|
|
// 2015-04-25 00:00:00 UTC
|
2018-03-23 16:31:23 -04:00
|
|
|
let clocks = clock::SimulatedClocks::new(time::Timespec::new(1429920000, 0));
|
2021-02-17 01:15:54 -05:00
|
|
|
clocks.sleep(time::Duration::seconds(86400)); // to 2015-04-26 00:00:00 UTC
|
2016-12-29 20:14:36 -05:00
|
|
|
|
2021-02-17 01:15:54 -05:00
|
|
|
let stream = stream::FFMPEG
|
|
|
|
.open(stream::Source::File("src/testdata/clip.mp4"))
|
|
|
|
.unwrap();
|
2016-12-30 00:05:57 -05:00
|
|
|
let mut stream = ProxyingStream::new(&clocks, time::Duration::seconds(2), stream);
|
2021-02-17 01:15:54 -05:00
|
|
|
stream.ts_offset = 123456; // starting pts of the input should be irrelevant
|
2016-12-06 21:41:44 -05:00
|
|
|
stream.ts_offset_pkts_left = u32::max_value();
|
|
|
|
stream.pkts_left = u32::max_value();
|
2021-02-17 01:15:54 -05:00
|
|
|
let opener = MockOpener {
|
2016-12-06 21:41:44 -05:00
|
|
|
expected_url: "rtsp://foo:bar@test-camera/main".to_owned(),
|
|
|
|
streams: Mutex::new(vec![stream]),
|
|
|
|
shutdown: Arc::new(AtomicBool::new(false)),
|
|
|
|
};
|
2018-03-23 16:31:23 -04:00
|
|
|
let db = testutil::TestDb::new(clocks.clone());
|
|
|
|
let env = super::Environment {
|
2016-12-06 21:41:44 -05:00
|
|
|
opener: &opener,
|
|
|
|
db: &db.db,
|
|
|
|
shutdown: &opener.shutdown,
|
|
|
|
};
|
|
|
|
let mut stream;
|
|
|
|
{
|
|
|
|
let l = db.db.lock();
|
|
|
|
let camera = l.cameras_by_id().get(&testutil::TEST_CAMERA_ID).unwrap();
|
2018-01-23 14:05:07 -05:00
|
|
|
let s = l.streams_by_id().get(&testutil::TEST_STREAM_ID).unwrap();
|
2021-02-17 01:15:54 -05:00
|
|
|
let dir = db
|
|
|
|
.dirs_by_stream_id
|
|
|
|
.get(&testutil::TEST_STREAM_ID)
|
|
|
|
.unwrap()
|
|
|
|
.clone();
|
|
|
|
stream = super::Streamer::new(
|
|
|
|
&env,
|
|
|
|
dir,
|
|
|
|
db.syncer_channel.clone(),
|
|
|
|
testutil::TEST_STREAM_ID,
|
|
|
|
camera,
|
|
|
|
s,
|
|
|
|
0,
|
|
|
|
3,
|
|
|
|
None,
|
|
|
|
)
|
|
|
|
.unwrap();
|
2016-12-06 21:41:44 -05:00
|
|
|
}
|
|
|
|
stream.run();
|
2018-02-22 19:35:34 -05:00
|
|
|
assert!(opener.streams.lock().is_empty());
|
2016-12-06 21:41:44 -05:00
|
|
|
db.syncer_channel.flush();
|
|
|
|
let db = db.db.lock();
|
|
|
|
|
|
|
|
// Compare frame-by-frame. Note below that while the rotation is scheduled to happen near
|
2016-12-29 16:07:25 -05:00
|
|
|
// 3-second boundaries (such as 2016-04-26 00:00:03), rotation happens somewhat later:
|
|
|
|
// * the first rotation is always skipped
|
|
|
|
// * the second rotation is deferred until a key frame.
|
2021-02-17 01:15:54 -05:00
|
|
|
#[rustfmt::skip]
|
track cumulative duration and runs
This is useful for a combo scrub bar-based UI (#32) + live view UI (#59)
in a non-obvious way. When constructing a HTML Media Source Extensions
API SourceBuffer, the caller can specify a "mode" of either "segments"
or "sequence":
In "sequence" mode, playback assumes segments are added sequentially.
This is good enough for a live view-only UI (#59) but not for a scrub
bar UI in which you may want to seek backward to a segment you've never
seen before. You will then need to insert a segment out-of-sequence.
Imagine what happens when the user goes forward again until the end of
the segment inserted immediately before it. The user should see the
chronologically next segment or a pause for loading if it's unavailable.
The best approximation of this is to track the mapping of timestamps to
segments and insert a VTTCue with an enter/exit handler that seeks to
the right position. But seeking isn't instantaneous; the user will
likely briefly see first the segment they seeked to before. That's
janky. Additionally, the "canplaythrough" event will behave strangely.
In "segments" mode, playback respects the timestamps we set:
* The obvious choice is to use wall clock timestamps. This is fine if
they're known to be fixed and correct. They're not. The
currently-recording segment may be "unanchored", meaning its start
timestamp is not yet fixed. Older timestamps may overlap if the system
clock was stepped between runs. The latter isn't /too/ bad from a user
perspective, though it's confusing as a developer. We probably will
only end up showing the more recent recording for a given
timestamp anyway. But the former is quite annoying. It means we have
to throw away part of the SourceBuffer that we may want to seek back
(causing UI pauses when that happens) or keep our own spare copy of it
(memory bloat). I'd like to avoid the whole mess.
* Another approach is to use timestamps that are guaranteed to be in
the correct order but that may have gaps. In particular, a timestamp
of (recording_id * max_recording_duration) + time_within_recording.
But again seeking isn't instantaneous. In my experiments, there's a
visible pause between segments that drives me nuts.
* Finally, the approach that led me to this schema change. Use
timestamps that place each segment after the one before, possibly with
an intentional gap between runs (to force a wait where we have an
actual gap). This should make the browser's natural playback behavior
work properly: it never goes to an incorrect place, and it only waits
when/if we want it to. We have to maintain a mapping between its
timestamps and segment ids but that's doable.
This commit is only the schema change; the new data aren't exposed in
the API yet, much less used by a UI.
Note that stream.next_recording_id became stream.cum_recordings. I made
a slight definition change in the process: recording ids for new streams
start at 0 rather than 1. Various tests changed accordingly.
The upgrade process makes a best effort to backfill these new fields,
but of course it doesn't know the total duration or number of runs of
previously deleted rows. That's good enough.
2020-06-09 19:17:32 -04:00
|
|
|
assert_eq!(get_frames(&db, CompositeId::new(testutil::TEST_STREAM_ID, 0)), &[
|
2021-02-17 01:15:54 -05:00
|
|
|
Frame { start_90k: 0, duration_90k: 90379, is_key: true },
|
|
|
|
Frame { start_90k: 90379, duration_90k: 89884, is_key: false },
|
|
|
|
Frame { start_90k: 180263, duration_90k: 89749, is_key: false },
|
|
|
|
Frame { start_90k: 270012, duration_90k: 89981, is_key: false }, // pts_time 3.0001...
|
|
|
|
Frame { start_90k: 359993, duration_90k: 90055, is_key: true },
|
|
|
|
Frame { start_90k: 450048, duration_90k: 89967, is_key: false },
|
|
|
|
Frame { start_90k: 540015, duration_90k: 90021, is_key: false }, // pts_time 6.0001...
|
|
|
|
Frame { start_90k: 630036, duration_90k: 89958, is_key: false },
|
2016-12-06 21:41:44 -05:00
|
|
|
]);
|
2021-02-17 01:15:54 -05:00
|
|
|
#[rustfmt::skip]
|
track cumulative duration and runs
This is useful for a combo scrub bar-based UI (#32) + live view UI (#59)
in a non-obvious way. When constructing a HTML Media Source Extensions
API SourceBuffer, the caller can specify a "mode" of either "segments"
or "sequence":
In "sequence" mode, playback assumes segments are added sequentially.
This is good enough for a live view-only UI (#59) but not for a scrub
bar UI in which you may want to seek backward to a segment you've never
seen before. You will then need to insert a segment out-of-sequence.
Imagine what happens when the user goes forward again until the end of
the segment inserted immediately before it. The user should see the
chronologically next segment or a pause for loading if it's unavailable.
The best approximation of this is to track the mapping of timestamps to
segments and insert a VTTCue with an enter/exit handler that seeks to
the right position. But seeking isn't instantaneous; the user will
likely briefly see first the segment they seeked to before. That's
janky. Additionally, the "canplaythrough" event will behave strangely.
In "segments" mode, playback respects the timestamps we set:
* The obvious choice is to use wall clock timestamps. This is fine if
they're known to be fixed and correct. They're not. The
currently-recording segment may be "unanchored", meaning its start
timestamp is not yet fixed. Older timestamps may overlap if the system
clock was stepped between runs. The latter isn't /too/ bad from a user
perspective, though it's confusing as a developer. We probably will
only end up showing the more recent recording for a given
timestamp anyway. But the former is quite annoying. It means we have
to throw away part of the SourceBuffer that we may want to seek back
(causing UI pauses when that happens) or keep our own spare copy of it
(memory bloat). I'd like to avoid the whole mess.
* Another approach is to use timestamps that are guaranteed to be in
the correct order but that may have gaps. In particular, a timestamp
of (recording_id * max_recording_duration) + time_within_recording.
But again seeking isn't instantaneous. In my experiments, there's a
visible pause between segments that drives me nuts.
* Finally, the approach that led me to this schema change. Use
timestamps that place each segment after the one before, possibly with
an intentional gap between runs (to force a wait where we have an
actual gap). This should make the browser's natural playback behavior
work properly: it never goes to an incorrect place, and it only waits
when/if we want it to. We have to maintain a mapping between its
timestamps and segment ids but that's doable.
This commit is only the schema change; the new data aren't exposed in
the API yet, much less used by a UI.
Note that stream.next_recording_id became stream.cum_recordings. I made
a slight definition change in the process: recording ids for new streams
start at 0 rather than 1. Various tests changed accordingly.
The upgrade process makes a best effort to backfill these new fields,
but of course it doesn't know the total duration or number of runs of
previously deleted rows. That's good enough.
2020-06-09 19:17:32 -04:00
|
|
|
assert_eq!(get_frames(&db, CompositeId::new(testutil::TEST_STREAM_ID, 1)), &[
|
2021-02-17 01:15:54 -05:00
|
|
|
Frame { start_90k: 0, duration_90k: 90011, is_key: true },
|
|
|
|
Frame { start_90k: 90011, duration_90k: 0, is_key: false },
|
2016-12-06 21:41:44 -05:00
|
|
|
]);
|
2016-12-29 20:14:36 -05:00
|
|
|
let mut recordings = Vec::new();
|
track cumulative duration and runs
This is useful for a combo scrub bar-based UI (#32) + live view UI (#59)
in a non-obvious way. When constructing a HTML Media Source Extensions
API SourceBuffer, the caller can specify a "mode" of either "segments"
or "sequence":
In "sequence" mode, playback assumes segments are added sequentially.
This is good enough for a live view-only UI (#59) but not for a scrub
bar UI in which you may want to seek backward to a segment you've never
seen before. You will then need to insert a segment out-of-sequence.
Imagine what happens when the user goes forward again until the end of
the segment inserted immediately before it. The user should see the
chronologically next segment or a pause for loading if it's unavailable.
The best approximation of this is to track the mapping of timestamps to
segments and insert a VTTCue with an enter/exit handler that seeks to
the right position. But seeking isn't instantaneous; the user will
likely briefly see first the segment they seeked to before. That's
janky. Additionally, the "canplaythrough" event will behave strangely.
In "segments" mode, playback respects the timestamps we set:
* The obvious choice is to use wall clock timestamps. This is fine if
they're known to be fixed and correct. They're not. The
currently-recording segment may be "unanchored", meaning its start
timestamp is not yet fixed. Older timestamps may overlap if the system
clock was stepped between runs. The latter isn't /too/ bad from a user
perspective, though it's confusing as a developer. We probably will
only end up showing the more recent recording for a given
timestamp anyway. But the former is quite annoying. It means we have
to throw away part of the SourceBuffer that we may want to seek back
(causing UI pauses when that happens) or keep our own spare copy of it
(memory bloat). I'd like to avoid the whole mess.
* Another approach is to use timestamps that are guaranteed to be in
the correct order but that may have gaps. In particular, a timestamp
of (recording_id * max_recording_duration) + time_within_recording.
But again seeking isn't instantaneous. In my experiments, there's a
visible pause between segments that drives me nuts.
* Finally, the approach that led me to this schema change. Use
timestamps that place each segment after the one before, possibly with
an intentional gap between runs (to force a wait where we have an
actual gap). This should make the browser's natural playback behavior
work properly: it never goes to an incorrect place, and it only waits
when/if we want it to. We have to maintain a mapping between its
timestamps and segment ids but that's doable.
This commit is only the schema change; the new data aren't exposed in
the API yet, much less used by a UI.
Note that stream.next_recording_id became stream.cum_recordings. I made
a slight definition change in the process: recording ids for new streams
start at 0 rather than 1. Various tests changed accordingly.
The upgrade process makes a best effort to backfill these new fields,
but of course it doesn't know the total duration or number of runs of
previously deleted rows. That's good enough.
2020-06-09 19:17:32 -04:00
|
|
|
db.list_recordings_by_id(testutil::TEST_STREAM_ID, 0..2, &mut |r| {
|
2016-12-29 20:14:36 -05:00
|
|
|
recordings.push(r);
|
|
|
|
Ok(())
|
2021-02-17 01:15:54 -05:00
|
|
|
})
|
|
|
|
.unwrap();
|
2016-12-29 20:14:36 -05:00
|
|
|
assert_eq!(2, recordings.len());
|
track cumulative duration and runs
This is useful for a combo scrub bar-based UI (#32) + live view UI (#59)
in a non-obvious way. When constructing a HTML Media Source Extensions
API SourceBuffer, the caller can specify a "mode" of either "segments"
or "sequence":
In "sequence" mode, playback assumes segments are added sequentially.
This is good enough for a live view-only UI (#59) but not for a scrub
bar UI in which you may want to seek backward to a segment you've never
seen before. You will then need to insert a segment out-of-sequence.
Imagine what happens when the user goes forward again until the end of
the segment inserted immediately before it. The user should see the
chronologically next segment or a pause for loading if it's unavailable.
The best approximation of this is to track the mapping of timestamps to
segments and insert a VTTCue with an enter/exit handler that seeks to
the right position. But seeking isn't instantaneous; the user will
likely briefly see first the segment they seeked to before. That's
janky. Additionally, the "canplaythrough" event will behave strangely.
In "segments" mode, playback respects the timestamps we set:
* The obvious choice is to use wall clock timestamps. This is fine if
they're known to be fixed and correct. They're not. The
currently-recording segment may be "unanchored", meaning its start
timestamp is not yet fixed. Older timestamps may overlap if the system
clock was stepped between runs. The latter isn't /too/ bad from a user
perspective, though it's confusing as a developer. We probably will
only end up showing the more recent recording for a given
timestamp anyway. But the former is quite annoying. It means we have
to throw away part of the SourceBuffer that we may want to seek back
(causing UI pauses when that happens) or keep our own spare copy of it
(memory bloat). I'd like to avoid the whole mess.
* Another approach is to use timestamps that are guaranteed to be in
the correct order but that may have gaps. In particular, a timestamp
of (recording_id * max_recording_duration) + time_within_recording.
But again seeking isn't instantaneous. In my experiments, there's a
visible pause between segments that drives me nuts.
* Finally, the approach that led me to this schema change. Use
timestamps that place each segment after the one before, possibly with
an intentional gap between runs (to force a wait where we have an
actual gap). This should make the browser's natural playback behavior
work properly: it never goes to an incorrect place, and it only waits
when/if we want it to. We have to maintain a mapping between its
timestamps and segment ids but that's doable.
This commit is only the schema change; the new data aren't exposed in
the API yet, much less used by a UI.
Note that stream.next_recording_id became stream.cum_recordings. I made
a slight definition change in the process: recording ids for new streams
start at 0 rather than 1. Various tests changed accordingly.
The upgrade process makes a best effort to backfill these new fields,
but of course it doesn't know the total duration or number of runs of
previously deleted rows. That's good enough.
2020-06-09 19:17:32 -04:00
|
|
|
assert_eq!(0, recordings[0].id.recording());
|
2016-12-29 20:14:36 -05:00
|
|
|
assert_eq!(recording::Time(128700575999999), recordings[0].start);
|
|
|
|
assert_eq!(0, recordings[0].flags);
|
track cumulative duration and runs
This is useful for a combo scrub bar-based UI (#32) + live view UI (#59)
in a non-obvious way. When constructing a HTML Media Source Extensions
API SourceBuffer, the caller can specify a "mode" of either "segments"
or "sequence":
In "sequence" mode, playback assumes segments are added sequentially.
This is good enough for a live view-only UI (#59) but not for a scrub
bar UI in which you may want to seek backward to a segment you've never
seen before. You will then need to insert a segment out-of-sequence.
Imagine what happens when the user goes forward again until the end of
the segment inserted immediately before it. The user should see the
chronologically next segment or a pause for loading if it's unavailable.
The best approximation of this is to track the mapping of timestamps to
segments and insert a VTTCue with an enter/exit handler that seeks to
the right position. But seeking isn't instantaneous; the user will
likely briefly see first the segment they seeked to before. That's
janky. Additionally, the "canplaythrough" event will behave strangely.
In "segments" mode, playback respects the timestamps we set:
* The obvious choice is to use wall clock timestamps. This is fine if
they're known to be fixed and correct. They're not. The
currently-recording segment may be "unanchored", meaning its start
timestamp is not yet fixed. Older timestamps may overlap if the system
clock was stepped between runs. The latter isn't /too/ bad from a user
perspective, though it's confusing as a developer. We probably will
only end up showing the more recent recording for a given
timestamp anyway. But the former is quite annoying. It means we have
to throw away part of the SourceBuffer that we may want to seek back
(causing UI pauses when that happens) or keep our own spare copy of it
(memory bloat). I'd like to avoid the whole mess.
* Another approach is to use timestamps that are guaranteed to be in
the correct order but that may have gaps. In particular, a timestamp
of (recording_id * max_recording_duration) + time_within_recording.
But again seeking isn't instantaneous. In my experiments, there's a
visible pause between segments that drives me nuts.
* Finally, the approach that led me to this schema change. Use
timestamps that place each segment after the one before, possibly with
an intentional gap between runs (to force a wait where we have an
actual gap). This should make the browser's natural playback behavior
work properly: it never goes to an incorrect place, and it only waits
when/if we want it to. We have to maintain a mapping between its
timestamps and segment ids but that's doable.
This commit is only the schema change; the new data aren't exposed in
the API yet, much less used by a UI.
Note that stream.next_recording_id became stream.cum_recordings. I made
a slight definition change in the process: recording ids for new streams
start at 0 rather than 1. Various tests changed accordingly.
The upgrade process makes a best effort to backfill these new fields,
but of course it doesn't know the total duration or number of runs of
previously deleted rows. That's good enough.
2020-06-09 19:17:32 -04:00
|
|
|
assert_eq!(1, recordings[1].id.recording());
|
2016-12-29 20:14:36 -05:00
|
|
|
assert_eq!(recording::Time(128700576719993), recordings[1].start);
|
|
|
|
assert_eq!(db::RecordingFlags::TrailingZero as i32, recordings[1].flags);
|
2016-12-06 21:41:44 -05:00
|
|
|
}
|
|
|
|
}
|