Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,19 @@ are the real limits on concurrent bystanders, and have not been load-tested. For
reverse proxy in front of `/watch/`: segments are marked cacheable for a
minute, and everyone given the same link requests the same URLs.

**Recording.** Each slot's record option is never, when armed, or always.
"When armed" follows the vehicle's own HEARTBEAT on the entry's MAVLink
session (the autopilot component, and the entry's FC system ID when one
is set). An MPEG-TS recording starts at the latest keyframe still held in
memory, which is usually just before arming, or else at the next one; a
Matroska recording starts at the next complete cluster. Recording stops
at disarm, so each flight gets its own segments. The
last armed state is kept through a telemetry dropout, so a link lost in
flight does not stop the recording. The proxy has to see the session:
without one, a "when armed" slot never records. From the CLI it is the
`record` and `record_armed` slot flags, e.g.
`./keydb.py videoflag 11024 0 record_armed` alongside `record`.

**Disk.** Video has its own budget, separate from telemetry, so a busy
camera can never evict a user's tlogs. Set it per entry in the web UI:
turning video on starts an entry at 1 GB, owners can go up to 4 GB, and
Expand Down
3 changes: 3 additions & 0 deletions keydb.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@
refused; with none set there is nothing to judge it against.
*/
#define VIDEO_SLOT_OPEN_PUB (1u << 4)
// With VIDEO_SLOT_RECORD: record only while the vehicle's MAVLink session
// reports it armed
#define VIDEO_SLOT_REC_ARMED (1u << 5)

// entry-wide bits, stored in the top byte
#define VIDEO_OPT_SHIFT 24
Expand Down
3 changes: 3 additions & 0 deletions keydb_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,16 @@
# Admit a publisher that offers no credential with no check at all --
# neither a MAVLink session nor a password. Off by default, per slot.
VIDEO_SLOT_OPEN_PUB = 1 << 4
# With VIDEO_SLOT_RECORD: record only while the vehicle reports armed.
VIDEO_SLOT_REC_ARMED = 1 << 5

VIDEO_SLOT_FLAG_NAMES = {
"srt": VIDEO_SLOT_SRT,
"record": VIDEO_SLOT_RECORD,
"raw_tcp": VIDEO_SLOT_RAW_TCP,
"session_ok": VIDEO_SLOT_SESSION_OK,
"open_publish": VIDEO_SLOT_OPEN_PUB,
"record_armed": VIDEO_SLOT_REC_ARMED,
}

VIDEO_OPT_SHIFT = 24
Expand Down
187 changes: 181 additions & 6 deletions supportproxy.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
#include "videostream.h"
#include "videomux.h"

#include <set>
#include <vector>

/*
Expand Down Expand Up @@ -90,6 +91,7 @@ struct listen_port {
time_t video_respawn_after; // backoff so a child that dies at once
// can't be re-forked in a tight loop
struct VideoHlsMark *video_hls_mark; // survives the child, see video.h
struct EntryLive *live; // shared with every child of the entry, see video.h
uint32_t video_ports[KEY_MAX_VIDEO_PORTS];
uint32_t video_flags;
uint32_t video_flags_hi; // slots past KEY_VIDEO_PORTS_INLINE
Expand Down Expand Up @@ -184,13 +186,43 @@ static void video_stop_child(struct listen_port *p, const char *why)
kill(p->video_pid, SIGTERM);
}

// Set the armed state under a new generation; returns the previous state.
static uint32_t entry_live_reset(struct listen_port *p, uint32_t state)
{
uint32_t cur = __atomic_load_n(&p->live->armed, __ATOMIC_ACQUIRE);
while (!__atomic_compare_exchange_n(&p->live->armed, &cur,
entry_armed_word(entry_armed_gen(cur) + 1, state),
false, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
}
return entry_armed_state(cur);
}

static void entry_live_update(struct listen_port *p, uint32_t flags, uint32_t fc_sysid)
{
if (p->live == nullptr) {
return;
}
__atomic_store_n(&p->live->video_on, (flags & KEY_FLAG_VIDEO) ? 1u : 0u, __ATOMIC_RELEASE);
if (__atomic_load_n(&p->live->fc_sysid, __ATOMIC_ACQUIRE) == fc_sysid) {
return;
}
// A different FC selected, session running or not: the old one's armed
// state no longer applies. The new filter first, so a session that sees
// the new generation also sees it.
__atomic_store_n(&p->live->fc_sysid, fc_sysid, __ATOMIC_RELEASE);
if (entry_live_reset(p, ENTRY_DISARMED) == ENTRY_ARMED) {
printf("[%d] %s vehicle disarmed (FC sysid changed)\n", p->port2, time_string());
}
}

static void upsert_port(int port1, int port2, uint32_t flags, uint32_t fc_sysid,
float tz_offset_hours, const uint32_t *video_ports,
uint32_t video_flags, uint32_t video_flags_hi)
{
for (auto *p = ports; p; p=p->next) {
if (p->port2 == port2) {
p->seen = true;
entry_live_update(p, flags, fc_sysid);
if (video_cfg_differs(p, flags, video_ports, video_flags,
video_flags_hi)) {
// Ports/enable/slot options changed: the running child
Expand All @@ -205,6 +237,10 @@ static void upsert_port(int port1, int port2, uint32_t flags, uint32_t fc_sysid,
// came back: re-add as a fresh listener
printf("[%d] re-added (port1=%d)\n", port2, port1);
p->removed = false;
// a new entry on this port: forget the old one's vehicle
if (p->live != nullptr) {
entry_live_reset(p, ENTRY_ARMED_UNKNOWN);
}
p->port1 = port1;
p->flags = flags;
p->fc_sysid = fc_sysid;
Expand Down Expand Up @@ -248,6 +284,13 @@ static void upsert_port(int port1, int port2, uint32_t flags, uint32_t fc_sysid,
p->video_pid = 0;
p->video_respawn_after = 0;
p->video_hls_mark = nullptr;
// before any child is forked, so all of them share it
p->live = entry_live_alloc();
if (p->live == nullptr) {
printf("[%d] live state mapping failed - %s; record-when-armed disabled\n",
port2, strerror(errno));
}
entry_live_update(p, flags, fc_sysid);
memcpy(p->video_ports, video_ports, sizeof(p->video_ports));
p->video_flags = video_flags;
p->video_flags_hi = video_flags_hi;
Expand Down Expand Up @@ -405,7 +448,12 @@ static void main_loop(struct listen_port *p)
// though nothing here writes video: with bidi signing, the video
// side needs this session to reach an authenticated state, and on
// the TCP path that only happens inside the parse block below.
const bool video_enabled = (p->flags & KEY_FLAG_VIDEO) != 0;
// read live: video can be turned on during a session, and
// record-when-armed then needs the heartbeats
auto video_enabled = [&]() {
return p->live ? __atomic_load_n(&p->live->video_on, __ATOMIC_ACQUIRE) != 0
: (p->flags & KEY_FLAG_VIDEO) != 0;
};
if (binlog_enabled) {
// Per-entry sysid filter for SYSTEM_TIME-based reboot
// detection. 0 (default) accepts any sysid.
Expand Down Expand Up @@ -447,6 +495,108 @@ static void main_loop(struct listen_port *p)
double last_conn_save_s = 0;
const pid_t my_pid = getpid();

/*
Vehicle armed state, from the autopilot's HEARTBEAT, for the video
child's record-when-armed slots, published to EntryLive. With no
fc_sysid filter any armed vehicle counts.

The shared state is the last session's and may say armed. With no
filter, a new session holds back a disarm for ARMED_SETTLE_S after
its first heartbeat, so a vehicle still armed elsewhere on the link
is heard first and a reconnect does not split its flight. With a
filter the selected FC's word is final.
*/
const double ARMED_SETTLE_S = 3;
double first_hb_s = 0; // monotonic: a clock step must not move the deadline
bool inherited_armed = false; // shared state said armed at our first heartbeat
double settle_since_s = 0; // a settle wake happened: idle waits are now exact
uint32_t armed_gen = p->live ? entry_armed_gen(__atomic_load_n(&p->live->armed,
__ATOMIC_ACQUIRE)) : 0;
uint32_t armed_filter = p->live ? __atomic_load_n(&p->live->fc_sysid, __ATOMIC_ACQUIRE) : 0;
std::set<uint32_t> armed_sysids;
auto shared_state = [&]() {
return entry_armed_state(__atomic_load_n(&p->live->armed, __ATOMIC_ACQUIRE));
};
auto set_shared_armed = [&](bool armed, const char *why) {
const uint32_t want = armed ? ENTRY_ARMED : ENTRY_DISARMED;
uint32_t cur = __atomic_load_n(&p->live->armed, __ATOMIC_ACQUIRE);
if (entry_armed_gen(cur) != armed_gen || entry_armed_state(cur) == want) {
return; // a generation change is picked up on the next pass
}
if (armed) {
// count before state: the video child reads them the other way
__atomic_add_fetch(&p->live->arm_count, 1, __ATOMIC_RELEASE);
}
const uint32_t shared = entry_armed_state(cur);
if (!__atomic_compare_exchange_n(&p->live->armed, &cur,
entry_armed_word(armed_gen, want),
false, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
return; // the parent changed it under us
}
if (armed || shared == ENTRY_ARMED) {
printf("[%d] %s vehicle %s%s\n", p->port2, time_string(),
armed ? "armed" : "disarmed", why);
}
};
// final: the session is ending, so a held-back disarm is published now
auto publish_armed = [&](bool final = false) {
if (p->live == nullptr) {
return;
}
const uint32_t gen = entry_armed_gen(__atomic_load_n(&p->live->armed, __ATOMIC_ACQUIRE));
if (gen != armed_gen) {
// a different FC selected (the parent has disarmed): the old
// one's state no longer applies
armed_gen = gen;
armed_filter = __atomic_load_n(&p->live->fc_sysid, __ATOMIC_ACQUIRE);
armed_sysids.clear();
first_hb_s = 0;
return;
}
const uint32_t want = armed_filter;
if (first_hb_s == 0) {
return; // nothing heard yet: leave the last known state
}
const bool armed = !armed_sysids.empty();
if (!armed && !final && inherited_armed && want == 0
&& monotonic_seconds() - first_hb_s < ARMED_SETTLE_S) {
return;
}
set_shared_armed(armed, "");
};
// seconds until a held-back disarm is due (a token wait once it is
// overdue), or 0 if none is held
auto armed_settle_left = [&]() -> double {
if (p->live == nullptr || first_hb_s == 0 || !inherited_armed || armed_filter != 0
|| !armed_sysids.empty() || shared_state() != ENTRY_ARMED) {
return 0;
}
const double left = ARMED_SETTLE_S - (monotonic_seconds() - first_hb_s);
return left > 0.001 ? left : 0.001;
};
auto observe_armed = [&](const mavlink_message_t &m) {
if (p->live == nullptr || m.msgid != MAVLINK_MSG_ID_HEARTBEAT
|| m.compid != MAV_COMP_ID_AUTOPILOT1
|| mavlink_msg_heartbeat_get_autopilot(&m) == MAV_AUTOPILOT_INVALID
|| mavlink_msg_heartbeat_get_type(&m) == MAV_TYPE_GCS) {
return;
}
publish_armed(); // applies a filter change first
if (armed_filter != 0 && m.sysid != armed_filter) {
return;
}
if (first_hb_s == 0) {
first_hb_s = monotonic_seconds();
inherited_armed = shared_state() == ENTRY_ARMED;
}
if (mavlink_msg_heartbeat_get_base_mode(&m) & MAV_MODE_FLAG_SAFETY_ARMED) {
armed_sysids.insert(m.sysid);
} else {
armed_sysids.erase(m.sysid);
}
publish_armed();
};

fdmax = MAX(fdmax, p->sock1_udp);
fdmax = MAX(fdmax, p->sock2_udp);
fdmax = MAX(fdmax, p->sock1_tcp);
Expand Down Expand Up @@ -563,11 +713,31 @@ static void main_loop(struct listen_port *p)
}
}

tval.tv_sec = 10;
tval.tv_usec = 0;
// wake for a held-back disarm rather than wait out the idle timeout,
// and then wait only for what is left of that timeout
const double idle_left = have_conn1 ? 10 - (now - last_pkt1) : 10;
const double settle = armed_settle_left();
const bool settle_wake = settle > 0 && settle < idle_left;
if (settle_wake) {
const long us = long(settle * 1e6) + 10000; // just past the deadline
tval.tv_sec = time_t(us / 1000000);
tval.tv_usec = suseconds_t(us % 1000000);
} else if (settle_since_s > 0 && have_conn1) {
const long us = long((idle_left > 0 ? idle_left : 0) * 1e6) + 10000;
tval.tv_sec = time_t(us / 1000000);
tval.tv_usec = suseconds_t(us % 1000000);
} else {
tval.tv_sec = 10;
tval.tv_usec = 0;
}

ret = select(fdmax+1, &fds, NULL, NULL, &tval);
if (ret == -1 && errno == EINTR) continue;
if (ret == 0 && settle_wake) {
settle_since_s = now;
publish_armed();
continue;
}
if (ret <= 0) break;

now = time_seconds();
Expand Down Expand Up @@ -692,12 +862,13 @@ static void main_loop(struct listen_port *p)
// recording, or video (which needs the session to authenticate).
// Without one of those, the bytes are read off the socket but
// discarded.
if (conn2_count > 0 || binlog_enabled || tlog_enabled || video_enabled) {
if (conn2_count > 0 || binlog_enabled || tlog_enabled || video_enabled()) {
uint8_t *buf0 = buf;
while (n > 0 && mav1.receive_message(buf0, n, msg)) {
mav1_rx_msgs++;
ensure_tlog_open();
tlog_write_message(tlog_ptr(), msg);
observe_armed(msg);
if (binlog_handle_user_msg(msg)) {
continue; // strip REMOTE_LOG_* from user→engineer
}
Expand Down Expand Up @@ -894,12 +1065,13 @@ static void main_loop(struct listen_port *p)
// would kill the session. (The UDP path differs: it
// validates inside its latch block, so it authenticates
// regardless of this gate.)
if (conn2_count > 0 || binlog_enabled || tlog_enabled || video_enabled) {
if (conn2_count > 0 || binlog_enabled || tlog_enabled || video_enabled()) {
uint8_t *buf0 = buf;
while (n > 0 && mav1.receive_message(buf0, n, msg)) {
mav1_rx_msgs++;
ensure_tlog_open();
tlog_write_message(tlog_ptr(), msg);
observe_armed(msg);
if (binlog_handle_user_msg(msg)) {
continue; // strip REMOTE_LOG_* from user→engineer
}
Expand Down Expand Up @@ -1060,6 +1232,8 @@ static void main_loop(struct listen_port *p)
save_signing_timestamp() in mavlink.cpp. The web UI's
http-equiv refresh runs at the same cadence.
*/
// a held-back disarm or an FC change lands without another heartbeat
publish_armed();
{
double snap_now = time_seconds();
if (snap_now - last_conn_save_s > 5) {
Expand Down Expand Up @@ -1141,6 +1315,7 @@ static void main_loop(struct listen_port *p)
}
}
}
publish_armed(true);

if (count1 != 0 || count2 != 0) {
printf("[%d] %s Closed connection count1=%u count2=%u\n",
Expand Down Expand Up @@ -1270,7 +1445,7 @@ static void fork_video_child(struct listen_port *p)
for (auto *p2 = ports; p2; p2 = p2->next) {
close_sockets(p2);
}
video_child_main(p->port2, ready[1], p->video_hls_mark);
video_child_main(p->port2, ready[1], p->video_hls_mark, p->live);
// video_child_main is noreturn and _exit()s: never fall back
// into the parent's code with copied destructors that would
// close fd numbers we have since reused.
Expand Down
7 changes: 5 additions & 2 deletions tests/test_video_child.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,9 @@ class _Mav:

def __init__(self, signed=False):
from pymavlink import mavutil
# heartbeat fields, changeable while running
self.base_mode = 0
self.mav_type = mavutil.mavlink.MAV_TYPE_QUADROTOR
self.mavutil = mavutil
self.conn = mavutil.mavlink_connection(
'udpout:127.0.0.1:%d' % PORT_USER, source_system=1,
Expand All @@ -216,8 +219,8 @@ def _run(self):
while not self._stop.is_set():
try:
self.conn.mav.heartbeat_send(
m.MAV_TYPE_QUADROTOR, m.MAV_AUTOPILOT_ARDUPILOTMEGA,
0, 0, m.MAV_STATE_ACTIVE)
self.mav_type, m.MAV_AUTOPILOT_ARDUPILOTMEGA,
self.base_mode, 0, m.MAV_STATE_ACTIVE)
except Exception:
pass
time.sleep(0.3)
Expand Down
Loading
Loading