From 5c585bebbc8ebeb378e70da9b2d8524adb7e005b Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 11 May 2026 11:51:47 +0200 Subject: [PATCH] fix(reflector): first-talker-wins arbitration for multi-monitor TGs dc3a8c0's SelectedTgIdleFilter closed the v1.3.10 mixing window only when the listener's selected TG was busy. When the selected TG is idle (or 0) and >=2 monitor TGs have simultaneous talkers, the filter let every frame through and the single Opus decoder mixed them -- a configuration MONITOR_TGS=1++,9+,110,112 hits this whenever 110 and 112 overlap, since svxlink's priority logic stays on the prio-1 TG 9. TGHandler now records a per-TG talker-start timestamp (local + trunk), retained across talker-clear so the flush-fanout filter can still identify the freshly-stopped TG. ReflectorClient gains EarliestMonitorTalkerFilter(tg): returns true iff tg is the earliest- started TG (local OR trunk) among the client's monitored set; ties broken by smaller TG id. Wired alongside the existing SelectedTgIdleFilter at all nine UDP fanout sites. The selected-TG arm of the OR is untouched, so svxlink priority and the pre-v1.3.10 single-TG-at-a-time invariant both keep working. Adds test_43 (selected idle + two simultaneous monitor talkers -> only earliest delivered) and test_44 (same, passive observer). test_39 and test_40-42 remain green; full test_trunk.py: 47/47. --- src/svxlink/reflector/Reflector.cpp | 12 +- src/svxlink/reflector/ReflectorClient.cpp | 80 ++++++++++++ src/svxlink/reflector/ReflectorClient.h | 28 ++++ src/svxlink/reflector/SatelliteClient.cpp | 8 +- src/svxlink/reflector/SatelliteLink.cpp | 8 +- src/svxlink/reflector/TGHandler.cpp | 41 ++++++ src/svxlink/reflector/TGHandler.h | 24 ++++ src/svxlink/reflector/TrunkLink.cpp | 8 +- tests/test_trunk.py | 149 ++++++++++++++++++++++ 9 files changed, 349 insertions(+), 9 deletions(-) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 17720c2..0eb48c7 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -1413,7 +1413,9 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, ReflectorClient::TgFilter(tg), ReflectorClient::mkAndFilter( ReflectorClient::TgMonitorFilter(tg), - ReflectorClient::SelectedTgIdleFilter())))); + ReflectorClient::mkAndFilter( + ReflectorClient::SelectedTgIdleFilter(), + ReflectorClient::EarliestMonitorTalkerFilter(tg)))))); if (m_is_satellite && m_satellite_client != nullptr) { m_satellite_client->onLocalAudio(tg, msg.audioData()); @@ -1581,7 +1583,9 @@ void Reflector::onTalkerUpdated(uint32_t tg, ReflectorClient* old_talker, ReflectorClient::TgFilter(tg), ReflectorClient::mkAndFilter( ReflectorClient::TgMonitorFilter(tg), - ReflectorClient::SelectedTgIdleFilter())), + ReflectorClient::mkAndFilter( + ReflectorClient::SelectedTgIdleFilter(), + ReflectorClient::EarliestMonitorTalkerFilter(tg)))), ReflectorClient::ExceptFilter(old_talker))); if (m_mqtt != nullptr) { @@ -2898,7 +2902,9 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, ReflectorClient::TgFilter(tg), ReflectorClient::mkAndFilter( ReflectorClient::TgMonitorFilter(tg), - ReflectorClient::SelectedTgIdleFilter()))); + ReflectorClient::mkAndFilter( + ReflectorClient::SelectedTgIdleFilter(), + ReflectorClient::EarliestMonitorTalkerFilter(tg))))); if (m_mqtt != nullptr) { m_mqtt->onPeerTalkerStop(peer_id, tg, old_cs); diff --git a/src/svxlink/reflector/ReflectorClient.cpp b/src/svxlink/reflector/ReflectorClient.cpp index 6934f00..567cc76 100644 --- a/src/svxlink/reflector/ReflectorClient.cpp +++ b/src/svxlink/reflector/ReflectorClient.cpp @@ -197,6 +197,86 @@ bool ReflectorClient::SelectedTgIdleFilter::operator()( } /* ReflectorClient::SelectedTgIdleFilter::operator() */ +namespace { +// Look up the earliest of (local talker start, trunk talker start) for a TG. +// Returns true iff at least one was set. Used by EarliestMonitorTalkerFilter. +bool startTimeForTG(uint32_t tg, struct timeval& out) +{ + TGHandler* h = TGHandler::instance(); + struct timeval local_ts, trunk_ts; + bool has_local = h->talkerStartTimeForTG(tg, local_ts); + bool has_trunk = h->trunkTalkerStartTimeForTG(tg, trunk_ts); + if (has_local && has_trunk) + { + out = timercmp(&local_ts, &trunk_ts, <) ? local_ts : trunk_ts; + return true; + } + if (has_local) + { + out = local_ts; + return true; + } + if (has_trunk) + { + out = trunk_ts; + return true; + } + return false; +} +} // namespace + +bool ReflectorClient::EarliestMonitorTalkerFilter::operator()( + ReflectorClient* client) const +{ + if (client->m_monitored_tgs.count(m_tg) == 0) + { + return false; + } + + struct timeval m_tg_ts; + if (!startTimeForTG(m_tg, m_tg_ts)) + { + // m_tg has never had a talker recorded — nothing to deliver. + return false; + } + + uint32_t earliest_tg = m_tg; + struct timeval earliest_ts = m_tg_ts; + + TGHandler* h = TGHandler::instance(); + for (uint32_t tg : client->m_monitored_tgs) + { + if (tg == m_tg) + { + continue; + } + bool active = (h->talkerForTG(tg) != nullptr) || h->hasTrunkTalker(tg); + if (!active) + { + continue; + } + + struct timeval ts; + if (!startTimeForTG(tg, ts)) + { + continue; + } + + bool earlier = timercmp(&ts, &earliest_ts, <); + bool same = !earlier && + ts.tv_sec == earliest_ts.tv_sec && + ts.tv_usec == earliest_ts.tv_usec; + if (earlier || (same && tg < earliest_tg)) + { + earliest_tg = tg; + earliest_ts = ts; + } + } + + return earliest_tg == m_tg; +} /* ReflectorClient::EarliestMonitorTalkerFilter::operator() */ + + ReflectorClient::ReflectorClient(Reflector *ref, Async::FramedTcpConnection *con, Async::Config *cfg) : m_con(con), m_con_state(STATE_EXPECT_PROTO_VER), diff --git a/src/svxlink/reflector/ReflectorClient.h b/src/svxlink/reflector/ReflectorClient.h index fcba3bc..db6cc42 100644 --- a/src/svxlink/reflector/ReflectorClient.h +++ b/src/svxlink/reflector/ReflectorClient.h @@ -210,6 +210,34 @@ class ReflectorClient : public sigc::trackable virtual bool operator ()(ReflectorClient *client) const; }; + /** + * @brief First-talker-wins arbitration for monitor-TG UDP delivery. + * + * Returns true iff the client is monitoring `m_tg` AND `m_tg` is the + * earliest-started TG (local or trunk talker) among this client's + * monitored set. Ties broken by smaller TG id. + * + * At audio fanout time `m_tg` has an active talker by construction. + * At flush fanout time `m_tg`'s talker was just cleared but its start + * timestamp persists in `TGHandler`, so the freshly-stopped TG is + * still considered as a candidate — this delivers the flush to the + * listener that was actually decoding it. + * + * Designed to be ANDed with `TgMonitorFilter(tg)` and + * `SelectedTgIdleFilter` at the seven UDP fanout sites added by + * `92d9a63`. With those two siblings the predicate evaluates only on + * the monitor arm of the OR; the selected-TG arm (`TgFilter(tg)`) + * is unaffected. + */ + class EarliestMonitorTalkerFilter : public Filter + { + public: + EarliestMonitorTalkerFilter(uint32_t tg) : m_tg(tg) {} + virtual bool operator ()(ReflectorClient *client) const; + private: + uint32_t m_tg; + }; + template class AndFilter : public Filter { diff --git a/src/svxlink/reflector/SatelliteClient.cpp b/src/svxlink/reflector/SatelliteClient.cpp index fd92677..ebf428b 100644 --- a/src/svxlink/reflector/SatelliteClient.cpp +++ b/src/svxlink/reflector/SatelliteClient.cpp @@ -367,7 +367,9 @@ void SatelliteClient::handleMsgPeerAudio(std::istream& is) ReflectorClient::TgFilter(msg.tg()), ReflectorClient::mkAndFilter( ReflectorClient::TgMonitorFilter(msg.tg()), - ReflectorClient::SelectedTgIdleFilter()))); + ReflectorClient::mkAndFilter( + ReflectorClient::SelectedTgIdleFilter(), + ReflectorClient::EarliestMonitorTalkerFilter(msg.tg()))))); } /* SatelliteClient::handleMsgPeerAudio */ @@ -381,7 +383,9 @@ void SatelliteClient::handleMsgPeerFlush(std::istream& is) ReflectorClient::TgFilter(msg.tg()), ReflectorClient::mkAndFilter( ReflectorClient::TgMonitorFilter(msg.tg()), - ReflectorClient::SelectedTgIdleFilter()))); + ReflectorClient::mkAndFilter( + ReflectorClient::SelectedTgIdleFilter(), + ReflectorClient::EarliestMonitorTalkerFilter(msg.tg()))))); } /* SatelliteClient::handleMsgPeerFlush */ diff --git a/src/svxlink/reflector/SatelliteLink.cpp b/src/svxlink/reflector/SatelliteLink.cpp index ab09d81..5a42627 100644 --- a/src/svxlink/reflector/SatelliteLink.cpp +++ b/src/svxlink/reflector/SatelliteLink.cpp @@ -387,7 +387,9 @@ void SatelliteLink::handleMsgPeerAudio(std::istream& is) ReflectorClient::TgFilter(tg), ReflectorClient::mkAndFilter( ReflectorClient::TgMonitorFilter(tg), - ReflectorClient::SelectedTgIdleFilter()))); + ReflectorClient::mkAndFilter( + ReflectorClient::SelectedTgIdleFilter(), + ReflectorClient::EarliestMonitorTalkerFilter(tg))))); // Forward to trunk peers m_reflector->forwardSatelliteRawAudioToTrunks(tg, msg.audio()); @@ -412,7 +414,9 @@ void SatelliteLink::handleMsgPeerFlush(std::istream& is) ReflectorClient::TgFilter(tg), ReflectorClient::mkAndFilter( ReflectorClient::TgMonitorFilter(tg), - ReflectorClient::SelectedTgIdleFilter()))); + ReflectorClient::mkAndFilter( + ReflectorClient::SelectedTgIdleFilter(), + ReflectorClient::EarliestMonitorTalkerFilter(tg))))); m_reflector->forwardSatelliteFlushToTrunks(tg); m_reflector->forwardSatelliteFlushToTwin(tg); diff --git a/src/svxlink/reflector/TGHandler.cpp b/src/svxlink/reflector/TGHandler.cpp index 29f5992..8ef2339 100644 --- a/src/svxlink/reflector/TGHandler.cpp +++ b/src/svxlink/reflector/TGHandler.cpp @@ -230,6 +230,13 @@ void TGHandler::setTalkerForTG(uint32_t tg, ReflectorClient* new_talker) } tg_info->sql_timeout_cnt = (new_talker != 0) ? m_sql_timeout : 0; id_map_it->second->talker = new_talker; + if (new_talker != 0) + { + // any → new_talker transition: stamp the talker-start time. Retained + // across the subsequent clear so EarliestMonitorTalkerFilter can + // identify the freshly-stopped TG at flush fanout time. + gettimeofday(&tg_info->talker_start_timestamp, NULL); + } talkerUpdated(tg, old_talker, new_talker); if (tg_info->auto_qsy_after_s > 0) @@ -260,6 +267,22 @@ ReflectorClient* TGHandler::talkerForTG(uint32_t tg) const } /* TGHandler::talkerForTG */ +bool TGHandler::talkerStartTimeForTG(uint32_t tg, struct timeval& out) const +{ + IdMap::const_iterator id_map_it = m_id_map.find(tg); + if (id_map_it == m_id_map.end()) + { + return false; + } + if (!timerisset(&id_map_it->second->talker_start_timestamp)) + { + return false; + } + out = id_map_it->second->talker_start_timestamp; + return true; +} /* TGHandler::talkerStartTimeForTG */ + + uint32_t TGHandler::TGForClient(ReflectorClient* client) { ClientMap::iterator client_map_it = m_client_map.find(client); @@ -288,6 +311,8 @@ void TGHandler::setTrunkTalkerForTG(uint32_t tg, const std::string& callsign) if (callsign.empty()) { m_trunk_talkers.erase(tg); + // Retain m_trunk_talker_start_times[tg] so flush fanout filters can + // identify this freshly-stopped TG. } else { @@ -300,6 +325,9 @@ void TGHandler::setTrunkTalkerForTG(uint32_t tg, const std::string& callsign) return; } m_trunk_talkers[tg] = callsign; + struct timeval now; + gettimeofday(&now, NULL); + m_trunk_talker_start_times[tg] = now; } trunkTalkerUpdated(tg, old, callsign, peer_id); } /* TGHandler::setTrunkTalkerForTG */ @@ -388,6 +416,19 @@ bool TGHandler::hasTrunkTalker(uint32_t tg) const } /* TGHandler::hasTrunkTalker */ +bool TGHandler::trunkTalkerStartTimeForTG(uint32_t tg, + struct timeval& out) const +{ + auto it = m_trunk_talker_start_times.find(tg); + if (it == m_trunk_talker_start_times.end()) + { + return false; + } + out = it->second; + return true; +} /* TGHandler::trunkTalkerStartTimeForTG */ + + bool TGHandler::allowTgSelection(ReflectorClient *client, uint32_t tg) { std::ostringstream ss; diff --git a/src/svxlink/reflector/TGHandler.h b/src/svxlink/reflector/TGHandler.h index 6b07073..9861298 100644 --- a/src/svxlink/reflector/TGHandler.h +++ b/src/svxlink/reflector/TGHandler.h @@ -162,6 +162,16 @@ class TGHandler : public sigc::trackable ReflectorClient* talkerForTG(uint32_t tg) const; + /** + * @brief Look up the wall-clock time (gettimeofday) at which the + * current talker — or, if no talker is currently set, the most + * recent talker — took TG `tg`. The value persists across + * talker-clear so the audio-flush fanout filter can still + * identify the freshly-stopped TG. + * @return true iff a start time has ever been recorded for `tg`. + */ + bool talkerStartTimeForTG(uint32_t tg, struct timeval& out) const; + uint32_t TGForClient(ReflectorClient* client); void setTrunkTalkerForTG(uint32_t tg, const std::string& callsign); @@ -169,6 +179,12 @@ class TGHandler : public sigc::trackable void clearAllTrunkTalkers(void); std::string trunkTalkerForTG(uint32_t tg) const; bool hasTrunkTalker(uint32_t tg) const; + + /** + * @brief Same as `talkerStartTimeForTG` but for trunk-sourced talkers. + * Persists across `clearTrunkTalkerForTG` for the same reason. + */ + bool trunkTalkerStartTimeForTG(uint32_t tg, struct timeval& out) const; const std::map& trunkTalkersSnapshot(void) const { return m_trunk_talkers; @@ -227,6 +243,10 @@ class TGHandler : public sigc::trackable ClientSet clients; ReflectorClient* talker; struct timeval last_talker_timestamp; + // Wall-clock time at which the current (or most recent) talker took + // this TG. Retained across talker-clear so flush fanout can identify + // the freshly-stopped TG. + struct timeval talker_start_timestamp; unsigned sql_timeout_cnt; time_t auto_qsy_after_s; time_t auto_qsy_time; @@ -236,6 +256,7 @@ class TGHandler : public sigc::trackable auto_qsy_time(-1) { timerclear(&last_talker_timestamp); + timerclear(&talker_start_timestamp); } }; typedef std::map IdMap; @@ -246,6 +267,9 @@ class TGHandler : public sigc::trackable ClientMap m_client_map; std::map m_trunk_talkers; std::map m_trunk_talker_peer_ids; // tg -> peer_id + // Wall-clock start time for the current (or most recent) trunk talker. + // Retained across clearTrunkTalkerForTG to support flush filtering. + std::map m_trunk_talker_start_times; Async::Timer m_timeout_timer; unsigned m_sql_timeout; unsigned m_sql_timeout_blocktime; diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 2ee3cd3..d48818b 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -1163,7 +1163,9 @@ void TrunkLink::handleMsgPeerAudio(std::istream& is) ReflectorClient::TgFilter(local_tg), ReflectorClient::mkAndFilter( ReflectorClient::TgMonitorFilter(local_tg), - ReflectorClient::SelectedTgIdleFilter()))); + ReflectorClient::mkAndFilter( + ReflectorClient::SelectedTgIdleFilter(), + ReflectorClient::EarliestMonitorTalkerFilter(local_tg))))); // Forward trunk audio to connected satellites m_reflector->forwardAudioToSatellitesExcept(nullptr, local_tg, msg.audio()); @@ -1203,7 +1205,9 @@ void TrunkLink::handleMsgPeerFlush(std::istream& is) ReflectorClient::TgFilter(local_tg), ReflectorClient::mkAndFilter( ReflectorClient::TgMonitorFilter(local_tg), - ReflectorClient::SelectedTgIdleFilter()))); + ReflectorClient::mkAndFilter( + ReflectorClient::SelectedTgIdleFilter(), + ReflectorClient::EarliestMonitorTalkerFilter(local_tg))))); // Forward trunk flush to connected satellites m_reflector->forwardFlushToSatellitesExcept(nullptr, local_tg); diff --git a/tests/test_trunk.py b/tests/test_trunk.py index d3001b8..bc535da 100644 --- a/tests/test_trunk.py +++ b/tests/test_trunk.py @@ -2910,6 +2910,155 @@ class TestTrunkIntegration(unittest.TestCase): a_client.close() c_client.close() + # ------------------------------------------------------------------ + # Test 43: two monitor TGs simultaneously busy must NOT mix + # ------------------------------------------------------------------ + def test_43_two_monitor_tgs_do_not_mix(self): + """Regression for the multi-monitor-TG mixing gap left open by + 28ebf29. With SELECT_TG=9 idle and MONITOR_TGS=[110, 112], two + simultaneous talkers (on 110 and 112) must NOT both reach the + listener — only the earliest-started one (first-talker-wins). + + Setup (all on PRIMARY reflector): + A: select_tg=9, monitor_tgs=[110, 112] (the listener) + C: select_tg=110, sends audio P_C (starts first) + D: select_tg=112, sends audio P_D (starts ~150 ms later) + + Assertion: every UDP audio payload received by A contains P_C and + none contain P_D. (C started first → C owns the listener's decoder + until C stops; D's frames must be suppressed.) + """ + port = T.mapped_client_port(self.PRIMARY) + + a_client = ClientPeer() + c_client = ClientPeer() + d_client = ClientPeer() + try: + a_client.connect(HOST, port) + a_client.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + a_client.setup_udp(udp_port=port) + a_client.select_tg(9) + a_client.monitor_tgs([110, 112]) + + c_client.connect(HOST, port) + c_client.authenticate(callsign=CLIENT2_CALLSIGN, password=CLIENT2_PASSWORD) + c_client.setup_udp(udp_port=port) + c_client.select_tg(110) + + d_client.connect(HOST, port) + d_client.authenticate(callsign=CLIENT3_CALLSIGN, password=CLIENT3_PASSWORD) + d_client.setup_udp(udp_port=port) + d_client.select_tg(112) + + time.sleep(0.5) + a_client.recv_udp_all(timeout=0.05) + + P_C = b"\xCC\xDD\xCC\xDD" + P_D = b"\xEE\xFF\xEE\xFF" + + # C starts first. + c_client.send_udp_audio(P_C * 40) + time.sleep(0.15) + # Now D joins; both stream interleaved frames. + for _ in range(8): + c_client.send_udp_audio(P_C * 40) + d_client.send_udp_audio(P_D * 40) + time.sleep(0.02) + c_client.send_udp_flush() + d_client.send_udp_flush() + time.sleep(0.5) + + msgs = a_client.recv_udp_all(timeout=1.0) + audio_payloads = [p for t, p in msgs if t == UDP_AUDIO] + + self.assertGreater(len(audio_payloads), 0, + "A received no UDP audio at all — monitor delivery broken") + + mixed = [p for p in audio_payloads if P_D in p] + self.assertEqual(len(mixed), 0, + f"A received {len(mixed)} UDP audio frame(s) carrying the " + f"TG 112 pattern P_D while TG 110 (started first) was still " + f"active — multi-monitor-TG mixing regression. Total audio " + f"frames: {len(audio_payloads)}.") + + self.assertTrue(any(P_C in p for p in audio_payloads), + "A received audio but none of it carried the TG 110 pattern " + "P_C — earliest-talker-wins delivery itself is broken") + finally: + a_client.close() + c_client.close() + d_client.close() + + # ------------------------------------------------------------------ + # Test 44: passive observer with two simultaneous monitor talkers + # ------------------------------------------------------------------ + def test_44_passive_observer_no_monitor_mix(self): + """Same first-talker-wins invariant for a passive observer + (currentTG=0). The earlier code path short-circuited `tg==0` in + SelectedTgIdleFilter, leaving passive observers fully exposed to + multi-monitor mixing. EarliestMonitorTalkerFilter must apply + uniformly. + """ + port = T.mapped_client_port(self.PRIMARY) + + a_client = ClientPeer() + c_client = ClientPeer() + d_client = ClientPeer() + try: + a_client.connect(HOST, port) + a_client.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + a_client.setup_udp(udp_port=port) + a_client.select_tg(0) + a_client.monitor_tgs([110, 112]) + + c_client.connect(HOST, port) + c_client.authenticate(callsign=CLIENT2_CALLSIGN, password=CLIENT2_PASSWORD) + c_client.setup_udp(udp_port=port) + c_client.select_tg(110) + + d_client.connect(HOST, port) + d_client.authenticate(callsign=CLIENT3_CALLSIGN, password=CLIENT3_PASSWORD) + d_client.setup_udp(udp_port=port) + d_client.select_tg(112) + + time.sleep(0.5) + a_client.recv_udp_all(timeout=0.05) + + P_C = b"\xCC\xDD\xCC\xDD" + P_D = b"\xEE\xFF\xEE\xFF" + + c_client.send_udp_audio(P_C * 40) + time.sleep(0.15) + for _ in range(8): + c_client.send_udp_audio(P_C * 40) + d_client.send_udp_audio(P_D * 40) + time.sleep(0.02) + c_client.send_udp_flush() + d_client.send_udp_flush() + time.sleep(0.5) + + msgs = a_client.recv_udp_all(timeout=1.0) + audio_payloads = [p for t, p in msgs if t == UDP_AUDIO] + + self.assertGreater(len(audio_payloads), 0, + "Passive observer received no UDP audio — monitor " + "delivery broken for currentTG=0") + + mixed = [p for p in audio_payloads if P_D in p] + self.assertEqual(len(mixed), 0, + f"Passive observer received {len(mixed)} UDP audio frame(s) " + f"carrying TG 112 pattern P_D while TG 110 (started first) " + f"was still active — multi-monitor-TG mixing regression for " + f"passive observers. Total audio frames: {len(audio_payloads)}.") + + self.assertTrue(any(P_C in p for p in audio_payloads), + "Passive observer received audio but none carried the TG 110 " + "pattern P_C") + finally: + a_client.close() + c_client.close() + d_client.close() + # --------------------------------------------------------------------------- # Custom test runner with clean, readable output