fix: let the UI tell zms which event is next/prev for gapless playback refs #4186

When an event is streamed by zms (the MJPEG/mpeg path, not the video.js MP4
player), zms advanced to the next/prev event itself with a hardcoded query:

  SELECT Id FROM Events WHERE MonitorId = <same> AND Id <>> <current> ...

That ignores the filter and sort the user is viewing, so gapless playback of a
cross-monitor filtered list skipped every event that did not belong to the
current event's monitor -- e.g. playing monitor A's event jumped straight to
A's next event, hopping over all the interleaved monitor B events. The earlier
getNearEvents fix only corrected the video.js path and the Prev/Next buttons;
this zms auto-advance was a separate path and still wrong.

Rather than reimplement filter/sort knowledge in C++, let the UI -- which
already computes the correct next/prev from the active filter via getNearEvents
-- tell zms which events those are. A new CMD_SET_EVENT command carries a
direction, a target event id, and the source event the hint was computed for;
EventStream stores them and checkEventLoaded loads the UI-provided event when
advancing. When the UI has not supplied a usable hint it falls back to the
existing by-monitor query, so behaviour is unchanged for clients that do not
send the command.

The event view sends CMD_SET_EVENT for both next and prev after each
getNearEvents response, but only when playback is served by zms (vid == null);
the video.js path already navigates correctly on its own.

Hardening in this path:

- Authorisation: zms only authorises the event the stream started on and loads
  forwarded targets without re-checking, so a client could hand it an event
  from a monitor it cannot view. ajax/stream.php now resolves the target's
  monitor and requires canView('Events', MonitorId) before forwarding (gated on
  ZM_OPT_USE_AUTH, matching zms).

- Filter boundaries: getNearEvents returns 0 when the filter has no neighbour
  in a direction. A hint now records whether the UI supplied a value, so an
  explicit 0 stops at the boundary instead of being treated as "no hint" and
  falling back to the same-monitor query (which would leave the filtered list).

- Stale hints: next and prev arrive as separate requests and can land out of
  order. Each hint carries the source event id; processCommand refuses to store
  one whose source is not the event playing (so a late command cannot overwrite
  a valid hint), and checkEventLoaded honours a stored hint only while its
  source still matches. The event view tags each hint with the getNearEvents
  response's own EventId, not the current event, so a slow response cannot send
  a self-referential hint that loops zms on one event.

- Deleted targets: a cached neighbour may be removed by retention or another
  user before it is used. checkEventLoaded checks existence first and falls back
  rather than hitting loadEventData's fatal "not found" path; ajax/stream.php
  treats a target that no longer exists as a filter boundary instead of
  returning an error that would flag the stream broken and stop UI polling.

- Cross-resolution MPEG: the mpeg encoder is created once at the first event's
  dimensions and cannot resize mid-stream. Frame and text-frame paths share a
  scaleToEncoder() helper that scales a later, differently sized image (a
  cross-monitor advance, or a boundary text frame built at another monitor's
  size) to the encoder's dimensions before encoding rather than overrunning its
  buffers.

- Portable packing: stream.php encodes the ids as big-endian 32-bit words
  instead of pack('J'), which 32-bit PHP (still supported in the status decode)
  cannot feed a 64-bit value.

Known limitation: in a multi-server install with non-shared storage a
cross-monitor neighbour can live on another server, whose recording this zms
cannot read. Such an advance degrades to failed frames; zms self-advance is
effectively same-server (or shared-storage) only. Routing it to the serving
server, as the video.js reload path does, is left to a separate change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Isaac ConnorandClaude Opus 4.8 committed 2026-10-23 18:43:43 -04:00
1 parent f9dc88629e
commit 64d3d772bb
8 files changed
+263 -19

No files matched your search

+109 -19
View File
@@ -458,6 +458,14 @@ bool EventStream::loadEventData(uint64_t event_id) {
return true;
} // bool EventStream::loadEventData( int event_id )
bool EventStream::eventExists(uint64_t event_id) {
MYSQL_RES *result = zmDbFetch(stringtf("SELECT 1 FROM `Events` WHERE `Id` = %" PRIu64, event_id));
if (!result) return false;
bool exists = mysql_num_rows(result) > 0;
mysql_free_result(result);
return exists;
}
void EventStream::processCommand(const CmdMsg *msg) {
Debug(2, "Got message, type %d, msg %d", msg->msg_type, msg->msg_data[0]);
@@ -698,6 +706,41 @@ void EventStream::processCommand(const CmdMsg *msg) {
send_frame = true;
break;
}
case CMD_SET_EVENT : {
// The UI tells us which event is next/prev in the filter/sort it is showing,
// so gapless advance follows that order rather than our same-monitor query
// (refs #4186). Payload: msg_data[1] = direction (0 next, 1 prev),
// msg_data[2..9] = target event id (64-bit big-endian, 0 = no neighbour in
// the filter), msg_data[10..15] = source event id (48-bit big-endian) this
// hint was computed against, so a hint for an event we have already left is
// discarded rather than applied to the wrong event.
unsigned char direction = (unsigned char)msg->msg_data[1];
uint64_t event_id = 0;
for (int i = 0; i < 8; i++)
event_id = (event_id << 8) | (unsigned char)msg->msg_data[2 + i];
uint64_t source_event_id = 0;
for (int i = 0; i < 6; i++)
source_event_id = (source_event_id << 8) | (unsigned char)msg->msg_data[10 + i];
// next and prev are sent as two separate AJAX requests and can arrive out of
// order. Only install a hint computed for the event we are currently playing;
// a command for an event we have already left (or have not reached) would
// otherwise overwrite the valid hint for the current event and make the next
// transition fall back to the same-monitor query (refs #4186). The 48-bit
// source truncates the id, but a collision only drops a legitimate hint (safe
// fallback), never installs a wrong one.
if (source_event_id != (event_data->event_id & 0xFFFFFFFFFFFFULL)) {
Debug(1, "Ignoring stale SET_EVENT %s = %" PRIu64 " for source %" PRIu64 "; current event is %" PRIu64,
direction == 0 ? "next" : "prev", event_id, source_event_id, event_data->event_id);
break;
}
EventHint &hint = (direction == 0) ? ui_next_hint : ui_prev_hint;
hint.have = true;
hint.event_id = event_id;
hint.source_event_id = source_event_id;
Debug(1, "Got SET_EVENT command, %s event = %" PRIu64 " (for source event %" PRIu64 ")",
direction == 0 ? "next" : "prev", event_id, source_event_id);
break;
}
case CMD_QUERY :
Debug(1, "Got QUERY command, sending STATUS");
break;
@@ -782,8 +825,13 @@ void EventStream::processCommand(const CmdMsg *msg) {
bool EventStream::checkEventLoaded() {
std::string sql;
// The neighbour hint the UI gave us for the direction we are moving, if any
// (CMD_SET_EVENT). It is honoured only while it is still bound to the event
// playing; otherwise we fall back to the same-monitor query (refs #4186).
const EventHint *hint = nullptr;
if (curr_frame_id <= 0) {
hint = &ui_prev_hint;
sql = stringtf(
"SELECT `Id` FROM `Events` WHERE `MonitorId` = %d AND `Id` < %" PRIu64 " ORDER BY `Id` DESC LIMIT 1",
event_data->monitor_id, event_data->event_id);
@@ -796,6 +844,7 @@ bool EventStream::checkEventLoaded() {
curr_frame_id = num_frames > 0 ? num_frames : 1;
return false;
}
hint = &ui_next_hint;
sql = stringtf(
"SELECT `Id` FROM `Events` WHERE `MonitorId` = %d AND `Id` > %" PRIu64 " ORDER BY `Id` ASC LIMIT 1",
event_data->monitor_id, event_data->event_id);
@@ -805,44 +854,75 @@ bool EventStream::checkEventLoaded() {
curr_frame_id, event_data->frames.size());
return false;
}
const char *direction = (curr_frame_id <= 0) ? "prev" : "next";
// Event change required.
if (forceEventChange || ((mode != MODE_SINGLE) && (mode != MODE_NONE))) {
Debug(1, "Checking for next event %s", sql.c_str());
// A hint applies only if the UI computed it for the event we are still on;
// a hint bound to an event we have already left is stale and ignored. It is
// not cleared on use: once we advance, its source no longer matches and the
// UI pushes a fresh pair for the new event.
// source_event_id is the 48-bit-truncated id the hint was computed for; mask
// the current id the same way processCommand does so the two comparisons agree.
bool use_hint = hint->have && (hint->source_event_id == (event_data->event_id & 0xFFFFFFFFFFFFULL));
uint64_t new_event_id = 0;
MYSQL_RES *result = zmDbFetch(sql);
if (!result) exit(-1);
if (mysql_num_rows(result) != 1) {
Debug(1, "No rows returned for %s", sql.c_str());
}
MYSQL_ROW dbrow = mysql_fetch_row(result);
if (mysql_errno(&dbconn)) {
Error("Can't fetch row: %s", mysql_error(&dbconn));
exit(mysql_errno(&dbconn));
if (use_hint) {
// The UI told us explicitly. event_id 0 means the filter has no neighbour
// in this direction, so stop at the boundary rather than falling back to
// the unfiltered same-monitor query (which would leave the filtered list).
new_event_id = hint->event_id;
if (new_event_id && !eventExists(new_event_id)) {
// Deleted since the UI fetched its neighbours: drop the hint and fall
// back rather than reaching loadEventData's fatal "not found" path.
Warning("UI-provided %s event %" PRIu64 " no longer exists; falling back to same-monitor query",
direction, new_event_id);
new_event_id = 0;
use_hint = false;
} else {
Debug(1, "Loading UI-provided %s event %" PRIu64 " (filter boundary if 0)", direction, new_event_id);
}
}
if (dbrow) {
uint64_t event_id = atoll(dbrow[0]);
Debug(1, "Loading new event %" PRIu64, event_id);
if (!use_hint) {
Debug(1, "Checking for next event %s", sql.c_str());
loadEventData(event_id);
MYSQL_RES *result = zmDbFetch(sql);
if (!result) exit(-1);
if (mysql_num_rows(result) != 1) {
Debug(1, "No rows returned for %s", sql.c_str());
}
MYSQL_ROW dbrow = mysql_fetch_row(result);
if (mysql_errno(&dbconn)) {
Error("Can't fetch row: %s", mysql_error(&dbconn));
exit(mysql_errno(&dbconn));
}
if (dbrow) new_event_id = atoll(dbrow[0]);
mysql_free_result(result);
}
if (new_event_id) {
Debug(1, "Loading new event %" PRIu64, new_event_id);
loadEventData(new_event_id);
int num_frames = (int)event_data->frames.size();
curr_frame_id = replay_rate < 0 ? (num_frames > 0 ? num_frames : 1) : 1;
Debug(2, "New frame id = %d", curr_frame_id);
start = std::chrono::steady_clock::now();
mysql_free_result(result);
return true;
} else {
Debug(2, "No next event loaded using %s. Pausing", sql.c_str());
// Either an explicit filter boundary (the UI sent 0) or no same-monitor
// event in this direction. Either way, pause here.
Debug(2, "No %s event to load (boundary or none). Pausing", direction);
int num_frames = (int)event_data->frames.size();
curr_frame_id = curr_frame_id <= 0 ? 1 : (num_frames > 0 ? num_frames : 1);
paused = true;
sendTextFrame("No more event data found");
} // end if found a new event or not
mysql_free_result(result);
forceEventChange = false;
} else {
Debug(2, "Pausing because mode is %s", StreamMode_Strings[mode].c_str());
@@ -921,6 +1001,8 @@ bool EventStream::sendFrame(Microseconds delta_us) {
if ( !vid_stream ) {
vid_stream = new VideoStream("pipe:", format, bitrate, effective_fps,
send_image->Colours(), send_image->SubpixelOrder(), send_image->Width(), send_image->Height());
vid_stream_width = send_image->Width();
vid_stream_height = send_image->Height();
fprintf(stdout, "Content-type: %s\r\n\r\n", vid_stream->MimeType());
if (!vid_stream->OpenStream()) {
Error("Failed to open video stream");
@@ -928,6 +1010,14 @@ bool EventStream::sendFrame(Microseconds delta_us) {
vid_stream = nullptr;
return false;
}
} else {
// The encoder is fixed at the first event's dimensions and cannot resize
// mid-stream (the Content-type header is already sent). A later event of a
// different resolution -- reachable now that gapless advance can cross
// monitors -- would otherwise be encoded against buffers sized for the
// original, overrunning them for a larger frame. Scale it to the encoder's
// dimensions instead (refs #4186). The text-frame path does the same.
scaleToEncoder(send_image);
}
vid_stream->EncodeFrame(send_image->Buffer(),
send_image->Size(),
+29
View File
@@ -82,6 +82,31 @@ class EventStream : public StreamBase {
StreamMode mode;
bool forceEventChange;
// A neighbour-event hint the UI pushes via CMD_SET_EVENT. The UI computes
// next/prev from the filter and sort the user is viewing and sends them here,
// so gapless advance follows that order across monitors instead of our own
// same-monitor query (refs #4186). Each hint is bound to the event it was
// computed for (source_event_id); checkEventLoaded honours it only while that
// source is still the event playing, so a hint that arrives after we have left
// that event is ignored rather than mis-steering the next transition. `have`
// separates "the UI says there is no neighbour here" (event_id 0 -> stop at
// the filter boundary) from "the UI has not told us" (fall back to the
// same-monitor query). Read and written only under mutex.
//
// Known limitation: in a multi-server install with non-shared storage a
// cross-monitor neighbour can live on another server, whose recording this
// zms cannot read (loadEventData builds local paths only). Such an advance
// degrades to failed frames; it is not re-routed to the serving server the
// way the video.js player's reload path is. zms self-advance is effectively
// same-server (or shared-storage) only; routing it is a separate change.
struct EventHint {
bool have = false;
uint64_t event_id = 0;
uint64_t source_event_id = 0;
};
EventHint ui_next_hint;
EventHint ui_prev_hint;
std::mutex mutex;
int curr_frame_id;
SystemTimePoint curr_stream_time;
@@ -92,6 +117,10 @@ class EventStream : public StreamBase {
protected:
bool loadEventData(uint64_t event_id);
// Cheap existence check so a UI-provided neighbour that retention (or another
// user) has deleted since the UI fetched it does not reach loadEventData's
// fatal "not found" path and kill the stream (refs #4186).
bool eventExists(uint64_t event_id);
bool loadInitialEventData(uint64_t init_event_id, int init_frame_id);
bool loadInitialEventData(int monitor_id, SystemTimePoint event_time);
+14
View File
@@ -311,6 +311,14 @@ Image *StreamBase::prepareImage(Image *image, int pre_scaled_by) {
return image;
} // end Image *StreamBase::prepareImage(Image *image, int pre_scaled_by)
void StreamBase::scaleToEncoder(Image *image) {
if (!vid_stream) return; // not opened yet; this frame will define the size
if (image->Width() == vid_stream_width && image->Height() == vid_stream_height) return;
Debug(2, "Scaling %ux%u frame to MPEG encoder dimensions %ux%u",
image->Width(), image->Height(), vid_stream_width, vid_stream_height);
image->Scale(vid_stream_width, vid_stream_height);
}
bool StreamBase::sendTextFrame(const char *frame_text) {
int width = 640;
int height = 480;
@@ -346,6 +354,12 @@ bool StreamBase::sendTextFrame(const char *frame_text) {
vid_stream = nullptr;
return false;
}
vid_stream_width = image.Width();
vid_stream_height = image.Height();
} else {
// A text frame for a later, larger monitor (after a cross-monitor gapless
// advance) would otherwise overrun the encoder's fixed buffers (refs #4186).
scaleToEncoder(&image);
}
/* double pts = */ vid_stream->EncodeFrame(image.Buffer(), image.Size());
} else {
+31
View File
@@ -110,6 +110,21 @@ class StreamBase {
CMD_ANALYZE_ON,
CMD_ANALYZE_OFF,
CMD_ZOOMSTOP,
// Tell an event stream which event to load next/prev, computed UI-side so the
// filter/sort the user is viewing is honoured without reimplementing filters
// in C++ (refs #4186). MSG payload:
// msg_data[1] = direction (0 = next, 1 = prev)
// msg_data[2..9] = target event id, big-endian uint64 (0 = the filter has
// no neighbour in this direction -> stop at the boundary)
// msg_data[10..15]= the event the UI computed this against, big-endian
// 48-bit (source event id). The stream honours a hint
// only while this still matches the event playing, so a
// hint that arrives after playback has moved on is
// ignored instead of mis-steering the next transition.
// 48 bits is ample for any real event id; a larger id
// would simply fail the match and fall back, never
// mis-match to a wrong event.
CMD_SET_EVENT,
CMD_QUERY=99
} MsgCommand;
@@ -170,6 +185,15 @@ class StreamBase {
TimePoint when_to_send_next_frame; // When to send next frame so if now < send_next_frame, skip
VideoStream *vid_stream;
// Dimensions vid_stream (the MPEG encoder) was opened with. It is created once
// from the first frame and cannot resize, and ActuallyEncodeFrame copies a
// buffer sized for these, so a later frame of a different size -- a
// cross-monitor gapless advance, or a text frame built at a different
// monitor's dimensions -- is scaled to these before encoding or it overruns
// that buffer (refs #4186). 0 until the encoder is created; every site that
// creates vid_stream must set them.
unsigned int vid_stream_width;
unsigned int vid_stream_height;
CmdMsg msg;
std::atomic<bool> got_command; // commands like zoom should output a frame even if paused; set on the command thread
@@ -196,6 +220,11 @@ class StreamBase {
void checkCommandQueue();
virtual void processCommand(const CmdMsg *msg)=0;
void reserveTempImgBuffer(size_t size);
// Scale image to the dimensions vid_stream was opened with, if it differs, so
// the MPEG encoder is never handed a frame sized differently from the buffers
// it allocated. A no-op until vid_stream exists (the first frame defines the
// size) and when the image already matches. See vid_stream_width/height.
void scaleToEncoder(Image *image);
public:
StreamBase():
@@ -243,6 +272,8 @@ class StreamBase {
last_fps_update = std::chrono::steady_clock::now();
vid_stream = nullptr;
vid_stream_width = 0;
vid_stream_height = 0;
msg = { 0, { 0 } };
}
virtual ~StreamBase();
+61
View File
@@ -96,6 +96,44 @@ case CMD_MAXFPS :
intval($_REQUEST['maxfps']),
1000000*( $_REQUEST['maxfps']-intval($_REQUEST['maxfps'])));
break;
case CMD_SET_EVENT :
# Tell zms which event is next (dir=0) or prev (dir=1) in the UI's filter/sort
# (refs #4186). Payload: dir byte, target event id (big-endian uint64, 0 = no
# neighbour in the filter), then the source event id the hint was computed
# against (big-endian 48-bit) so zms can discard stale hints.
global $user;
$dir = intval($_REQUEST['dir']);
# Keep ids as strings so packEventId*() need not go through a 32-bit intval().
$eventid = isset($_REQUEST['eventid']) ? $_REQUEST['eventid'] : 0;
$srcid = isset($_REQUEST['srcid']) ? $_REQUEST['srcid'] : 0;
# zms authorises only the event the stream started on; it loads whatever
# target we forward without re-checking. So a client could hand us an event
# from a monitor it cannot view and advance into that footage. Resolve the
# target's monitor and require view permission here, where the session user is
# known. Gated on ZM_OPT_USE_AUTH to match zms, which only validates event
# access when auth is on; 0 carries no event (filter boundary) and needs no
# check.
if (ZM_OPT_USE_AUTH && $eventid) {
$monitorId = dbFetchOne('SELECT `MonitorId` FROM `Events` WHERE `Id`=?', 'MonitorId', array($eventid));
if (!$monitorId) {
# Retention or another user deleted the neighbour between getNearEvents and
# now. That is a benign race, not a privilege problem, so do not ajaxError:
# getCmdResponse() would set zmsBroke=true and can stop the UI's status
# polling even though zms is fine. Forward it as a filter boundary (0) so
# zms pauses cleanly instead of advancing.
ZM\Debug('SET_EVENT target '.$eventid.' no longer exists; treating as filter boundary');
$eventid = 0;
} else if (!canView('Events', $monitorId)) {
if ($semaphore) sem_release($semaphore);
ajaxError('Insufficient privileges for event '.$eventid, HTTP_STATUS_OK, STREAM_ERR_INVALID);
}
}
ZM\Debug('Setting '.($dir ? 'prev' : 'next').' event to '.$eventid.' (source '.$srcid.')');
$msg = pack('lcC', MSG_CMD, $_REQUEST['command'], $dir)
.packEventId64($eventid)
.packEventId48($srcid);
break;
default :
ZM\Debug('Sending command ' . $_REQUEST['command']);
$msg = pack('lc', MSG_CMD, $_REQUEST['command']);
@@ -234,4 +272,27 @@ function ajaxCleanup() {
if ( !empty($localSocketFile) )
@unlink($localSocketFile);
}
# Big-endian uint64 as two 32-bit words. Avoids pack('J') (needs a 64-bit PHP
# int) and intval() truncation on 32-bit PHP, which this endpoint still supports
# (see the two-word MSG_DATA_EVENT decode above). On 32-bit PHP an id above 2^31
# cannot be represented at all, so the high word is simply 0.
function packEventId64($value) {
if (PHP_INT_SIZE >= 8) {
$v = intval($value);
return pack('NN', ($v >> 32) & 0xFFFFFFFF, $v & 0xFFFFFFFF);
}
return pack('NN', 0, intval($value));
}
# Big-endian 48-bit id (16-bit high word + 32-bit low word = 6 bytes), used for
# the source event id, which only needs to match zms' current event; see
# packEventId64 for the 32/64-bit handling.
function packEventId48($value) {
if (PHP_INT_SIZE >= 8) {
$v = intval($value);
return pack('nN', ($v >> 32) & 0xFFFF, $v & 0xFFFFFFFF);
}
return pack('nN', 0, intval($value));
}
?>
+1
View File
@@ -95,6 +95,7 @@ define('CMD_MAXFPS', 18);
define('CMD_ANALYZE_ON', 19);
define('CMD_ANALYZE_OFF', 20);
define('CMD_ZOOMSTOP', 21);
define('CMD_SET_EVENT', 22);
define('CMD_QUERY', 99);
//
+1
View File
@@ -131,6 +131,7 @@ const CMD_SCALE = <?php echo CMD_SCALE ?>;
const CMD_PREV = <?php echo CMD_PREV ?>;
const CMD_NEXT = <?php echo CMD_NEXT ?>;
const CMD_SEEK = <?php echo CMD_SEEK ?>;
const CMD_SET_EVENT = <?php echo CMD_SET_EVENT ?>;
const CMD_QUERY = <?php echo CMD_QUERY ?>;
const CMD_QUIT = <?php echo CMD_QUIT ?>;
const CMD_MAXFPS = <?php echo CMD_MAXFPS ?>;
+17
View File
@@ -955,6 +955,23 @@ function getNearEventsResponse(respObj, respText) {
$j('#prevBtn').prop('disabled', prevEventId == 0 ? true : false).attr('class', prevEventId == 0 ? 'unavail' : 'inactive');
$j('#nextBtn').prop('disabled', nextEventId == 0 ? true : false).attr('class', nextEventId == 0 ? 'unavail' : 'inactive');
// When playback is served by zms (not the video.js player), tell it which
// events are next/prev in the current filter/sort so its gapless auto-advance
// follows that order across monitors instead of its own same-monitor query
// (refs #4186). dir: 0 = next, 1 = prev. eventid 0 means the filter has no
// neighbour in that direction (zms then stops at the boundary). srcid binds
// the hint to the event these neighbours were computed for -- the response's
// own EventId, NOT the current eventData.Id. A slow nearevents response can
// arrive after the page has moved to another event; tagging it with the
// current id could send "for event B, next = B" (if B was A's next) and loop
// zms on B. Bound to its own source, zms discards a hint that no longer
// matches the event it is playing, so a superseded response is simply ignored.
var srcEventId = parseInt(respObj.nearevents.EventId);
if (vid == null && srcEventId == parseInt(eventData.Id)) {
streamReq({command: CMD_SET_EVENT, dir: 0, eventid: nextEventId, srcid: srcEventId});
streamReq({command: CMD_SET_EVENT, dir: 1, eventid: prevEventId, srcid: srcEventId});
}
}
function nearEventsQuery(eventId) {