Просмотр исходного кода

fix(video): ZLM自动回收空闲流后关闭回执不再永久卡住

ZLM 会在「流无人观看」时自行回收 RTP server,之后我们的 closeRtpServer
只会得到 code=0/hit=0。原实现把 hit=0 一律当作"未确认关闭",于是该
stream 的停止回执永远停在 CLOSING,canReplaceAllocation() 从此拒绝该通道
的任何新点播——表现为"播一次之后再也播不了"。

hit=0 本身仍不算证据(那是既有正确语义,测试已锁定)。新增
isRtpServerAbsent() 作为正向缺失证据:只有 ZLM 明确回答 code=0 且
exist=false 才把 CLOSING 推进到 CLOSED 并归还 SSRC;节点不可读时保持
未确认。普通 legacy OPEN 若对应的流已被 ZLM 回收,同样按 OPEN→CLOSING→
CLOSED 走完状态机后再分配,未知节点仍然封锁。
Kazerin 3 недель назад
Родитель
Сommit
96584ba184

+ 3 - 0
video-service/src/main/java/com/ruoyi/wvp/media/service/IMediaNodeServerService.java

@@ -61,4 +61,7 @@ public interface IMediaNodeServerService {
 
     List<String> listRtpServer(MediaServer mediaServer);
 
+    /** Positive absence evidence: ZLM answers code=0 and exist=false for this stream. */
+    boolean isRtpServerAbsent(MediaServer mediaServer, String streamId);
+
 }

+ 6 - 0
video-service/src/main/java/com/ruoyi/wvp/media/service/IMediaServerService.java

@@ -149,4 +149,10 @@ public interface IMediaServerService {
     int createRTPServer(MediaServer mediaServerItem, String streamId, long ssrc, Integer port, boolean onlyAuto, boolean disableAudio, boolean reUsePort, Integer tcpMode);
 
     List<String> listRtpServer(MediaServer mediaServer);
+
+    /**
+     * Positive absence evidence for one RTP server: code=0 and exist=false. Returns false when the
+     * node cannot be read or reports any other state, so callers never treat UNKNOWN as stopped.
+     */
+    boolean isRtpServerAbsent(MediaServer mediaServer, String streamId);
 }

+ 11 - 0
video-service/src/main/java/com/ruoyi/wvp/media/service/impl/MediaServerServiceImpl.java

@@ -213,6 +213,17 @@ public class MediaServerServiceImpl implements IMediaServerService {
         return rtpServerPort;
     }
 
+    @Override
+    public boolean isRtpServerAbsent(MediaServer mediaServer, String streamId) {
+        if (mediaServer == null || streamId == null) return false;
+        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
+        if (mediaNodeServerService == null) {
+            log.info("[rtp absence] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
+            return false;
+        }
+        return mediaNodeServerService.isRtpServerAbsent(mediaServer, streamId);
+    }
+
     @Override
     public List<String> listRtpServer(MediaServer mediaServer) {
         IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());

+ 7 - 0
video-service/src/main/java/com/ruoyi/wvp/media/zlm/ZLMMediaNodeServerService.java

@@ -334,6 +334,13 @@ public class ZLMMediaNodeServerService implements IMediaNodeServerService {
         }
     }
 
+    @Override
+    public boolean isRtpServerAbsent(MediaServer mediaServer, String streamId) {
+        JSONObject info = zlmresTfulUtils.getRtpInfo(mediaServer, streamId);
+        return info != null && Integer.valueOf(0).equals(info.getInteger("code"))
+                && Boolean.FALSE.equals(info.getBoolean("exist"));
+    }
+
     @Override
     public List<String> listRtpServer(MediaServer mediaServer) {
         JSONObject jsonObject = zlmresTfulUtils.listRtpServer(mediaServer);

+ 4 - 3
video-service/src/main/java/com/ruoyi/wvp/media/zlm/ZLMServerFactory.java

@@ -31,9 +31,10 @@ public class ZLMServerFactory {
         int result = -1;
         // 查询此rtp server 是否已经存在
         JSONObject rtpInfo = zlmresTfulUtils.getRtpInfo(mediaServerItem, streamId);
-        if(rtpInfo.getInteger("code") == 0){
-            if (rtpInfo.getBoolean("exist")) {
-                result = rtpInfo.getInteger("local_port");
+        if(rtpInfo != null && Integer.valueOf(0).equals(rtpInfo.getInteger("code"))){
+            if (Boolean.TRUE.equals(rtpInfo.getBoolean("exist"))) {
+                Integer existingPort = rtpInfo.getInteger("local_port");
+                result = existingPort == null ? 0 : existingPort;
                 if (result == 0) {
                     // 此时说明rtpServer已经创建但是流还没有推上来
                     // 此时重新打开rtpServer

+ 65 - 3
video-service/src/main/java/com/ruoyi/wvp/service/impl/RtpServerServiceImpl.java

@@ -172,11 +172,62 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         } catch (RuntimeException ex) {
             log.warn("[RTP close] {}/{} remains pending: {}", node.getId(), info.getStream(), ex.getMessage());
         }
+        // ZLM reclaims an idle RTP server on its own (on_stream_none_reader), so the name-close above
+        // answers hit=0 even though the resource is genuinely gone. Without this the allocation would
+        // sit in CLOSING for ever and canReplaceAllocation() would reject every later play on the
+        // channel. hit=0 alone is still not evidence: finish only when ZLM positively reports the
+        // server absent, and stay unresolved when the node cannot be read.
+        if (!info.getStream().startsWith("managed_") && serverAbsent(node, info.getStream())) {
+            if (allocationState(node, info, RtpState.CLOSING, RtpState.CLOSED, actorGuard)) {
+                try { releaseClosedSsrc(node, info); }
+                catch (RuntimeException ex) { log.warn("[RTP close reclaimed] {}/{}: {}", 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;
     }
 
+    /**
+     * Positive absence evidence from ZLM: the query must answer code=0 and say the server does not
+     * exist. A failed request or a non-zero code is UNKNOWN and must never unlock the allocation.
+     */
+    private boolean serverAbsent(MediaServer node, String stream) {
+        try {
+            return mediaServerService.isRtpServerAbsent(node, stream);
+        } catch (RuntimeException ex) {
+            log.warn("[RTP absence check] {}/{} unreadable: {}", node.getId(), stream, ex.getMessage());
+            return false;
+        }
+    }
+    /**
+     * Retire a legacy allocation whose stream ZLM no longer holds, so the channel can be played again.
+     * Only callers that already have positive absence evidence may reach this.
+     */
+    private boolean retireStaleAllocation(MediaServer node, String stream) {
+        try {
+            // ZLM positively reports this stream gone, so whatever the receipt still says about
+            // callId or bound viewers describes a handle that no longer exists. The state machine
+            // only permits OPEN -> CLOSING -> CLOSED, so walk both steps rather than jump.
+            Snapshot closing = stopReceipts.update(node.getId(), stream, snapshot -> {
+                if (snapshot.allocation == null || snapshot.allocation.state != RtpState.OPEN) return null;
+                // Play evidence is immutable once recorded; only the allocation state moves.
+                snapshot.allocation.state = RtpState.CLOSING;
+                return snapshot;
+            });
+            if (closing == null) return false;
+            Snapshot retired = stopReceipts.update(node.getId(), stream, snapshot -> {
+                if (snapshot.allocation == null || snapshot.allocation.state != RtpState.CLOSING) return null;
+                snapshot.allocation.state = RtpState.CLOSED;
+                return snapshot;
+            });
+            return retired != null;
+        } catch (RuntimeException ex) {
+            log.warn("[RTP stale retire] {}/{}: {}", node.getId(), stream, ex.getMessage());
+            return false;
+        }
+    }
+
     private boolean cancelled(String stream) {
         // Managed resource creation fails closed without the cancellation persistence seam.
         return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
@@ -406,9 +457,20 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         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;
+            // A viewer that went away without a clean stop leaves the previous allocation OPEN while
+            // ZLM has already reclaimed the idle stream. That is a dead handle, not a live lease: once
+            // ZLM positively reports the stream gone, retire the stale allocation and allocate again.
+            // An unreadable node stays fenced, so UNKNOWN never unlocks the name.
+            if (!rtpServerParam.getMediaServerItem().getId().isEmpty()
+                    && serverAbsent(rtpServerParam.getMediaServerItem(), streamId)
+                    && retireStaleAllocation(rtpServerParam.getMediaServerItem(), streamId)
+                    && reserveAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo, rtpServerParam.getPresetSsrc() != null)) {
+                legacyRtp.put(allocationKey, entry);
+            } else {
+                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)) {