package com.ruoyi.wvp.service.impl; import com.ruoyi.wvp.common.InviteInfo; import com.ruoyi.wvp.conf.DynamicTask; import com.ruoyi.wvp.conf.UserSetting; import com.ruoyi.wvp.gb28181.bean.OpenRTPServerResult; import com.ruoyi.wvp.gb28181.bean.SsrcTransaction; import com.ruoyi.wvp.gb28181.session.SSRCFactory; import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager; import com.ruoyi.wvp.media.bean.MediaServer; import com.ruoyi.wvp.media.event.hook.Hook; import com.ruoyi.wvp.media.event.hook.HookSubscribe; import com.ruoyi.wvp.media.event.hook.HookType; import com.ruoyi.wvp.media.event.media.MediaArrivalEvent; import com.ruoyi.wvp.media.event.media.MediaDepartureEvent; import com.ruoyi.wvp.media.service.IMediaServerService; import com.ruoyi.wvp.service.IReceiveRtpServerService; import com.ruoyi.wvp.service.bean.ErrorCallback; import com.ruoyi.wvp.service.bean.InviteErrorCode; import com.ruoyi.wvp.service.bean.RTPServerParam; import com.ruoyi.wvp.service.bean.SSRCInfo; import com.zksy.video.lifecycle.VideoStopReceipts; import com.zksy.video.lifecycle.VideoStopReceipts.Allocation; import com.zksy.video.lifecycle.VideoStopReceipts.RtpState; import com.zksy.video.lifecycle.VideoStopReceipts.Snapshot; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.util.Objects; import java.util.UUID; import java.util.function.Predicate; @Slf4j @Service public class RtpServerServiceImpl implements IReceiveRtpServerService { @Autowired private IMediaServerService mediaServerService; @Autowired private DynamicTask dynamicTask; @Autowired private SSRCFactory ssrcFactory; @Autowired private UserSetting userSetting; @Autowired private HookSubscribe subscribe; @Autowired private SipInviteSessionManager sessionManager; /** * 流到来的处理 */ @Async("taskExecutor") @EventListener public void onApplicationEvent(MediaArrivalEvent event) { } /** * 流离开的处理 */ @Async("taskExecutor") @EventListener public void onApplicationEvent(MediaDepartureEvent event) { } @Autowired private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore; @Autowired private VideoStopReceipts stopReceipts; // Only callback/timer ownership is local. No field here is stop evidence. private final java.util.concurrent.ConcurrentMap managedRtp = new java.util.concurrent.ConcurrentHashMap<>(); private static final class ManagedRtp { private final SSRCInfo info; private HookSubscribe.Subscription owner; private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean(); private ManagedRtp(SSRCInfo info) { this.info = info; } } private String managedKey(MediaServer node, String stream) { return Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId()).toString(); } private boolean reserveAllocation(MediaServer node, SSRCInfo info, boolean externalSsrc) { if (stopReceipts == null) return false; return stopReceipts.update(node.getId(), info.getStream(), snapshot -> { if (!snapshot.canReplaceAllocation()) return null; if (info.getStream().startsWith("managed_") && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null; Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey(); allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.INTENT; allocation.poolTracked = !externalSsrc; allocation.externalSsrc = externalSsrc; snapshot.allocation = allocation; VideoStopReceipts.Play play = snapshot.plays.get(info.getStream()); if (play != null) play.allocationToken = allocation.token; return snapshot; }) != null; } private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next) { return allocationState(node, info, expected, next, snapshot -> true); } private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next, Predicate actorGuard) { if (stopReceipts == null) return false; for (int attempt = 0; attempt < 4; attempt++) { Snapshot updated = stopReceipts.update(node.getId(), info.getStream(), snapshot -> { Allocation allocation = snapshot.allocation; if (allocation == null || !allocation.matches(info) || allocation.state != expected || !actorGuard.test(snapshot)) return null; if (next == RtpState.CREATING && info.getStream().startsWith("managed_") && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null; allocation.state = next; allocation.port = info.getPort(); return snapshot; }); if (updated != null) return true; Snapshot latest = stopReceipts.read(node.getId(), info.getStream()); if (latest == null || latest.allocation == null || !latest.allocation.matches(info) || latest.allocation.state != expected) return false; } return false; } private boolean closeAllocation(MediaServer node, SSRCInfo info) { return closeAllocation(node, info, snapshot -> true); } private boolean closeAllocation(MediaServer node, SSRCInfo info, Predicate actorGuard) { if (stopReceipts == null || info == null || info.getStream() == null || info.getTimeOutTaskKey() == null || info.getSsrc() == null || !"rtp".equals(info.getApp())) return false; Snapshot retained = stopReceipts.read(node.getId(), info.getStream()); if ((retained == null || retained.allocation == null) && !info.getStream().startsWith("managed_")) { // Pre-upgrade legacy callers retain the original typed allocation. Never replace a newer token, // reconstruct a managed/adopted receipt, or treat absence as a positive stop acknowledgement. retained = stopReceipts.update(node.getId(), info.getStream(), snapshot -> { if (snapshot.allocation != null || !snapshot.plays.isEmpty() || !actorGuard.test(snapshot) || (sessionManager != null && sessionManager.isAdoptedAllocation(node.getId(), info))) return null; Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey(); allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.OPEN; snapshot.allocation = allocation; return snapshot; }); } if (retained == null || retained.allocation == null || !retained.allocation.matches(info) || !actorGuard.test(retained)) return false; if (retained.allocation.terminal()) return true; if (retained.allocation.state == RtpState.INTENT) { // CAS competes with the creator's INTENT -> CREATING, so this is positive never-created evidence. return allocationState(node, info, RtpState.INTENT, RtpState.NEVER_CREATED, actorGuard); } // A process lost during create/close cannot infer completion or send another name-based command. if (!allocationState(node, info, RtpState.OPEN, RtpState.CLOSING, actorGuard)) return false; try { mediaServerService.closeRTPServer(node, info.getStream(), closed -> { // Boolean true is the ZLM adapter's code=0/hit=1 receipt, not a request-send result. // Retry only shared state CAS inside allocationState, never the external name-close. if (!Boolean.TRUE.equals(closed)) return; if (!allocationState(node, info, RtpState.CLOSING, RtpState.CLOSED)) return; // A late positive receipt must finish pool cleanup even when the caller already // returned and no second stop is ever issued. try { releaseClosedSsrc(node, info); } catch (RuntimeException ex) { log.warn("[RTP close return] {}/{}: {}", node.getId(), info.getStream(), ex.getMessage()); } }); } catch (RuntimeException ex) { log.warn("[RTP close] {}/{} remains pending: {}", node.getId(), info.getStream(), ex.getMessage()); } Snapshot after = stopReceipts.read(node.getId(), info.getStream()); return after != null && after.allocation != null && after.allocation.matches(info) && after.allocation.state == RtpState.CLOSED; } private boolean cancelled(String stream) { // Managed resource creation fails closed without the cancellation persistence seam. return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream); } private SSRCInfo openManagedRtp(RTPServerParam param, ErrorCallback callback) { MediaServer node = param.getMediaServerItem(); String stream = param.getStreamId(); if (callback == null || node == null || node.getId() == null || !node.isRtpEnable() || !stream.matches("managed_[0-9a-fA-F]{32}") || cancelled(stream)) { if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP requires a unique stream, multi-port node and live generation", null); return null; } // The stream is a single-use generation identity; use it for the pool request too, // so cancellation can fence/recover an acquisition whose reply was lost before RTP registration. ManagedRtp entry = new ManagedRtp(new SSRCInfo(0, null, "rtp", stream, stream)); if (managedRtp.putIfAbsent(managedKey(node, stream), entry) != null) { callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP generation already allocated", null); return null; } try { entry.info.setSsrc(ssrcFactory.getPlaySsrc(node.getId(), entry.info.getTimeOutTaskKey())); if (!reserveAllocation(node, entry.info, false)) { Snapshot current = stopReceipts.read(node.getId(), stream); if (current == null || current.allocation == null || !current.allocation.matches(entry.info)) releaseManagedSsrc(node, entry); callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation is already retained", null); return null; } if (cancelled(stream)) { closeManagedRTPServer(node, entry.info); return null; } if (!allocationState(node, entry.info, RtpState.INTENT, RtpState.CREATING)) { closeManagedRTPServer(node, entry.info); return null; } int port = mediaServerService.createRTPServer(node, stream, param.isSsrcCheck() ? Long.parseLong(entry.info.getSsrc()) : 0, 0, false, param.isDisableAudio(), false, param.getTcpMode()); entry.info.setPort(port); // Only the creator knows create returned. Restart during create remains CREATING. if (!allocationState(node, entry.info, RtpState.CREATING, RtpState.OPEN)) { // The port was already created above. A failed receipt transition must not leak it: // close the exact allocation instead of returning silently. closeManagedRTPServer(node, entry.info); callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP receipt not acknowledged", null); return null; } if (port <= 0 || cancelled(stream) || entry.terminal.get()) { closeManagedRTPServer(node, entry.info); callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation failed or was cancelled", null); return null; } OpenRTPServerResult result = new OpenRTPServerResult(); result.setSsrcInfo(entry.info); Hook hook = Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId()); entry.owner = subscribe.addOwnedSubscribe(hook, data -> { if (data.getMediaServer() == null || !node.getId().equals(data.getMediaServer().getId()) || !stream.equals(data.getStream()) || !"rtp".equals(data.getApp()) || data.getMediaInfo() == null || !stream.equals(data.getMediaInfo().getStream()) || !"rtp".equals(data.getMediaInfo().getApp()) || (data.getMediaInfo().getMediaServer() != null && !node.getId().equals(data.getMediaInfo().getMediaServer().getId()))) return; if (!entry.terminal.compareAndSet(false, true)) return; try { dynamicTask.stop(entry.info.getTimeOutTaskKey()); if (cancelled(stream)) { closeManagedRTPServer(node, entry.info); callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", result); return; } result.setHookData(data); callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), result); } finally { subscribe.removeOwnedSubscribe(entry.owner); } }); if (entry.terminal.get()) subscribe.removeOwnedSubscribe(entry.owner); dynamicTask.startDelay(entry.info.getTimeOutTaskKey(), () -> { if (!entry.terminal.compareAndSet(false, true)) return; try { closeManagedRTPServer(node, entry.info); } finally { callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), "Managed RTP timed out", result); } }, userSetting.getPlayTimeout()); // Cancellation may have raced creation/registration. Never hand out that resource. if (cancelled(stream)) { closeManagedRTPServer(node, entry.info); callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", result); return null; } if (entry.terminal.get()) dynamicTask.stop(entry.info.getTimeOutTaskKey()); return entry.info; } catch (RuntimeException ex) { // An ambiguous create/receipt write is not proof that the port never existed. closeManagedRTPServer(node, entry.info); callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation uncertain: " + ex.getMessage(), null); return null; } } private void releaseManagedSsrc(MediaServer node, ManagedRtp entry) { if (entry.info.getSsrc() != null) { ssrcFactory.releaseSsrc(node.getId(), entry.info.getSsrc(), entry.info.getTimeOutTaskKey()); } } /** A completed port close is not full cleanup until its pool allocation was returned. * The Factory receipt is atomic with SADD and remains valid after the SN is reused. */ private boolean releaseClosedSsrc(MediaServer node, SSRCInfo info) { Snapshot snapshot = stopReceipts.read(node.getId(), info.getStream()); if (snapshot == null || snapshot.allocation == null || !snapshot.allocation.matches(info) || !snapshot.allocation.terminal()) return false; Allocation allocation = snapshot.allocation; if (allocation.externalSsrc || allocation.poolSsrc() == null || allocation.poolReturned) return true; String poolSsrc = allocation.poolSsrc(), token = allocation.token; if (ssrcFactory.wasReleased(node.getId(), poolSsrc, token)) return true; // Return the originally allocated number, never a device-negotiated SSRC. boolean released = allocation.poolTracked ? ssrcFactory.releaseSsrc(node.getId(), poolSsrc, token) : ssrcFactory.releaseObservedLegacySsrc(node.getId(), poolSsrc, token); return released || ssrcFactory.wasReleased(node.getId(), poolSsrc, token); } @Override public boolean closeManagedRTPServer(MediaServer node, SSRCInfo info) { if (node == null || node.getId() == null || info == null || info.getStream() == null || !info.getStream().matches("managed_[0-9a-fA-F]{32}")) return false; if (stopReceipts != null) { Snapshot pending = stopReceipts.read(node.getId(), info.getStream()); VideoStopReceipts.Play intent = pending == null ? null : pending.plays.get(info.getStream()); if (pending != null && pending.allocation == null && intent != null && intent.cancelled && !intent.inviteSent && info.getStream().equals(info.getTimeOutTaskKey())) return ssrcFactory.cancelAllocation(node.getId(), info.getStream()); } ManagedRtp entry = managedRtp.get(managedKey(node, info.getStream())); if (entry != null) { entry.terminal.set(true); try { if (entry.info.getTimeOutTaskKey() != null) dynamicTask.stop(entry.info.getTimeOutTaskKey()); } catch (RuntimeException ex) { log.warn("[Managed timer close] {}: {}", info.getStream(), ex.getMessage()); } finally { subscribe.removeOwnedSubscribe(entry.owner); } } boolean closed = closeAllocation(node, info); return closed && releaseClosedSsrc(node, info); } /** Unlike managed UUIDs, legacy names can be allocated again. Keep the allocation token, not a name receipt. */ private final java.util.Map legacyRtp = new java.util.concurrent.ConcurrentHashMap<>(); private static final class LegacyRtp { private final SSRCInfo info; private HookSubscribe.Subscription owner; private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean(); private LegacyRtp(SSRCInfo info) { this.info = info; } } @Override public synchronized boolean closeAdoptedRTPServer(MediaServer node, SSRCInfo info, String callId) { if (node == null || node.getId() == null || !node.isRtpEnable() || info == null || info.getStream() == null || info.getStream().startsWith("managed_") || !"rtp".equals(info.getApp()) || info.getSsrc() == null || info.getTimeOutTaskKey() == null || callId == null || sessionManager == null || stopReceipts == null || !sessionManager.isAdoptedRtp(node.getId(), callId, info)) return false; String key = managedKey(node, info.getStream()); LegacyRtp entry = legacyRtp.get(key); if (entry != null && !entry.info.equals(info)) entry = null; // stale local timer owner is not allocation evidence com.ruoyi.wvp.gb28181.bean.SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", info.getStream()); if (current != null && (!callId.equals(current.getCallId()) || !info.getSsrc().equals(current.getSsrc()) || !node.getId().equals(current.getMediaServerId()) || !sessionManager.isAdopted(current))) return false; Snapshot retained = stopReceipts.read(node.getId(), info.getStream()); if (retained == null || retained.allocation == null || !retained.allocation.matches(info) || !callId.equals(retained.allocation.callId)) return false; com.ruoyi.wvp.gb28181.bean.SsrcTransaction expected = retained.plays.values().stream() .filter(play -> java.util.Objects.equals(play.allocationToken, info.getTimeOutTaskKey()) && play.dialog != null && callId.equals(play.dialog.getCallId())) .map(play -> play.dialog).findFirst().orElse(null); if (expected == null || !sessionManager.isAdopted(expected) || (current != null && !SipInviteSessionManager.sameDialog(expected, current))) return false; if (entry != null) entry.terminal.set(true); try { dynamicTask.stop(info.getTimeOutTaskKey()); } catch (RuntimeException ex) { log.warn("[Adopted timer close] {}: {}", info.getStream(), ex.getMessage()); } finally { if (entry != null) subscribe.removeOwnedSubscribe(entry.owner); } boolean closed = closeAllocation(node, info, snapshot -> originalActor(snapshot, info, expected)); return closed && releaseClosedSsrc(node, info); } @Override public SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback callback) { if (rtpServerParam.getStreamId() != null && rtpServerParam.getStreamId().startsWith("managed_")) { return openManagedRtp(rtpServerParam, callback); } return openLegacyRtp(rtpServerParam, callback); } private synchronized SSRCInfo openLegacyRtp(RTPServerParam rtpServerParam, ErrorCallback callback) { if (callback == null) { log.warn("[开启RTP收流] 失败,回调为NULL"); return null; } if (rtpServerParam.getMediaServerItem() == null) { log.warn("[开启RTP收流] 失败,媒体节点为NULL"); return null; } // 获取mediaServer可用的ssrc final String timeOutTaskKey = UUID.randomUUID().toString(); final String ssrc; if (rtpServerParam.getPresetSsrc() != null) { ssrc = rtpServerParam.getPresetSsrc(); }else { if (rtpServerParam.isPlayback()) { ssrc = ssrcFactory.getPlayBackSsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey); }else { ssrc = ssrcFactory.getPlaySsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey); } } final String streamId; if (rtpServerParam.getStreamId() == null) { streamId = String.format("%08x", Long.parseLong(ssrc)).toUpperCase(); }else { streamId = rtpServerParam.getStreamId(); } if (rtpServerParam.isSsrcCheck() && rtpServerParam.getTcpMode() > 0) { // 目前zlm不支持 tcp模式更新ssrc,暂时关闭ssrc校验 log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc,但是tcp模式zlm收流目前无法更新ssrc,可能收流超时,此时请使用udp收流或者关闭ssrc校验"); } // Register BEFORE create: even an in-flight replacement invalidates the previous close receipt. SSRCInfo ssrcInfo = new SSRCInfo(0, ssrc, "rtp", streamId, timeOutTaskKey); LegacyRtp entry = new LegacyRtp(ssrcInfo); String allocationKey = managedKey(rtpServerParam.getMediaServerItem(), streamId); if (!reserveAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo, rtpServerParam.getPresetSsrc() != null)) { if (rtpServerParam.getPresetSsrc() == null) ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey); callback.run(InviteErrorCode.FAIL.getCode(), "Adopted RTP close is still pending", null); return null; } legacyRtp.put(allocationKey, entry); if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.INTENT, RtpState.CREATING)) { closeAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo); return null; } int rtpServerPort; if (rtpServerParam.getMediaServerItem().isRtpEnable()) { rtpServerPort = mediaServerService.createRTPServer(rtpServerParam.getMediaServerItem(), streamId, rtpServerParam.isSsrcCheck() ? Long.parseLong(ssrc) : 0, rtpServerParam.getPort(), rtpServerParam.isOnlyAuto(), rtpServerParam.isDisableAudio(), rtpServerParam.isReUsePort(), rtpServerParam.getTcpMode()); } else { rtpServerPort = rtpServerParam.getMediaServerItem().getRtpProxyPort(); } ssrcInfo.setPort(rtpServerPort); if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.CREATING, RtpState.OPEN)) { // A created port must be closed even when the receipt transition did not commit. closeAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo); callback.run(InviteErrorCode.FAIL.getCode(), "RTP receipt not acknowledged", null); return null; } if (rtpServerPort == 0) { callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "开启RTPServer失败", null); // 释放ssrc if (rtpServerParam.getPresetSsrc() == null) { ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey); } return null; } OpenRTPServerResult openRTPServerResult = new OpenRTPServerResult(); openRTPServerResult.setSsrcInfo(ssrcInfo); Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, ssrcInfo.getApp(), streamId, rtpServerParam.getMediaServerItem().getId()); dynamicTask.startDelay(timeOutTaskKey, () -> { if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return; // Close through the shared allocation fence; never release an unknown allocation's SSRC early. closeRTPServer(rtpServerParam.getMediaServerItem(), ssrcInfo); subscribe.removeOwnedSubscribe(entry.owner); callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), openRTPServerResult); }, userSetting.getPlayTimeout()); // 开启流到来的监听 entry.owner = subscribe.addOwnedSubscribe(rtpHook, (hookData) -> { if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return; dynamicTask.stop(timeOutTaskKey); // hook响应 openRTPServerResult.setHookData(hookData); try { callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), openRTPServerResult); } finally { subscribe.removeOwnedSubscribe(entry.owner); } }); if (entry.terminal.get()) subscribe.removeOwnedSubscribe(entry.owner); return ssrcInfo; } /** Peer BYE/offline must use the original Invite and dialog, never the name's current allocation. */ public boolean closeRTPServerForSession(SsrcTransaction original, InviteInfo invite) { if (original == null || sessionManager == null || stopReceipts == null || !SipInviteSessionManager.sameDialog(original, sessionManager.getSsrcTransactionByStream(original.getApp(), original.getStream()))) return false; SSRCInfo info = invite == null ? sessionManager.getAdoptedAllocation(original) : invite.getSsrcInfo(); if (info == null || !Objects.equals(original.getApp(), info.getApp()) || !Objects.equals(original.getStream(), info.getStream()) || !Objects.equals(original.getSsrc(), info.getSsrc()) || (invite != null && (!Objects.equals(original.getMediaServerId(), invite.getMediaServerId()) || !Objects.equals(original.getDeviceId(), invite.getDeviceId()) || !Objects.equals(original.getChannelId(), invite.getChannelId()) || original.getType() != invite.getType() || !Objects.equals(original.getStream(), invite.getStream())))) return false; MediaServer node = mediaServerService.getOne(original.getMediaServerId()); if (node == null || !Objects.equals(original.getMediaServerId(), node.getId())) return false; if (info.getStream().startsWith("managed_")) { if (!stopReceipts.retainDialog(original)) return false; return closeManagedRTPServer(node, info); } if (sessionManager.isAdopted(original)) return closeAdoptedRTPServer(node, info, original.getCallId()); return closeLegacyRtp(node, info, snapshot -> originalActor(snapshot, info, original)); } private boolean originalActor(Snapshot snapshot, SSRCInfo info, SsrcTransaction original) { return (snapshot.allocation == null || snapshot.allocation.callId == null || Objects.equals(snapshot.allocation.callId, original.getCallId())) && snapshot.plays.values().stream().noneMatch(play -> Objects.equals(play.allocationToken, info.getTimeOutTaskKey()) && play.dialog != null && !SipInviteSessionManager.sameDialog(original, play.dialog)); } @Override public void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) { if (ssrcInfo != null && ssrcInfo.getStream() != null && ssrcInfo.getStream().startsWith("managed_")) { closeManagedRTPServer(mediaServer, ssrcInfo); return; } closeLegacyRtp(mediaServer, ssrcInfo, snapshot -> true); } private boolean closeLegacyRtp(MediaServer mediaServer, SSRCInfo ssrcInfo, Predicate actorGuard) { if (mediaServer == null || mediaServer.getId() == null || ssrcInfo == null || ssrcInfo.getStream() == null) return false; if (ssrcInfo.getTimeOutTaskKey() != null) dynamicTask.stop(ssrcInfo.getTimeOutTaskKey()); LegacyRtp entry = legacyRtp.get(managedKey(mediaServer, ssrcInfo.getStream())); if (entry != null && entry.info.equals(ssrcInfo)) { entry.terminal.set(true); subscribe.removeOwnedSubscribe(entry.owner); } boolean closed = closeAllocation(mediaServer, ssrcInfo, actorGuard); return closed && releaseClosedSsrc(mediaServer, ssrcInfo); } }